9a6f8d1f06894cd25d749afc9d2bac8019fd132d
[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 DXTimer;
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         $conn->{peerhost} =~ s/^::ffff://;
137         return $conn->{peerhost};
138 }
139
140 #-----------------------------------------------------------------
141 # Send side routines
142
143 sub _on_connect
144 {
145         my $conn = shift;
146         my $handle = shift;
147         undef $conn->{sock};
148         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
149         $sock->on(read => sub {$conn->_rcv($_[1]);} );
150         $sock->on(error => sub {delete $conn->{sock}; $conn->disconnect;});
151         $sock->on(close => sub {delete $conn->{sock}; $conn->disconnect;});
152         $sock->timeout(0);
153         $sock->start;
154         $conn->{peerhost} = eval { $handle->peerhost; };
155         dbg((ref $conn) . " connected $conn->{cnum} to $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg ('connect');
156         if ($conn->{on_connect}) {
157                 &{$conn->{on_connect}}($conn, $handle);
158         }
159 }
160
161 sub is_connected
162 {
163         my $conn = shift;
164         my $sock = $conn->{sock};
165         return ref $sock && $sock->isa('Mojo::IOLoop::Stream');
166 }
167
168 sub connect {
169     my ($pkg, $to_host, $to_port, %args) = @_;
170         my $timeout = delete $args{timeout} || $connect_timeout;
171         
172     # Create a connection end-point object
173     my $conn = $pkg;
174         unless (ref $pkg) {
175                 my $rproc = delete $args{rproc}; 
176                 $conn = $pkg->new($rproc);
177         }
178         $conn->{peerhost} = $to_host;
179         $conn->{peerport} = $to_port;
180         $conn->{sort} = 'Outgoing';
181
182         dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
183         
184         my $sock;
185         $conn->{sock} = $sock = Mojo::IOLoop::Client->new;
186         $sock->on(connect => sub {
187                                   $conn->_on_connect($_[1])
188                           } );
189         $sock->on(error => sub {
190                                   &{$conn->{eproc}}($conn, $_[1]) if exists $conn->{eproc};
191                                   delete $conn->{sock};
192                                   $conn->disconnect
193                           });
194         $sock->on(close => sub {
195                                   delete $conn->{sock};
196                                   $conn->disconnect}
197                          );
198
199         # copy any args like on_connect, on_disconnect etc
200         while (my ($k, $v) = each %args) {
201                 $conn->{$k} = $v;
202         }
203         
204         $sock->connect(address => $to_host, port => $to_port, timeout => $timeout);
205         
206     return $conn;
207 }
208
209 sub start_program
210 {
211         my ($conn, $line, $sort) = @_;
212         my $pid;
213         
214 #       local $^F = 10000;              # make sure it ain't closed on exec
215 #       my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
216 #       if ($a && $b) {
217 #               $a->autoflush(1);
218 #               $b->autoflush(1);
219 #               $pid = fork;
220 #               if (defined $pid) {
221 #                       if ($pid) {
222 #                               close $b;
223 #                               $conn->{sock} = $a;
224 #                               $conn->{csort} = $sort;
225 #                               $conn->{lineend} = "\cM" if $sort eq 'ax25';
226 #                               $conn->{pid} = $pid;
227 #                               if ($conn->{rproc}) {
228 #                                       my $callback = sub {$conn->_rcv};
229 #                                       Msg::set_event_handler ($a, read => $callback);
230 #                               }
231 #                               dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
232 #                       } else {
233 #                               $^W = 0;
234 #                               dbgclose();
235 #                               STDIN->close;
236 #                               STDOUT->close;
237 #                               STDOUT->close;
238 #                               *STDIN = IO::File->new_from_fd($b, 'r') or die;
239 #                               *STDOUT = IO::File->new_from_fd($b, 'w') or die;
240 #                               *STDERR = IO::File->new_from_fd($b, 'w') or die;
241 #                               close $a;
242 #                               unless ($main::is_win) {
243 #                                       #                                               $SIG{HUP} = 'IGNORE';
244 #                                       $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
245 #                                       alarm(0);
246 #                               }
247 #                               exec "$line" or dbg("exec '$line' failed $!");
248 #                       } 
249 #               } else {
250 #                       dbg("cannot fork for $line");
251 #               }
252 #       } else {
253 #               dbg("no socket pair $! for $line");
254 #       }
255         return $pid;
256 }
257
258 sub disconnect
259 {
260         my $conn = shift;
261         my $count = $conn->{disconnecting}++;
262         my $dbg = isdbg('connll');
263         my ($pkg, $fn, $line) = caller if $dbg;
264
265         if ($count >= 2) {
266                 dbgtrace((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line FORCING CLOSE ") if $dbg;
267                 _close_it($conn);
268                 return;
269         }
270         dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ") if $dbg;
271         return if $count;
272
273         # remove this conn from the active queue
274         # be careful to delete the correct one
275         my $call;
276         if ($call = $conn->{call}) {
277                 my $ref = $conns{$call};
278                 delete $conns{$call} if $ref && $ref == $conn;
279         }
280         $call ||= 'unallocated';
281
282         $delqueue{$conn} = $conn; # save this connection until everything is finished
283         my $sock = $conn->{sock};
284         if ($sock) {
285                 if ($sock->{buffer}) {
286                         my $lth = length $sock->{buffer};
287                         Mojo::IOLoop->timer($disc_waittime, sub {
288                                                                         dbg("Buffer contained $lth characters, coordinated for $disc_waittime secs, now disconnecting $call") if $dbg;
289                                                                         _close_it($conn);
290                                                                 });
291                 } else {
292                         dbg("Buffer empty, just close $call") if $dbg;
293                         _close_it($conn);
294                 }
295         }
296         else {
297                 dbg((ref $conn) . " socket missing on $conn->{call}") if $dbg;
298                 _close_it($conn);
299         }
300 }
301
302 sub _close_it
303 {
304     my $conn = shift;
305     my $sock = delete $conn->{sock};
306         $conn->{state} = 'E';
307         $conn->{timeout}->del if $conn->{timeout};
308
309         my $call = $conn->{call};
310
311         if (isdbg('connll')) {
312                 my ($pkg, $fn, $line) = caller;
313                 dbg((ref $conn) . "::_close_it on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ");
314         }
315
316
317         dbg((ref $conn) . " Connection $conn->{cnum} $call starting to close") if isdbg('connll');
318         
319         if ($conn->{on_disconnect}) {
320                 &{$conn->{on_disconnect}}($conn);
321         }
322
323         if ($sock) {
324                 dbg((ref $conn) . " Connection $conn->{cnum} $call closing gracefully") if isdbg('connll');
325                 $sock->close_gracefully if $sock->can('close_gracefully');
326         }
327         
328         # get rid of any references
329         for (keys %$conn) {
330                 if (ref($conn->{$_})) {
331                         delete $conn->{$_};
332                 }
333         }
334
335         delete $delqueue{$conn};        # finally remove the $conn
336         
337         unless ($main::is_win) {
338                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
339         }
340 }
341
342 sub _send_stuff
343 {
344         my $conn = shift;
345         my $rq = $conn->{outqueue};
346     my $sock = $conn->{sock};
347         return unless defined $sock;
348         return if $conn->{disconnecting};
349         
350         while (@$rq) {
351                 my $data = shift @$rq;
352                 my $lth = length $data;
353                 my $call = $conn->{call} || 'none';
354                 if (isdbg('raw')) {
355                         dbgdump('raw', "$call send $lth:", $data);
356                 }
357                 if (defined $sock) {
358                         $sock->write($data);
359                         $total_out += $lth;
360                         $conn->{dataout} += $lth;
361                         ++$conn->{linesout};
362                         ++$total_lines_out;
363                 } else {
364                         dbg("_send_stuff $call ending data ignored: $data");
365                 }
366         }
367 }
368
369 sub send_now {
370     my ($conn, $msg) = @_;
371     $conn->enqueue($msg);
372     _send_stuff($conn);
373 }
374
375 sub send_later {
376         goto &send_now;
377 }
378
379 sub send_raw
380 {
381     my ($conn, $msg) = @_;
382         push @{$conn->{outqueue}}, $msg;
383         _send_stuff($conn);
384 }
385
386 sub enqueue {
387     my $conn = shift;
388     push @{$conn->{outqueue}}, defined $_[0] ? $_[0] : '';
389 }
390
391 sub _err_will_block 
392 {
393         return 0;
394 }
395
396 sub close_on_empty
397 {
398         my $conn = shift;
399         $conn->{sock}->on(drain => sub {$conn->disconnect;});
400 }
401
402 #-----------------------------------------------------------------
403 # Receive side routines
404
405 sub new_server 
406 {
407 #    @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
408         my ($pkg, $my_host, $my_port, $login_proc) = @_;
409         my $conn = $pkg->new($login_proc);
410         
411     my $sock = $conn->{sock} = Mojo::IOLoop::Server->new;
412         $sock->on(accept=>sub{$conn->new_client($_[1]);});
413         $sock->listen(address=>$my_host, port=>$my_port);
414         $sock->start;
415         
416     die "Could not create socket: $! \n" unless $conn->{sock};
417         return $conn;
418 }
419
420
421 sub nolinger
422 {
423         my $conn = shift;
424 }
425
426 sub dequeue
427 {
428         my $conn = shift;
429         return if $conn->{disconnecting};
430         
431         if ($conn->{msg} =~ /\cJ/) {
432                 my @lines = split /\cM?\cJ/, $conn->{msg};
433                 if ($conn->{msg} =~ /\cM?\cJ$/) {
434                         delete $conn->{msg};
435                 } else {
436                         $conn->{msg} = pop @lines;
437                 }
438                 $conn->{linesin} += @lines;
439                 $total_lines_in += @lines;
440                 for (@lines) {
441                         last if $conn->{disconnecting};
442                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
443                 }
444         }
445 }
446
447 sub _rcv {                     # Complement to _send
448     my $conn = shift; # $rcv_now complement of $flush
449         my $msg = shift;
450     my $sock = $conn->{sock};
451     return unless defined($sock);
452         return if $conn->{disconnecting};
453
454         $total_in += length $msg;
455         $conn->{datain} += length $msg;
456
457         if (isdbg('raw')) {
458                 my $call = $conn->{call} || 'none';
459                 my $lth = length $msg;
460                 dbgdump('raw', "$call read $lth: ", $msg);
461         }
462         if ($conn->{echo}) {
463                 my @ch = split //, $msg;
464                         my $out;
465                         for (@ch) {
466                                 if (/[\cH\x7f]/) {
467                                         $out .= "\cH \cH";
468                                         $conn->{msg} =~ s/.$//;
469                                 } else {
470                                         $out .= $_;
471                                         $conn->{msg} .= $_;
472                                 }
473                         }
474                         if (defined $out) {
475                                 $conn->send_raw($out);
476                         }
477         } else {
478                 $conn->{msg} .= $msg;
479         }
480
481         unless ($conn->{disable_read}) {
482                 $conn->dequeue if exists $conn->{msg};
483         }
484 }
485
486 sub new_client {
487         my $server_conn = shift;
488         my $handle = shift;
489         
490         my $conn = $server_conn->new($server_conn->{rproc});
491         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
492         $sock->on(read => sub {$conn->_rcv($_[1])});
493         $sock->timeout(0);
494         $sock->start;
495         $conn->{peerhost} = $handle->peerhost || 'unknown';
496         $conn->{peerhost} =~ s|^::ffff:||; # chop off leading pseudo IPV6 stuff on dual stack listeners
497         $conn->{peerport} = $handle->peerport || 0;
498         dbg((ref $conn) . " accept $conn->{cnum} from $conn->{peerhost}:$conn->{peerport}") if isdbg('conn') || isdbg('connect');
499         my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost}, $conn->{peerport});
500         $conn->{sort} = 'Incoming';
501         if ($eproc) {
502                 $conn->{eproc} = $eproc;
503         }
504         if ($rproc) {
505                 $conn->{rproc} = $rproc;
506         } else {  # Login failed
507                 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
508                 $conn->disconnect();
509         }
510         return $conn;
511 }
512
513 sub close_server
514 {
515         my $conn = shift;
516         delete $conn->{sock};
517 }
518
519 # close all clients (this is for forking really)
520 sub close_all_clients
521 {
522         foreach my $conn (values %conns) {
523                 $conn->disconnect;
524         }
525 }
526
527 sub disable_read
528 {
529         my $conn = shift;
530         return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
531 }
532
533
534 #
535 #----------------------------------------------------
536 # Event loop routines used by both client and server
537
538 sub set_event_handler {
539         my $sock = shift;
540         my %args = @_;
541         my ($pkg, $fn, $line) = caller;
542         my $s;
543         foreach (my ($k,$v) = each %args) {
544                 $s .= "$k => $v, ";
545         }
546         $s =~ s/[\s,]$//;
547         dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
548 }
549
550 sub sleep
551 {
552         my ($pkg, $interval) = @_;
553         my $now = time;
554         while (time - $now < $interval) {
555                 sleep 1;
556         }
557 }
558
559 sub DESTROY
560 {
561         my $conn = shift;
562         my $call = $conn->{call} || 'unallocated';
563
564         if (isdbg('connll')) {
565                 my ($pkg, $fn, $line) = caller;
566                 dbgtrace((ref $conn) . "::DESTROY on call $call called from ${pkg}::${fn} line $line ");
567         }
568
569         my $call = $conn->{call} || 'unallocated';
570         my $host = $conn->{peerhost} || '';
571         my $port = $conn->{peerport} || '';
572         my $sock = $conn->{sock};
573
574         if ($sock) {
575                 $sock->close_gracefully if $sock->can('close_gracefully');
576                 delete $conn->{sock};
577         }
578         
579         $noconns--;
580         dbg((ref $conn) . " Connection $conn->{cnum} $call [$host $port] being destroyed (total $noconns)") if isdbg('connll');
581 }
582
583 1;
584
585 __END__
586