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