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