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 $total_lines_in $total_lines_out $connect_timeout $disc_waittime);
25 $total_in = $total_out = 0;
26 $total_lines_in = $total_lines_out = 0;
37 #-----------------------------------------------------------------
38 # Generalised initializer
42 my ($pkg, $rproc) = @_;
44 my $class = $obj || $pkg;
55 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
64 dbg("$class Connection created (total $noconns)") if isdbg('connll');
65 return bless $conn, $class;
72 $conn->{sock}->on(error => sub {$callback->($_[1]);});
79 $conn->{sock}->on(close => sub {$callback->()});
86 $conn->{rproc} = $callback;
97 $call = $pkg->{call} unless $call;
98 return undef unless $call;
99 dbg((ref $pkg) . " changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
100 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
101 $pkg->{call} = $call;
102 $ref = $conns{$call} = $pkg;
103 dbg((ref $pkg) . " Connection $pkg->{cnum} $call stored") if isdbg('connll');
105 $ref = $conns{$call};
110 # this is only called by any dependent processes going away unexpectedly
113 my ($pkg, $pid) = @_;
115 my @pid = grep {$_->{pid} == $pid} values %conns;
116 foreach my $p (@pid) {
117 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
125 return $conn->{csort} eq 'ax25';
131 unless ($conn->{peerhost}) {
132 $conn->{peerhost} ||= 'ax25' if $conn->ax25;
133 $conn->{peerhost} ||= $conn->{sock}->handle->peerhost if $conn->{sock};
134 $conn->{peerhost} ||= 'UNKNOWN';
136 $conn->{peerhost} =~ s/^::ffff://;
137 return $conn->{peerhost};
143 unless ($conn->{sockhost}) {
144 $conn->{sockhost} ||= 'ax25' if $conn->ax25;
145 $conn->{sockhost} ||= $conn->{sock}->handle->sockhost if $conn->{sock};
146 $conn->{sockhost} ||= 'UNKNOWN';
148 $conn->{sockhost} =~ s/^::ffff://;
149 if (! defined $main::localhost_alias_ipv4 && $conn->{sockhost} =~ /\./ && $conn->{sockhost} !~ /^127\./) {
150 $main::localhost_alias_ipv4 = $conn->{sockhost};
151 dbg("Msg: localhost_alias_ipv4 = '$main::localhost_alias_ipv4'");
152 } elsif (! defined $main::localhost_alias_ipv6 && $conn->{sockhost} =~ /:/ && $conn->{sockhost} !~ /^::1$/) {
153 $main::localhost_alias_ipv6 = $conn->{sockhost};
154 dbg("Msg: localhost_alias_ipv6 = '$main::localhost_alias_ipv6'");
156 return $conn->{sockhost};
158 #-----------------------------------------------------------------
166 my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
167 $sock->on(read => sub {$conn->_rcv($_[1]);} );
168 $sock->on(error => sub {delete $conn->{sock}; $conn->disconnect;});
169 $sock->on(close => sub {delete $conn->{sock}; $conn->disconnect;});
172 $conn->{peerhost} = eval { $handle->peerhost; };
173 $conn->{sockhost} = eval { $handle->sockhost; };
174 dbg((ref $conn) . " connected $conn->{cnum}:$conn->{sockhost} to $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg ('connect');
175 if ($conn->{on_connect}) {
176 &{$conn->{on_connect}}($conn, $handle);
183 my $sock = $conn->{sock};
184 return ref $sock && $sock->isa('Mojo::IOLoop::Stream');
188 my ($pkg, $to_host, $to_port, %args) = @_;
189 my $timeout = delete $args{timeout} || $connect_timeout;
191 # Create a connection end-point object
194 my $rproc = delete $args{rproc};
195 $conn = $pkg->new($rproc);
197 $conn->{peerhost} = $to_host;
198 $conn->{peerport} = $to_port;
199 $conn->{sort} = 'Outgoing';
201 dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
204 $conn->{sock} = $sock = Mojo::IOLoop::Client->new;
205 $sock->on(connect => sub {
206 $conn->_on_connect($_[1])
208 $sock->on(error => sub {
209 &{$conn->{eproc}}($conn, $_[1]) if exists $conn->{eproc};
210 delete $conn->{sock};
213 $sock->on(close => sub {
214 delete $conn->{sock};
218 # copy any args like on_connect, on_disconnect etc
219 while (my ($k, $v) = each %args) {
223 $sock->connect(address => $to_host, port => $to_port, timeout => $timeout);
230 my ($conn, $line, $sort) = @_;
233 # local $^F = 10000; # make sure it ain't closed on exec
234 # my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
239 # if (defined $pid) {
242 # $conn->{sock} = $a;
243 # $conn->{csort} = $sort;
244 # $conn->{lineend} = "\cM" if $sort eq 'ax25';
245 # $conn->{pid} = $pid;
246 # if ($conn->{rproc}) {
247 # my $callback = sub {$conn->_rcv};
248 # Msg::set_event_handler ($a, read => $callback);
250 # dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
257 # *STDIN = IO::File->new_from_fd($b, 'r') or die;
258 # *STDOUT = IO::File->new_from_fd($b, 'w') or die;
259 # *STDERR = IO::File->new_from_fd($b, 'w') or die;
261 # unless ($main::is_win) {
262 # # $SIG{HUP} = 'IGNORE';
263 # $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
266 # exec "$line" or dbg("exec '$line' failed $!");
269 # dbg("cannot fork for $line");
272 # dbg("no socket pair $! for $line");
280 my $count = $conn->{disconnecting}++;
281 my $dbg = isdbg('connll');
282 my ($pkg, $fn, $line) = caller if $dbg;
285 dbgtrace((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line FORCING CLOSE ") if $dbg;
289 dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ") if $dbg;
292 # remove this conn from the active queue
293 # be careful to delete the correct one
295 if ($call = $conn->{call}) {
296 my $ref = $conns{$call};
297 delete $conns{$call} if $ref && $ref == $conn;
299 $call ||= 'unallocated';
301 $delqueue{$conn} = $conn; # save this connection until everything is finished
302 my $sock = $conn->{sock};
304 if ($sock->{buffer}) {
305 my $lth = length $sock->{buffer};
306 Mojo::IOLoop->timer($disc_waittime, sub {
307 dbg("Buffer contained $lth characters, coordinated for $disc_waittime secs, now disconnecting $call") if $dbg;
311 dbg("Buffer empty, just close $call") if $dbg;
316 dbg((ref $conn) . " socket missing on $conn->{call}") if $dbg;
324 my $sock = delete $conn->{sock};
325 $conn->{state} = 'E';
326 $conn->{timeout}->del if $conn->{timeout};
328 my $call = $conn->{call};
330 if (isdbg('connll')) {
331 my ($pkg, $fn, $line) = caller;
332 dbg((ref $conn) . "::_close_it on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ");
336 dbg((ref $conn) . " Connection $conn->{cnum} $call starting to close") if isdbg('connll');
338 if ($conn->{on_disconnect}) {
339 &{$conn->{on_disconnect}}($conn);
343 dbg((ref $conn) . " Connection $conn->{cnum} $call closing gracefully") if isdbg('connll');
344 $sock->close_gracefully if $sock->can('close_gracefully');
347 # get rid of any references
349 if (ref($conn->{$_})) {
354 delete $delqueue{$conn}; # finally remove the $conn
356 unless ($main::is_win) {
357 kill 'TERM', $conn->{pid} if exists $conn->{pid};
364 my $rq = $conn->{outqueue};
365 my $sock = $conn->{sock};
366 return unless defined $sock;
367 return if $conn->{disconnecting};
370 my $data = shift @$rq;
371 my $lth = length $data;
372 my $call = $conn->{call} || 'none';
374 dbgdump('raw', "$call send $lth:", $data);
379 $conn->{dataout} += $lth;
383 dbg("_send_stuff $call ending data ignored: $data");
389 my ($conn, $msg) = @_;
390 $conn->enqueue($msg);
400 my ($conn, $msg) = @_;
401 push @{$conn->{outqueue}}, $msg;
407 push @{$conn->{outqueue}}, defined $_[0] ? $_[0] : '';
418 $conn->{sock}->on(drain => sub {$conn->disconnect;});
421 #-----------------------------------------------------------------
422 # Receive side routines
426 # @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
427 my ($pkg, $my_host, $my_port, $login_proc) = @_;
428 my $conn = $pkg->new($login_proc);
430 my $sock = $conn->{sock} = Mojo::IOLoop::Server->new;
431 $sock->on(accept=>sub{$conn->new_client($_[1]);});
432 $sock->listen(address=>$my_host, port=>$my_port);
435 die "Could not create socket: $! \n" unless $conn->{sock};
448 return if $conn->{disconnecting};
450 if ($conn->{msg} =~ /\cJ/) {
451 my @lines = split /\cM?\cJ/, $conn->{msg};
452 if ($conn->{msg} =~ /\cM?\cJ$/) {
455 $conn->{msg} = pop @lines;
457 $conn->{linesin} += @lines;
458 $total_lines_in += @lines;
460 last if $conn->{disconnecting};
461 &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
466 sub _rcv { # Complement to _send
467 my $conn = shift; # $rcv_now complement of $flush
469 my $sock = $conn->{sock};
470 return unless defined($sock);
471 return if $conn->{disonnecting};
473 $total_in += length $msg;
474 $conn->{datain} += length $msg;
477 my $call = $conn->{call} || 'none';
478 my $lth = length $msg;
479 dbgdump('raw', "$call read $lth: ", $msg);
482 my @ch = split //, $msg;
487 $conn->{msg} =~ s/.$//;
494 $conn->send_raw($out);
497 $conn->{msg} .= $msg;
500 unless ($conn->{disable_read}) {
501 $conn->dequeue if exists $conn->{msg};
506 my $server_conn = shift;
509 my $conn = $server_conn->new($server_conn->{rproc});
510 my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
511 $sock->on(read => sub {$conn->_rcv($_[1])});
514 $conn->{peerhost} = $handle->peerhost || 'unknown';
515 $conn->{peerport} = $handle->peerport || 0;
516 $conn->{sockhost} = $handle->sockhost || '';
517 dbg((ref $conn) . " accept $conn->{cnum}:$conn->{sockhost} from $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg('connect');
518 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost}, $conn->{peerport});
519 $conn->{sort} = 'Incoming';
521 $conn->{eproc} = $eproc;
524 $conn->{rproc} = $rproc;
525 } else { # Login failed
526 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
535 delete $conn->{sock};
538 # close all clients (this is for forking really)
539 sub close_all_clients
541 foreach my $conn (values %conns) {
549 return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
554 #----------------------------------------------------
555 # Event loop routines used by both client and server
557 sub set_event_handler {
560 my ($pkg, $fn, $line) = caller;
562 foreach (my ($k,$v) = each %args) {
566 dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
571 my ($pkg, $interval) = @_;
573 while (time - $now < $interval) {
581 my $call = $conn->{call} || 'unallocated';
583 if (isdbg('connll')) {
584 my ($pkg, $fn, $line) = caller;
585 dbgtrace((ref $conn) . "::DESTROY on call $call called from ${pkg}::${fn} line $line ");
588 my $host = $conn->{peerhost} || '';
589 my $port = $conn->{peerport} || '';
590 my $sock = $conn->{sock};
593 $sock->close_gracefully if $sock->can('close_gracefully');
594 delete $conn->{sock};
598 dbg((ref $conn) . " Connection $conn->{cnum} $call [$host $port] being destroyed (total $noconns)") if isdbg('connll');