Add latest RBN chnages and data stats
[spider.git] / perl / Msg.pm
1 #
2 # This has been taken from the 'Advanced Perl Programming' book by Sriram Srinivasan 
3 #
4 # I am presuming that the code is distributed on the same basis as perl itself.
5 #
6 # I have modified it to suit my devious purposes (Dirk Koopman G1TLH)
7 #
8 #
9 #
10
11 package Msg;
12
13 use strict;
14
15 use DXUtil;
16
17 use Mojo::IOLoop;
18 use Mojo::IOLoop::Stream;
19
20 use DXDebug;
21 use Timer;
22
23 use vars qw($now %conns $noconns $cnum $total_in $total_out $total_lines_in $total_lines_out $connect_timeout $disc_waittime);
24
25 $total_in = $total_out = 0;
26 $total_lines_in = $total_lines_out = 0;
27
28 $now = time;
29
30 $cnum = 0;
31 $connect_timeout = 5;
32 $disc_waittime = 1.5;
33
34 our %delqueue;
35
36 #
37 #-----------------------------------------------------------------
38 # Generalised initializer
39
40 sub new
41 {
42     my ($pkg, $rproc) = @_;
43         my $obj = ref($pkg);
44         my $class = $obj || $pkg;
45
46     my $conn = {
47                                 rproc => $rproc,
48                                 inqueue => [],
49                                 outqueue => [],
50                                 state => 0,
51                                 lineend => "\r\n",
52                                 csort => 'telnet',
53                                 timeval => 60,
54                                 blocking => 0,
55                                 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
56                                 linesin => 0,
57                                 linesout => 0,
58                                 datain => 0,
59                                 dataout => 0,
60     };
61
62         $noconns++;
63         
64         dbg("$class Connection created (total $noconns)") if isdbg('connll');
65         return bless $conn, $class;
66 }
67
68 sub set_error
69 {
70         my $conn = shift;
71         my $callback = shift;
72         $conn->{sock}->on(error => sub {$callback->($_[1]);});
73 }
74
75 sub set_on_eof
76 {
77         my $conn = shift;
78         my $callback = shift;
79         $conn->{sock}->on(close => sub {$callback->()});
80 }
81
82 sub set_rproc
83 {
84         my $conn = shift;
85         my $callback = shift;
86         $conn->{rproc} = $callback;
87 }
88
89 # save it
90 sub conns
91 {
92         my $pkg = shift;
93         my $call = shift;
94         my $ref;
95         
96         if (ref $pkg) {
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');
104         } else {
105                 $ref = $conns{$call};
106         }
107         return $ref;
108 }
109
110 # this is only called by any dependent processes going away unexpectedly
111 sub pid_gone
112 {
113         my ($pkg, $pid) = @_;
114         
115         my @pid = grep {$_->{pid} == $pid} values %conns;
116         foreach my $p (@pid) {
117                 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
118                 $p->disconnect;
119         }
120 }
121
122 sub ax25
123 {
124         my $conn = shift;
125         return $conn->{csort} eq 'ax25';
126 }
127
128 sub peerhost
129 {
130         my $conn = shift;
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';
135         }
136         return $conn->{peerhost};
137 }
138
139 #-----------------------------------------------------------------
140 # Send side routines
141
142 sub _on_connect
143 {
144         my $conn = shift;
145         my $handle = shift;
146         undef $conn->{sock};
147         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
148         $sock->on(read => sub {$conn->_rcv($_[1]);} );
149         $sock->on(error => sub {delete $conn->{sock}; $conn->disconnect;});
150         $sock->on(close => sub {delete $conn->{sock}; $conn->disconnect;});
151         $sock->timeout(0);
152         $sock->start;
153         $conn->{peerhost} = eval { $handle->peerhost; };
154         dbg((ref $conn) . " connected $conn->{cnum} to $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg ('connect');
155         if ($conn->{on_connect}) {
156                 &{$conn->{on_connect}}($conn, $handle);
157         }
158 }
159
160 sub is_connected
161 {
162         my $conn = shift;
163         my $sock = $conn->{sock};
164         return ref $sock && $sock->isa('Mojo::IOLoop::Stream');
165 }
166
167 sub connect {
168     my ($pkg, $to_host, $to_port, %args) = @_;
169         my $timeout = delete $args{timeout} || $connect_timeout;
170         
171     # Create a connection end-point object
172     my $conn = $pkg;
173         unless (ref $pkg) {
174                 my $rproc = delete $args{rproc}; 
175                 $conn = $pkg->new($rproc);
176         }
177         $conn->{peerhost} = $to_host;
178         $conn->{peerport} = $to_port;
179         $conn->{sort} = 'Outgoing';
180
181         dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
182         
183         my $sock;
184         $conn->{sock} = $sock = Mojo::IOLoop::Client->new;
185         $sock->on(connect => sub {
186                                   $conn->_on_connect($_[1])
187                           } );
188         $sock->on(error => sub {
189                                   &{$conn->{eproc}}($conn, $_[1]) if exists $conn->{eproc};
190                                   delete $conn->{sock};
191                                   $conn->disconnect
192                           });
193         $sock->on(close => sub {
194                                   delete $conn->{sock};
195                                   $conn->disconnect}
196                          );
197
198         # copy any args like on_connect, on_disconnect etc
199         while (my ($k, $v) = each %args) {
200                 $conn->{$k} = $v;
201         }
202         
203         $sock->connect(address => $to_host, port => $to_port, timeout => $timeout);
204         
205     return $conn;
206 }
207
208 sub start_program
209 {
210         my ($conn, $line, $sort) = @_;
211         my $pid;
212         
213 #       local $^F = 10000;              # make sure it ain't closed on exec
214 #       my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
215 #       if ($a && $b) {
216 #               $a->autoflush(1);
217 #               $b->autoflush(1);
218 #               $pid = fork;
219 #               if (defined $pid) {
220 #                       if ($pid) {
221 #                               close $b;
222 #                               $conn->{sock} = $a;
223 #                               $conn->{csort} = $sort;
224 #                               $conn->{lineend} = "\cM" if $sort eq 'ax25';
225 #                               $conn->{pid} = $pid;
226 #                               if ($conn->{rproc}) {
227 #                                       my $callback = sub {$conn->_rcv};
228 #                                       Msg::set_event_handler ($a, read => $callback);
229 #                               }
230 #                               dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
231 #                       } else {
232 #                               $^W = 0;
233 #                               dbgclose();
234 #                               STDIN->close;
235 #                               STDOUT->close;
236 #                               STDOUT->close;
237 #                               *STDIN = IO::File->new_from_fd($b, 'r') or die;
238 #                               *STDOUT = IO::File->new_from_fd($b, 'w') or die;
239 #                               *STDERR = IO::File->new_from_fd($b, 'w') or die;
240 #                               close $a;
241 #                               unless ($main::is_win) {
242 #                                       #                                               $SIG{HUP} = 'IGNORE';
243 #                                       $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
244 #                                       alarm(0);
245 #                               }
246 #                               exec "$line" or dbg("exec '$line' failed $!");
247 #                       } 
248 #               } else {
249 #                       dbg("cannot fork for $line");
250 #               }
251 #       } else {
252 #               dbg("no socket pair $! for $line");
253 #       }
254         return $pid;
255 }
256
257 sub disconnect
258 {
259         my $conn = shift;
260         my $count = $conn->{disconnecting}++;
261         my $dbg = isdbg('connll');
262         my ($pkg, $fn, $line) = caller if $dbg;
263
264         if ($count >= 2) {
265                 dbgtrace((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line FORCING CLOSE ") if $dbg;
266                 _close_it($conn);
267                 return;
268         }
269         dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ") if $dbg;
270         return if $count;
271
272         # remove this conn from the active queue
273         # be careful to delete the correct one
274         my $call;
275         if ($call = $conn->{call}) {
276                 my $ref = $conns{$call};
277                 delete $conns{$call} if $ref && $ref == $conn;
278         }
279         $call ||= 'unallocated';
280
281         $delqueue{$conn} = $conn; # save this connection until everything is finished
282         my $sock = $conn->{sock};
283         if ($sock) {
284                 if ($sock->{buffer}) {
285                         my $lth = length $sock->{buffer};
286                         Mojo::IOLoop->timer($disc_waittime, sub {
287                                                                         dbg("Buffer contained $lth characters, coordinated for $disc_waittime secs, now disconnecting $call") if $dbg;
288                                                                         _close_it($conn);
289                                                                 });
290                 } else {
291                         dbg("Buffer empty, just close $call") if $dbg;
292                         _close_it($conn);
293                 }
294         } else {
295                 dbg((ref $conn) . " socket missing on $conn->{call}") if $dbg;
296                 _close_it($conn);
297         }
298 }
299
300 sub _close_it
301 {
302     my $conn = shift;
303     my $sock = delete $conn->{sock};
304         $conn->{state} = 'E';
305         $conn->{timeout}->del if $conn->{timeout};
306
307         my $call = $conn->{call};
308
309         if (isdbg('connll')) {
310                 my ($pkg, $fn, $line) = caller;
311                 dbg((ref $conn) . "::_close_it on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ");
312         }
313
314
315         dbg((ref $conn) . " Connection $conn->{cnum} $call starting to close") if isdbg('connll');
316         
317         if ($conn->{on_disconnect}) {
318                 &{$conn->{on_disconnect}}($conn);
319         }
320
321         if ($sock) {
322                 dbg((ref $conn) . " Connection $conn->{cnum} $call closing gracefully") if isdbg('connll');
323                 $sock->close_gracefully;
324         }
325         
326         # get rid of any references
327         for (keys %$conn) {
328                 if (ref($conn->{$_})) {
329                         delete $conn->{$_};
330                 }
331         }
332
333         delete $delqueue{$conn};        # finally remove the $conn
334         
335         unless ($main::is_win) {
336                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
337         }
338 }
339
340 sub _send_stuff
341 {
342         my $conn = shift;
343         my $rq = $conn->{outqueue};
344     my $sock = $conn->{sock};
345         return unless defined $sock;
346         return if $conn->{disconnecting};
347         
348         while (@$rq) {
349                 my $data = shift @$rq;
350                 my $lth = length $data;
351                 my $call = $conn->{call} || 'none';
352                 if (isdbg('raw')) {
353                         dbgdump('raw', "$call send $lth:", $data);
354                 }
355                 if (defined $sock) {
356                         $sock->write($data);
357                         $total_out += $lth;
358                         $conn->{dataout} += $lth;
359                         ++$conn->{linesout};
360                         ++$total_lines_out;
361                 } else {
362                         dbg("_send_stuff $call ending data ignored: $data");
363                 }
364         }
365 }
366
367 sub send_now {
368     my ($conn, $msg) = @_;
369     $conn->enqueue($msg);
370     _send_stuff($conn);
371 }
372
373 sub send_later {
374         goto &send_now;
375 }
376
377 sub send_raw
378 {
379     my ($conn, $msg) = @_;
380         push @{$conn->{outqueue}}, $msg;
381         _send_stuff($conn);
382 }
383
384 sub enqueue {
385     my $conn = shift;
386     push @{$conn->{outqueue}}, defined $_[0] ? $_[0] : '';
387 }
388
389 sub _err_will_block 
390 {
391         return 0;
392 }
393
394 sub close_on_empty
395 {
396         my $conn = shift;
397         $conn->{sock}->on(drain => sub {$conn->disconnect;});
398 }
399
400 #-----------------------------------------------------------------
401 # Receive side routines
402
403 sub new_server 
404 {
405 #    @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
406         my ($pkg, $my_host, $my_port, $login_proc) = @_;
407         my $conn = $pkg->new($login_proc);
408         
409     my $sock = $conn->{sock} = Mojo::IOLoop::Server->new;
410         $sock->on(accept=>sub{$conn->new_client($_[1]);});
411         $sock->listen(address=>$my_host, port=>$my_port);
412         $sock->start;
413         
414     die "Could not create socket: $! \n" unless $conn->{sock};
415         return $conn;
416 }
417
418
419 sub nolinger
420 {
421         my $conn = shift;
422 }
423
424 sub dequeue
425 {
426         my $conn = shift;
427         return if $conn->{disconnecting};
428         
429         if ($conn->{msg} =~ /\cJ/) {
430                 my @lines = split /\cM?\cJ/, $conn->{msg};
431                 if ($conn->{msg} =~ /\cM?\cJ$/) {
432                         delete $conn->{msg};
433                 } else {
434                         $conn->{msg} = pop @lines;
435                 }
436                 $conn->{linesin} += @lines;
437                 $total_lines_in += @lines;
438                 for (@lines) {
439                         last if $conn->{disconnecting};
440                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
441                 }
442         }
443 }
444
445 sub _rcv {                     # Complement to _send
446     my $conn = shift; # $rcv_now complement of $flush
447         my $msg = shift;
448     my $sock = $conn->{sock};
449     return unless defined($sock);
450         return if $conn->{disconnecting};
451
452         $total_in += length $msg;
453         $conn->{datain} += length $msg;
454
455         if (isdbg('raw')) {
456                 my $call = $conn->{call} || 'none';
457                 my $lth = length $msg;
458                 dbgdump('raw', "$call read $lth: ", $msg);
459         }
460         if ($conn->{echo}) {
461                 my @ch = split //, $msg;
462                         my $out;
463                         for (@ch) {
464                                 if (/[\cH\x7f]/) {
465                                         $out .= "\cH \cH";
466                                         $conn->{msg} =~ s/.$//;
467                                 } else {
468                                         $out .= $_;
469                                         $conn->{msg} .= $_;
470                                 }
471                         }
472                         if (defined $out) {
473                                 $conn->send_raw($out);
474                         }
475         } else {
476                 $conn->{msg} .= $msg;
477         }
478
479         unless ($conn->{disable_read}) {
480                 $conn->dequeue if exists $conn->{msg};
481         }
482 }
483
484 sub new_client {
485         my $server_conn = shift;
486         my $handle = shift;
487         
488         my $conn = $server_conn->new($server_conn->{rproc});
489         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
490         $sock->on(read => sub {$conn->_rcv($_[1])});
491         $sock->timeout(0);
492         $sock->start;
493         $conn->{peerhost} = $handle->peerhost || 'unknown';
494         $conn->{peerhost} =~ s|^::ffff:||; # chop off leading pseudo IPV6 stuff on dual stack listeners
495         $conn->{peerport} = $handle->peerport || 0;
496         dbg((ref $conn) . " accept $conn->{cnum} from $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg('connect');
497         my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost}, $conn->{peerport});
498         $conn->{sort} = 'Incoming';
499         if ($eproc) {
500                 $conn->{eproc} = $eproc;
501         }
502         if ($rproc) {
503                 $conn->{rproc} = $rproc;
504         } else {  # Login failed
505                 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
506                 $conn->disconnect();
507         }
508         return $conn;
509 }
510
511 sub close_server
512 {
513         my $conn = shift;
514         delete $conn->{sock};
515 }
516
517 # close all clients (this is for forking really)
518 sub close_all_clients
519 {
520         foreach my $conn (values %conns) {
521                 $conn->disconnect;
522         }
523 }
524
525 sub disable_read
526 {
527         my $conn = shift;
528         return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
529 }
530
531
532 #
533 #----------------------------------------------------
534 # Event loop routines used by both client and server
535
536 sub set_event_handler {
537         my $sock = shift;
538         my %args = @_;
539         my ($pkg, $fn, $line) = caller;
540         my $s;
541         foreach (my ($k,$v) = each %args) {
542                 $s .= "$k => $v, ";
543         }
544         $s =~ s/[\s,]$//;
545         dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
546 }
547
548 sub sleep
549 {
550         my ($pkg, $interval) = @_;
551         my $now = time;
552         while (time - $now < $interval) {
553                 sleep 1;
554         }
555 }
556
557 sub DESTROY
558 {
559         my $conn = shift;
560         my $call = $conn->{call} || 'unallocated';
561
562         if (isdbg('connll')) {
563                 my ($pkg, $fn, $line) = caller;
564                 dbgtrace((ref $conn) . "::DESTROY on call $call called from ${pkg}::${fn} line $line ");
565         }
566
567         my $call = $conn->{call} || 'unallocated';
568         my $host = $conn->{peerhost} || '';
569         my $port = $conn->{peerport} || '';
570         my $sock = $conn->{sock};
571
572         if ($sock) {
573                 $sock->close_gracefully;
574         }
575         
576         $noconns--;
577         dbg((ref $conn) . " Connection $conn->{cnum} $call [$host $port] being destroyed (total $noconns)") if isdbg('connll');
578 }
579
580 1;
581
582 __END__
583