normalise peerhost on outgoing connects
[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 AnyEvent;
18 use AnyEvent::Handle;
19 use AnyEvent::Socket;
20
21 use DXDebug;
22 use Timer;
23
24 use vars qw(%conns $noconns $cnum $total_in $total_out);
25
26 $total_in = $total_out = 0;
27 $cnum = 0;
28
29 #
30 #-----------------------------------------------------------------
31 # Generalised initializer
32
33 sub new
34 {
35     my ($pkg, $rproc) = @_;
36         my $obj = ref($pkg);
37         my $class = $obj || $pkg;
38
39     my $conn = {
40         rproc => $rproc,
41                 inqueue => [],
42                 outqueue => [],
43                 state => 0,
44                 lineend => "\r\n",
45                 csort => 'telnet',
46                 timeval => 60,
47                 blocking => 0,
48                 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
49     };
50
51         $noconns++;
52         
53         dbg("Connection created ($noconns)") if isdbg('connll');
54         return bless $conn, $class;
55 }
56
57 sub set_error
58 {
59         my $conn = shift;
60         my $callback = shift;
61         $conn->{eproc} = $callback;
62 }
63
64 sub set_eof
65 {
66         my $conn = shift;
67         my $callback = shift;
68         $conn->{sock}->on_eof(sub {$callback});
69 }
70
71 sub set_rproc
72 {
73         my $conn = shift;
74         my $callback = shift;
75         $conn->{rproc} = $callback;
76 }
77
78 # save it
79 sub conns
80 {
81         my $pkg = shift;
82         my $call = shift;
83         my $ref;
84         
85         if (ref $pkg) {
86                 $call = $pkg->{call} unless $call;
87                 return undef unless $call;
88                 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
89                 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call; 
90                 $pkg->{call} = $call;
91                 $ref = $conns{$call} = $pkg;
92                 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
93         } else {
94                 $ref = $conns{$call};
95         }
96         return $ref;
97 }
98
99 # this is only called by any dependent processes going away unexpectedly
100 sub pid_gone
101 {
102         my ($pkg, $pid) = @_;
103         
104         my @pid = grep {$_->{pid} == $pid} values %conns;
105         foreach my $p (@pid) {
106                 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
107                 $p->disconnect;
108         }
109 }
110
111 sub ax25
112 {
113         my $conn = shift;
114         return $conn->{csort} eq 'ax25';
115 }
116
117 sub peerhost
118 {
119         my $conn = shift;
120         $conn->{peerhost} ||= 'ax25' if $conn->ax25;
121         $conn->{peerhost} ||= $conn->{sock}->peerhost if $conn->{sock} && $conn->{sock}->isa('IO::Socket::INET');
122         $conn->{peerhost} ||= 'UNKNOWN';
123         return $conn->{peerhost};
124 }
125
126 #-----------------------------------------------------------------
127 # Send side routines
128 sub connect {
129     my ($pkg, $to_host, $to_port, $rproc) = @_;
130
131     # Create a connection end-point object
132     my $conn = $pkg;
133         unless (ref $pkg) {
134                 $conn = $pkg->new($rproc);
135         }
136         $conn->{peerhost} = $to_host;
137         $conn->{peerport} = $to_port;
138         $conn->{sort} = 'Outgoing';
139         
140         my $sock = AnyEvent::Handle->new(
141
142                 connect => [$to_host, $to_port],
143
144                 on_connect => sub {my $h = shift; $conn->{peerhost} = shift;},
145
146                 on_eof => sub {$conn->disconnect},
147
148                 on_error => sub {$conn->disconnect},
149
150                 keepalive => 1,
151
152                 linger => 0,
153         );
154         
155         $conn->{sock} = $sock;
156         $sock->on_read(sub{$conn->_rcv});
157
158     return $conn;
159 }
160
161 sub start_program
162 {
163         my ($conn, $line, $sort) = @_;
164         my $pid;
165         
166 #       local $^F = 10000;              # make sure it ain't closed on exec
167 #       my ($a, $b) = $io_socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
168 #       if ($a && $b) {
169 #               $a->autoflush(1);
170 #               $b->autoflush(1);
171 #               $pid = fork;
172 #               if (defined $pid) {
173 #                       if ($pid) {
174 #                               close $b;
175 #                               $conn->{sock} = $a;
176 #                               $conn->{csort} = $sort;
177 #                               $conn->{lineend} = "\cM" if $sort eq 'ax25';
178 #                               $conn->{pid} = $pid;
179 #                               if ($conn->{rproc}) {
180 #                                       my $callback = sub {$conn->_rcv};
181 #                                       Msg::set_event_handler ($a, read => $callback);
182 #                               }
183 #                               dbg("connect $conn->{cnum}: started pid: $conn->{pid} as $line") if isdbg('connect');
184 #                       } else {
185 #                               $^W = 0;
186 #                               dbgclose();
187 #                               STDIN->close;
188 #                               STDOUT->close;
189 #                               STDOUT->close;
190 #                               *STDIN = IO::File->new_from_fd($b, 'r') or die;
191 #                               *STDOUT = IO::File->new_from_fd($b, 'w') or die;
192 #                               *STDERR = IO::File->new_from_fd($b, 'w') or die;
193 #                               close $a;
194 #                               unless ($main::is_win) {
195 #                                       #                                               $SIG{HUP} = 'IGNORE';
196 #                                       $SIG{HUP} = $SIG{CHLD} = $SIG{TERM} = $SIG{INT} = 'DEFAULT';
197 #                                       alarm(0);
198 #                               }
199 #                               exec "$line" or dbg("exec '$line' failed $!");
200 #                       }
201 #               } else {
202 #                       dbg("cannot fork for $line");
203 #               }
204 #       } else {
205 #               dbg("no socket pair $! for $line");
206 #       }
207         return $pid;
208 }
209
210 sub disconnect 
211 {
212     my $conn = shift;
213         return if exists $conn->{disconnecting};
214
215         $conn->{disconnecting} = 1;
216     my $sock = delete $conn->{sock};
217         $conn->{state} = 'E';
218         $conn->{timeout}->del if $conn->{timeout};
219
220         # be careful to delete the correct one
221         my $call;
222         if ($call = $conn->{call}) {
223                 my $ref = $conns{$call};
224                 delete $conns{$call} if $ref && $ref == $conn;
225         }
226         $call ||= 'unallocated';
227         dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
228         
229         # get rid of any references
230         for (keys %$conn) {
231                 if (ref($conn->{$_})) {
232                         delete $conn->{$_};
233                 }
234         }
235
236         if (defined($sock)) {
237                 shutdown($sock->{fh}, 2);
238                 $sock->destroy;
239         }
240         
241         unless ($main::is_win) {
242                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
243         }
244 }
245
246 sub _send_stuff
247 {
248     my $conn = shift;
249         my $rq = $conn->{outqueue};
250         my $sock = $conn->{sock};
251
252         while (@$rq) {
253                 my $data = shift @$rq;
254                 my $lth = length $data;
255                 my $call = $conn->{call} || 'none';
256                 if (isdbg('raw')) {
257                         if (isdbg('raw')) {
258                                 dbgdump('raw', "$call send $lth: ", $lth);
259                         }
260                 }
261                 if (defined $sock && !$sock->destroyed) {
262                         $sock->push_write($data);
263                         $total_out = $lth;
264                 } else {
265                         dbg("_send_stuff $call ending data ignored: $data");
266                 }
267         }
268 }
269
270 sub send_later {
271     my ($conn, $msg) = @_;
272         my $rq = $conn->{outqueue};
273         my $sock = $conn->{sock};
274
275         # this is done like this because enqueueing may be going on independently of
276         # sending (whether later or now)
277     $conn->enqueue($msg);
278         _send_stuff($conn)
279 }
280
281 sub send_now { goto &send_later; }
282
283 sub send_raw
284 {
285     my ($conn, $msg) = @_;
286         push @{$conn->{outqueue}}, $msg;
287         _send_stuff($conn);
288 }
289
290 sub enqueue {
291     my $conn = shift;
292     push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
293 }
294
295 sub _err_will_block {
296         return 0;
297 }
298
299 sub close_on_empty
300 {
301         my $conn = shift;
302         $conn->{sock}->on_drain(sub {$conn->disconnect;});
303 }
304
305 #-----------------------------------------------------------------
306 # Receive side routines
307
308 sub new_server {
309     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
310     my ($pkg, $my_host, $my_port, $login_proc) = @_;
311         my $self = $pkg->new($login_proc);
312         
313     $self->{sock} = tcp_server $my_host, $my_port, sub { $self->new_client(@_); }, sub { return 256; };
314     die "Could not create socket: $! \n" unless $self->{sock};
315         return $self;
316 }
317
318
319 sub nolinger
320 {
321         my $conn = shift;
322         my $sock = $conn->{sock};
323 #       $sock->linger(0);
324 #       $sock->keepalive(1);
325 }
326
327 sub dequeue
328 {
329         my $conn = shift;
330
331         if ($conn->{msg} =~ /\n/) {
332                 my @lines = split /\r?\n/, $conn->{msg};
333                 if ($conn->{msg} =~ /\n$/) {
334                         delete $conn->{msg};
335                 } else {
336                         $conn->{msg} = pop @lines;
337                 }
338                 for (@lines) {
339                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
340                 }
341         }
342 }
343
344 sub _rcv {                     # Complement to _send
345     my $conn = shift; # $rcv_now complement of $flush
346     # Find out how much has already been received, if at all
347     my ($msg, $offset, $bytes_to_read, $bytes_read);
348     my $sock = $conn->{sock};
349     return unless defined($sock);
350
351         my @lines;
352         $msg = $sock->{rbuf};
353         $bytes_read = length $msg || 0;
354         $sock->{rbuf} = '';
355
356         if ($bytes_read > 0) {
357                 $total_in += $bytes_read;
358                 if (isdbg('raw')) {
359                         my $call = $conn->{call} || 'none';
360                         dbgdump('raw', "$call read $bytes_read: ", $msg);
361                 }
362                 if ($conn->{echo}) {
363                         my @ch = split //, $msg;
364                         my $out;
365                         for (@ch) {
366                                 if (/[\cH\x7f]/) {
367                                         $out .= "\cH \cH";
368                                         $conn->{msg} =~ s/.$//;
369                                 } else {
370                                         $out .= $_;
371                                         $conn->{msg} .= $_;
372                                 }
373                         }
374                         if (defined $out) {
375                                 $conn->send_now($out);
376                         }
377                 } else {
378                         $conn->{msg} .= $msg;
379                 }
380         }
381
382         unless ($conn->{disable_read}) {
383                 $conn->dequeue if exists $conn->{msg};
384         }
385 }
386
387 sub new_client {
388         my $server_conn = shift;
389         my $sock = shift;
390         my $peerhost = shift;
391         my $peerport = shift;
392         if ($sock) {
393                 my $conn = $server_conn->new($server_conn->{rproc});
394                 $conn->{sock} = AnyEvent::Handle->new(
395
396             fh => $sock,
397
398                     on_eof => sub {$conn->disconnect},
399
400                     on_error => sub {$conn->disconnect},
401
402                     keepalive => 1,
403
404                     linger => 0,
405             );
406                 $conn->{blocking} = 0;
407                 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $peerhost, $conn->{peerport} = $peerport);
408                 dbg("accept $conn->{cnum} from $conn->{peerhost} $conn->{peerport}") if isdbg('connll');
409                 $conn->{sort} = 'Incoming';
410                 if ($eproc) {
411                         $conn->{eproc} = $eproc;
412                 }
413                 if ($rproc) {
414                         $conn->{rproc} = $rproc;
415                         $conn->{sock}->on_read(sub {$conn->_rcv});
416                 } else {  # Login failed
417                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
418                         $conn->disconnect();
419                 }
420         } else {
421                 dbg("Msg: error on accept ($!)") if isdbg('err');
422         }
423 }
424
425 sub close_server
426 {
427         my $conn = shift;
428         undef $conn->{sock};
429 }
430
431 # close all clients (this is for forking really)
432 sub close_all_clients
433 {
434         foreach my $conn (values %conns) {
435                 $conn->disconnect;
436         }
437 }
438
439 sub disable_read
440 {
441         my $conn = shift;
442         return defined $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
443 }
444
445 sub sleep
446 {
447         my ($pkg, $interval) = @_;
448         my $cv = AnyEvent->condvar;
449         my $wait_a_bit = AnyEvent->timer(
450                                                                          after => $interval,
451                                                                          cb => sub {$cv->send},
452                                                                         );
453         $cv->recv;
454 }
455
456 sub set_event_handler
457 {
458         my $sock = shift;
459         my %args = @_;
460         my ($pkg, $fn, $line) = caller;
461         my $s;
462         foreach (my ($k,$v) = each %args) {
463                 $s .= "$k => $v, ";
464         }
465         $s =~ s/[\s,]$//;
466         dbg("Msg::set_event_handler called from ${pkg}::${fn} line $line doing $s");
467 }
468
469 sub echo
470 {
471         my $conn = shift;
472         return defined $_[0] ? $conn->{echo} = $_[0] : $_[0];
473 }
474
475 sub DESTROY
476 {
477         my $conn = shift;
478         my $call = $conn->{call} || 'unallocated';
479         my $host = $conn->{peerhost} || '';
480         my $port = $conn->{peerport} || '';
481         dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');
482         $noconns--;
483 }
484
485 1;
486
487 __END__
488