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 Mojo::IOLoop::Stream;
23 use vars qw($now %conns $noconns $cnum $total_in $total_out $connect_timeout $disc_waittime);
25 $total_in = $total_out = 0;
36 #-----------------------------------------------------------------
37 # Generalised initializer
41 my ($pkg, $rproc) = @_;
43 my $class = $obj || $pkg;
54 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
59 dbg("$class Connection created (total $noconns)") if isdbg('connll');
60 return bless $conn, $class;
67 $conn->{sock}->on(error => sub {$callback->($_[1]);});
74 $conn->{sock}->on(close => sub {$callback->()});
81 $conn->{rproc} = $callback;
92 $call = $pkg->{call} unless $call;
93 return undef unless $call;
94 dbg((ref $pkg) . " changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
95 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
97 $ref = $conns{$call} = $pkg;
98 dbg((ref $pkg) . " Connection $pkg->{cnum} $call stored") if isdbg('connll');
100 $ref = $conns{$call};
105 # this is only called by any dependent processes going away unexpectedly
108 my ($pkg, $pid) = @_;
110 my @pid = grep {$_->{pid} == $pid} values %conns;
111 foreach my $p (@pid) {
112 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
120 return $conn->{csort} eq 'ax25';
126 unless ($conn->{peerhost}) {
127 $conn->{peerhost} ||= 'ax25' if $conn->ax25;
128 $conn->{peerhost} ||= $conn->{sock}->handle->peerhost if $conn->{sock};
129 $conn->{peerhost} ||= 'UNKNOWN';
131 return $conn->{peerhost};
134 #-----------------------------------------------------------------
142 my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
143 $sock->on(read => sub {$conn->_rcv($_[1]);} );
144 $sock->on(error => sub {delete $conn->{sock}; $conn->disconnect;});
145 $sock->on(close => sub {delete $conn->{sock}; $conn->disconnect;});
148 $conn->{peerhost} = eval { $handle->peerhost; };
149 dbg((ref $conn) . " connected $conn->{cnum} to $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg ('connect');
150 if ($conn->{on_connect}) {
151 &{$conn->{on_connect}}($conn, $handle);
158 my $sock = $conn->{sock};
159 return ref $sock && $sock->isa('Mojo::IOLoop::Stream');
163 my ($pkg, $to_host, $to_port, %args) = @_;
164 my $timeout = delete $args{timeout} || $connect_timeout;
166 # Create a connection end-point object
169 my $rproc = delete $args{rproc};
170 $conn = $pkg->new($rproc);
172 $conn->{peerhost} = $to_host;
173 $conn->{peerport} = $to_port;
174 $conn->{sort} = 'Outgoing';
176 dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
179 $conn->{sock} = $sock = Mojo::IOLoop::Client->new;
180 $sock->on(connect => sub {
181 $conn->_on_connect($_[1])
183 $sock->on(error => sub {
184 &{$conn->{eproc}}($conn, $_[1]) if exists $conn->{eproc};
185 delete $conn->{sock};
188 $sock->on(close => sub {
189 delete $conn->{sock};
193 # copy any args like on_connect, on_disconnect etc
194 while (my ($k, $v) = each %args) {
198 $sock->connect(address => $to_host, port => $to_port, timeout => $timeout);
205 my ($conn, $line, $sort) = @_;
208 # local $^F = 10000; # make sure it ain't closed on exec
209 # my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
214 # if (defined $pid) {
217 # $conn->{sock} = $a;
218 # $conn->{csort} = $sort;
219 # $conn->{lineend} = "\cM" if $sort eq 'ax25';
220 # $conn->{pid} = $pid;
221 # if ($conn->{rproc}) {
222 # my $callback = sub {$conn->_rcv};
223 # Msg::set_event_handler ($a, read => $callback);
225 # dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
232 # *STDIN = IO::File->new_from_fd($b, 'r') or die;
233 # *STDOUT = IO::File->new_from_fd($b, 'w') or die;
234 # *STDERR = IO::File->new_from_fd($b, 'w') or die;
236 # unless ($main::is_win) {
237 # # $SIG{HUP} = 'IGNORE';
238 # $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
241 # exec "$line" or dbg("exec '$line' failed $!");
244 # dbg("cannot fork for $line");
247 # dbg("no socket pair $! for $line");
255 my $count = $conn->{disconnecting}++;
256 my $dbg = isdbg('connll');
257 my ($pkg, $fn, $line) = caller if $dbg;
260 dbgtrace((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line FORCING CLOSE ") if $dbg;
264 dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ") if $dbg;
267 # remove this conn from the active queue
268 # be careful to delete the correct one
270 if ($call = $conn->{call}) {
271 my $ref = $conns{$call};
272 delete $conns{$call} if $ref && $ref == $conn;
274 $call ||= 'unallocated';
276 $delqueue{$conn} = $conn; # save this connection until everything is finished
277 my $sock = $conn->{sock};
279 if ($sock->{buffer}) {
280 my $lth = length $sock->{buffer};
281 Mojo::IOLoop->timer($disc_waittime, sub {
282 dbg("Buffer contained $lth characters, coordinated for $disc_waittime secs, now disconnecting $call") if $dbg;
286 dbg("Buffer empty, just close $call") if $dbg;
290 dbg((ref $conn) . " socket missing on $conn->{call}") if $dbg;
298 my $sock = delete $conn->{sock};
299 $conn->{state} = 'E';
300 $conn->{timeout}->del if $conn->{timeout};
302 my $call = $conn->{call};
304 if (isdbg('connll')) {
305 my ($pkg, $fn, $line) = caller;
306 dbg((ref $conn) . "::_close_it on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ");
310 dbg((ref $conn) . " Connection $conn->{cnum} $call starting to close") if isdbg('connll');
312 if ($conn->{on_disconnect}) {
313 &{$conn->{on_disconnect}}($conn);
317 dbg((ref $conn) . " Connection $conn->{cnum} $call closing gracefully") if isdbg('connll');
318 $sock->close_gracefully;
321 # get rid of any references
323 if (ref($conn->{$_})) {
328 delete $delqueue{$conn}; # finally remove the $conn
330 unless ($main::is_win) {
331 kill 'TERM', $conn->{pid} if exists $conn->{pid};
338 my $rq = $conn->{outqueue};
339 my $sock = $conn->{sock};
340 return unless defined $sock;
341 return if $conn->{disconnecting};
344 my $data = shift @$rq;
345 my $lth = length $data;
346 my $call = $conn->{call} || 'none';
348 dbgdump('raw', "$call send $lth:", $data);
354 dbg("_send_stuff $call ending data ignored: $data");
360 my ($conn, $msg) = @_;
361 $conn->enqueue($msg);
371 my ($conn, $msg) = @_;
372 push @{$conn->{outqueue}}, $msg;
378 push @{$conn->{outqueue}}, defined $_[0] ? $_[0] : '';
389 $conn->{sock}->on(drain => sub {$conn->disconnect;});
392 #-----------------------------------------------------------------
393 # Receive side routines
397 # @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
398 my ($pkg, $my_host, $my_port, $login_proc) = @_;
399 my $conn = $pkg->new($login_proc);
401 my $sock = $conn->{sock} = Mojo::IOLoop::Server->new;
402 $sock->on(accept=>sub{$conn->new_client($_[1]);});
403 $sock->listen(address=>$my_host, port=>$my_port);
406 die "Could not create socket: $! \n" unless $conn->{sock};
419 return if $conn->{disconnecting};
421 if ($conn->{msg} =~ /\cJ/) {
422 my @lines = split /\cM?\cJ/, $conn->{msg};
423 if ($conn->{msg} =~ /\cM?\cJ$/) {
426 $conn->{msg} = pop @lines;
429 last if $conn->{disconnecting};
430 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
435 sub _rcv { # Complement to _send
436 my $conn = shift; # $rcv_now complement of $flush
438 my $sock = $conn->{sock};
439 return unless defined($sock);
440 return if $conn->{disconnecting};
442 $total_in += length $msg;
446 my $call = $conn->{call} || 'none';
447 my $lth = length $msg;
448 dbgdump('raw', "$call read $lth: ", $msg);
451 my @ch = split //, $msg;
456 $conn->{msg} =~ s/.$//;
463 $conn->send_raw($out);
466 $conn->{msg} .= $msg;
469 unless ($conn->{disable_read}) {
470 $conn->dequeue if exists $conn->{msg};
475 my $server_conn = shift;
478 my $conn = $server_conn->new($server_conn->{rproc});
479 my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
480 $sock->on(read => sub {$conn->_rcv($_[1])});
483 $conn->{peerhost} = $handle->peerhost || 'unknown';
484 $conn->{peerhost} =~ s|^::ffff:||; # chop off leading pseudo IPV6 stuff on dual stack listeners
485 $conn->{peerport} = $handle->peerport || 0;
486 dbg((ref $conn) . " accept $conn->{cnum} from $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg('connect');
487 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost}, $conn->{peerport});
488 $conn->{sort} = 'Incoming';
490 $conn->{eproc} = $eproc;
493 $conn->{rproc} = $rproc;
494 } else { # Login failed
495 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
504 delete $conn->{sock};
507 # close all clients (this is for forking really)
508 sub close_all_clients
510 foreach my $conn (values %conns) {
518 return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
523 #----------------------------------------------------
524 # Event loop routines used by both client and server
526 sub set_event_handler {
529 my ($pkg, $fn, $line) = caller;
531 foreach (my ($k,$v) = each %args) {
535 dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
540 my ($pkg, $interval) = @_;
542 while (time - $now < $interval) {
550 my $call = $conn->{call} || 'unallocated';
552 if (isdbg('connll')) {
553 my ($pkg, $fn, $line) = caller;
554 dbgtrace((ref $conn) . "::DESTROY on call $call called from ${pkg}::${fn} line $line ");
557 my $call = $conn->{call} || 'unallocated';
558 my $host = $conn->{peerhost} || '';
559 my $port = $conn->{peerport} || '';
560 my $sock = $conn->{sock};
563 $sock->close_gracefully;
567 dbg((ref $conn) . " Connection $conn->{cnum} $call [$host $port] being destroyed (total $noconns)") if isdbg('connll');