add first take on IP address remembering
[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 = 1.5;
32 %conns;
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     };
57
58         $noconns++;
59         
60         dbg("$class Connection created (total $noconns)") if isdbg('connll');
61         return bless $conn, $class;
62 }
63
64 sub set_error
65 {
66         my $conn = shift;
67         my $callback = shift;
68         $conn->{sock}->on(error => sub {$callback->($_[1]);});
69 }
70
71 sub set_on_eof
72 {
73         my $conn = shift;
74         my $callback = shift;
75         $conn->{sock}->on(close => sub {$callback->()});
76 }
77
78 sub set_rproc
79 {
80         my $conn = shift;
81         my $callback = shift;
82         $conn->{rproc} = $callback;
83 }
84
85 # save it
86 sub conns
87 {
88         my $pkg = shift;
89         my $call = shift;
90         my $ref;
91         
92         if (ref $pkg) {
93                 $call = $pkg->{call} unless $call;
94                 return undef unless $call;
95                 dbg((ref $pkg) . " changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
96                 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call; 
97                 $pkg->{call} = $call;
98                 $ref = $conns{$call} = $pkg;
99                 dbg((ref $pkg) . " Connection $pkg->{cnum} $call stored") if isdbg('connll');
100         } else {
101                 $ref = $conns{$call};
102         }
103         return $ref;
104 }
105
106 # this is called as a FUNCTION i.e my $conn = Msg::get($call);
107 sub get
108 {
109         return $conns{shift};
110 }
111
112 # this is only called by any dependent processes going away unexpectedly
113 sub pid_gone
114 {
115         my ($pkg, $pid) = @_;
116         
117         my @pid = grep {$_->{pid} == $pid} values %conns;
118         foreach my $p (@pid) {
119                 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
120                 $p->disconnect;
121         }
122 }
123
124 sub ax25
125 {
126         my $conn = shift;
127         return $conn->{csort} eq 'ax25';
128 }
129
130 sub peerhost
131 {
132         my $conn = shift;
133         unless ($conn->{peerhost}) {
134                 $conn->{peerhost} ||= 'ax25' if $conn->ax25;
135                 $conn->{peerhost} ||= $conn->{sock}->handle->peerhost if $conn->{sock};
136                 $conn->{peerhost} ||= 'UNKNOWN';
137         }
138         return $conn->{peerhost};
139 }
140
141 #-----------------------------------------------------------------
142 # Send side routines
143
144 sub _on_connect
145 {
146         my $conn = shift;
147         my $handle = shift;
148         undef $conn->{sock};
149         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
150         $sock->on(read => sub {$conn->_rcv($_[1]);} );
151         $sock->on(error => sub {delete $conn->{sock}; $conn->disconnect;});
152         $sock->on(close => sub {delete $conn->{sock}; $conn->disconnect;});
153         $sock->timeout(0);
154         $sock->start;
155         $conn->{peerhost} = eval { $handle->peerhost; };
156         dbg((ref $conn) . " connected $conn->{cnum} to $conn->{peerhost}:$conn->{peerport}") if isdbg('connll');
157         if ($conn->{on_connect}) {
158                 &{$conn->{on_connect}}($conn, $handle);
159         }
160 }
161
162 sub is_connected
163 {
164         my $conn = shift;
165         my $sock = $conn->{sock};
166         return ref $sock && $sock->isa('Mojo::IOLoop::Stream');
167 }
168
169 sub connect {
170     my ($pkg, $to_host, $to_port, %args) = @_;
171         my $timeout = delete $args{timeout} || $connect_timeout;
172         
173     # Create a connection end-point object
174     my $conn = $pkg;
175         unless (ref $pkg) {
176                 my $rproc = delete $args{rproc}; 
177                 $conn = $pkg->new($rproc);
178         }
179         $conn->{peerhost} = $to_host;
180         $conn->{peerport} = $to_port;
181         $conn->{sort} = 'Outgoing';
182
183         dbg((ref $conn) . " connecting $conn->{cnum} to $to_host:$to_port") if isdbg('connll');
184         
185         my $sock;
186         $conn->{sock} = $sock = Mojo::IOLoop::Client->new;
187         $sock->on(connect => sub {
188                                   $conn->_on_connect($_[1])
189                           } );
190         $sock->on(error => sub {
191                                   &{$conn->{eproc}}($conn, $_[1]) if exists $conn->{eproc};
192                                   delete $conn->{sock};
193                                   $conn->disconnect
194                           });
195         $sock->on(close => sub {
196                                   delete $conn->{sock};
197                                   $conn->disconnect}
198                          );
199
200         # copy any args like on_connect, on_disconnect etc
201         while (my ($k, $v) = each %args) {
202                 $conn->{$k} = $v;
203         }
204         
205         $sock->connect(address => $to_host, port => $to_port, timeout => $timeout);
206         
207     return $conn;
208 }
209
210 sub start_program
211 {
212         my ($conn, $line, $sort) = @_;
213         my $pid;
214         
215 #       local $^F = 10000;              # make sure it ain't closed on exec
216 #       my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
217 #       if ($a && $b) {
218 #               $a->autoflush(1);
219 #               $b->autoflush(1);
220 #               $pid = fork;
221 #               if (defined $pid) {
222 #                       if ($pid) {
223 #                               close $b;
224 #                               $conn->{sock} = $a;
225 #                               $conn->{csort} = $sort;
226 #                               $conn->{lineend} = "\cM" if $sort eq 'ax25';
227 #                               $conn->{pid} = $pid;
228 #                               if ($conn->{rproc}) {
229 #                                       my $callback = sub {$conn->_rcv};
230 #                                       Msg::set_event_handler ($a, read => $callback);
231 #                               }
232 #                               dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
233 #                       } else {
234 #                               $^W = 0;
235 #                               dbgclose();
236 #                               STDIN->close;
237 #                               STDOUT->close;
238 #                               STDOUT->close;
239 #                               *STDIN = IO::File->new_from_fd($b, 'r') or die;
240 #                               *STDOUT = IO::File->new_from_fd($b, 'w') or die;
241 #                               *STDERR = IO::File->new_from_fd($b, 'w') or die;
242 #                               close $a;
243 #                               unless ($main::is_win) {
244 #                                       #                                               $SIG{HUP} = 'IGNORE';
245 #                                       $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
246 #                                       alarm(0);
247 #                               }
248 #                               exec "$line" or dbg("exec '$line' failed $!");
249 #                       } 
250 #               } else {
251 #                       dbg("cannot fork for $line");
252 #               }
253 #       } else {
254 #               dbg("no socket pair $! for $line");
255 #       }
256         return $pid;
257 }
258
259 sub disconnect
260 {
261         my $conn = shift;
262         my $count = $conn->{disconnecting}++;
263         my $dbg = isdbg('connll');
264         my ($pkg, $fn, $line) = caller if $dbg;
265
266         if ($count >= 2) {
267                 dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line FORCING CLOSE ") if $dbg;
268                 _close_it($conn);
269                 return;
270         }
271         dbg((ref $conn) . "::disconnect on call $conn->{call} attempt $conn->{disconnecting} called from ${pkg}::${fn} line $line ") if $dbg;
272         return if $count;
273
274         # remove this conn from the active queue
275         # be careful to delete the correct one
276         my $call;
277         if ($call = $conn->{call}) {
278                 my $ref = $conns{$call};
279                 delete $conns{$call} if $ref && $ref == $conn;
280         }
281         $call ||= 'unallocated';
282
283         $delqueue{$conn} = $conn; # save this connection until everything is finished
284         my $sock = $conn->{sock};
285         if ($sock) {
286                 if ($sock->{buffer}) {
287                         my $lth = length $sock->{buffer};
288                         Mojo::IOLoop->timer($disc_waittime, sub {
289                                                                         dbg("Buffer contained $lth characters, coordinated for $disc_waittime secs, now disconnecting $call") if $dbg;
290                                                                         _close_it($conn);
291                                                                 });
292                 } else {
293                         dbg("Buffer empty, just close $call") if $dbg;
294                         _close_it($conn);
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;
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                         if (isdbg('raw')) {
356                                 dbgdump('raw', "$call send $lth: ", $lth);
357                         }
358                 }
359                 if (defined $sock) {
360                         $sock->write($data);
361                         $total_out += $lth;
362                 } else {
363                         dbg("_send_stuff $call ending data ignored: $data");
364                 }
365         }
366 }
367
368 sub send_now {
369     my ($conn, $msg) = @_;
370     $conn->enqueue($msg);
371     _send_stuff($conn);
372 }
373
374 sub send_later {
375         goto &send_now;
376 }
377
378 sub send_raw
379 {
380     my ($conn, $msg) = @_;
381         push @{$conn->{outqueue}}, $msg;
382         _send_stuff($conn);
383 }
384
385 sub enqueue {
386     my $conn = shift;
387     push @{$conn->{outqueue}}, defined $_[0] ? $_[0] : '';
388 }
389
390 sub _err_will_block 
391 {
392         return 0;
393 }
394
395 sub close_on_empty
396 {
397         my $conn = shift;
398         $conn->{sock}->on(drain => sub {$conn->disconnect;});
399 }
400
401 #-----------------------------------------------------------------
402 # Receive side routines
403
404 sub new_server 
405 {
406 #    @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
407         my ($pkg, $my_host, $my_port, $login_proc) = @_;
408         my $conn = $pkg->new($login_proc);
409         
410     my $sock = $conn->{sock} = Mojo::IOLoop::Server->new;
411         $sock->on(accept=>sub{$conn->new_client($_[1]);});
412         $sock->listen(address=>$my_host, port=>$my_port);
413         $sock->start;
414         
415     die "Could not create socket: $! \n" unless $conn->{sock};
416         return $conn;
417 }
418
419
420 sub nolinger
421 {
422         my $conn = shift;
423 }
424
425 sub dequeue
426 {
427         my $conn = shift;
428         return if $conn->{disconnecting};
429         
430         if ($conn->{msg} =~ /\cJ/) {
431                 my @lines = split /\cM?\cJ/, $conn->{msg};
432                 if ($conn->{msg} =~ /\cM?\cJ$/) {
433                         delete $conn->{msg};
434                 } else {
435                         $conn->{msg} = pop @lines;
436                 }
437                 for (@lines) {
438                         last if $conn->{disconnecting};
439                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
440                 }
441         }
442 }
443
444 sub _rcv {                     # Complement to _send
445     my $conn = shift; # $rcv_now complement of $flush
446         my $msg = shift;
447     my $sock = $conn->{sock};
448     return unless defined($sock);
449         return if $conn->{disconnecting};
450
451         $total_in += length $msg;
452
453         my @lines;
454         if (isdbg('raw')) {
455                 my $call = $conn->{call} || 'none';
456                 my $lth = length $msg;
457                 dbgdump('raw', "$call read $lth: ", $msg);
458         }
459         if ($conn->{echo}) {
460                 my @ch = split //, $msg;
461                         my $out;
462                         for (@ch) {
463                                 if (/[\cH\x7f]/) {
464                                         $out .= "\cH \cH";
465                                         $conn->{msg} =~ s/.$//;
466                                 } else {
467                                         $out .= $_;
468                                         $conn->{msg} .= $_;
469                                 }
470                         }
471                         if (defined $out) {
472                                 $conn->send_raw($out);
473                         }
474         } else {
475                 $conn->{msg} .= $msg;
476         }
477
478         unless ($conn->{disable_read}) {
479                 $conn->dequeue if exists $conn->{msg};
480         }
481 }
482
483 sub new_client {
484         my $server_conn = shift;
485         my $handle = shift;
486         
487         my $conn = $server_conn->new($server_conn->{rproc});
488         my $sock = $conn->{sock} = Mojo::IOLoop::Stream->new($handle);
489         $sock->on(read => sub {$conn->_rcv($_[1])});
490         $sock->timeout(0);
491         $sock->start;
492         $conn->{peerhost} = $handle->peerhost;
493         $conn->{peerhost} =~ s|^::ffff:||; # chop off leading pseudo IPV6 stuff on dual stack listeners
494         $conn->{peerport} = $handle->peerport;
495         dbg((ref $conn) . " accept $conn->{cnum} from $conn->{peerhost}:$conn->{peerport}") if isdbg('connll');
496         my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost}, $conn->{peerport});
497         $conn->{sort} = 'Incoming';
498         if ($eproc) {
499                 $conn->{eproc} = $eproc;
500         }
501         if ($rproc) {
502                 $conn->{rproc} = $rproc;
503         } else {  # Login failed
504                 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
505                 $conn->disconnect();
506         }
507         return $conn;
508 }
509
510 sub close_server
511 {
512         my $conn = shift;
513         delete $conn->{sock};
514 }
515
516 # close all clients (this is for forking really)
517 sub close_all_clients
518 {
519         foreach my $conn (values %conns) {
520                 $conn->disconnect;
521         }
522 }
523
524 sub disable_read
525 {
526         my $conn = shift;
527         return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
528 }
529
530
531 #
532 #----------------------------------------------------
533 # Event loop routines used by both client and server
534
535 sub set_event_handler {
536         my $sock = shift;
537         my %args = @_;
538         my ($pkg, $fn, $line) = caller;
539         my $s;
540         foreach (my ($k,$v) = each %args) {
541                 $s .= "$k => $v, ";
542         }
543         $s =~ s/[\s,]$//;
544         dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
545 }
546
547 sub sleep
548 {
549         my ($pkg, $interval) = @_;
550         my $now = time;
551         while (time - $now < $interval) {
552                 sleep 1;
553         }
554 }
555
556 sub DESTROY
557 {
558         my $conn = shift;
559         my $call = $conn->{call} || 'unallocated';
560
561         if (isdbg('connll')) {
562                 my ($pkg, $fn, $line) = caller;
563                 dbg((ref $conn) . "::DESTROY on call $call called from ${pkg}::${fn} line $line ");
564                 
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