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