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