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