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