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