put in a prototype echo handler in Msg/ExtMsg
[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 # $Id$
9 #
10
11 package Msg;
12
13 use strict;
14
15 use vars qw($VERSION $BRANCH);
16 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
17 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/ ) || 0;
18 $main::build += $VERSION;
19 $main::branch += $BRANCH;
20
21 use IO::Select;
22 use IO::Socket;
23 use DXDebug;
24 use Timer;
25
26 use vars qw(%rd_callbacks %wt_callbacks %er_callbacks $rd_handles $wt_handles $er_handles $now %conns $noconns $blocking_supported $cnum);
27
28 %rd_callbacks = ();
29 %wt_callbacks = ();
30 %er_callbacks = ();
31 $rd_handles   = IO::Select->new();
32 $wt_handles   = IO::Select->new();
33 $er_handles   = IO::Select->new();
34
35 $now = time;
36
37 BEGIN {
38     # Checks if blocking is supported
39     eval {
40         require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
41     };
42         if ($@ || $main::is_win) {
43 #               print STDERR "POSIX Blocking *** NOT *** supported $@\n";
44                 $blocking_supported = 0;
45         } else {
46                 $blocking_supported = 1;
47 #               print STDERR "POSIX Blocking enabled\n";
48         }
49
50
51         # import as many of these errno values as are available
52         eval {
53                 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
54         };
55 }
56
57 my $w = $^W;
58 $^W = 0;
59 my $eagain = eval {EAGAIN()};
60 my $einprogress = eval {EINPROGRESS()};
61 my $ewouldblock = eval {EWOULDBLOCK()};
62 $^W = $w;
63 $cnum = 0;
64
65
66 #
67 #-----------------------------------------------------------------
68 # Generalised initializer
69
70 sub new
71 {
72     my ($pkg, $rproc) = @_;
73         my $obj = ref($pkg);
74         my $class = $obj || $pkg;
75
76     my $conn = {
77         rproc => $rproc,
78                 inqueue => [],
79                 outqueue => [],
80                 state => 0,
81                 lineend => "\r\n",
82                 csort => 'telnet',
83                 timeval => 60,
84                 blocking => 0,
85                 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
86     };
87
88         $noconns++;
89         
90         dbg("Connection created ($noconns)") if isdbg('connll');
91         return bless $conn, $class;
92 }
93
94 sub set_error
95 {
96         my $conn = shift;
97         my $callback = shift;
98         $conn->{eproc} = $callback;
99         set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
100 }
101
102 sub set_rproc
103 {
104         my $conn = shift;
105         my $callback = shift;
106         $conn->{rproc} = $callback;
107 }
108
109 sub blocking
110 {
111         return unless $blocking_supported;
112         
113         my $flags = fcntl ($_[0], F_GETFL, 0);
114         if ($_[1]) {
115                 $flags &= ~O_NONBLOCK;
116         } else {
117                 $flags |= O_NONBLOCK;
118         }
119         fcntl ($_[0], F_SETFL, $flags);
120 }
121
122 # save it
123 sub conns
124 {
125         my $pkg = shift;
126         my $call = shift;
127         my $ref;
128         
129         if (ref $pkg) {
130                 $call = $pkg->{call} unless $call;
131                 return undef unless $call;
132                 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
133                 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call; 
134                 $pkg->{call} = $call;
135                 $ref = $conns{$call} = $pkg;
136                 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
137         } else {
138                 $ref = $conns{$call};
139         }
140         return $ref;
141 }
142
143 # this is only called by any dependent processes going away unexpectedly
144 sub pid_gone
145 {
146         my ($pkg, $pid) = @_;
147         
148         my @pid = grep {$_->{pid} == $pid} values %conns;
149         foreach my $p (@pid) {
150                 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
151                 $p->disconnect;
152         }
153 }
154
155 #-----------------------------------------------------------------
156 # Send side routines
157 sub connect {
158     my ($pkg, $to_host, $to_port, $rproc) = @_;
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     # Create a new internet socket
170     my $sock = IO::Socket::INET->new();
171     return undef unless $sock;
172         
173         my $proto = getprotobyname('tcp');
174         $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
175         
176         blocking($sock, 0);
177         $conn->{blocking} = 0;
178
179         my $ip = gethostbyname($to_host);
180 #       my $r = $sock->connect($to_port, $ip);
181         my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
182         return undef unless $r || _err_will_block($!);
183         
184         $conn->{sock} = $sock;
185     
186     if ($conn->{rproc}) {
187         my $callback = sub {$conn->_rcv};
188         set_event_handler ($sock, read => $callback);
189     }
190     return $conn;
191 }
192
193 sub disconnect {
194     my $conn = shift;
195         return if exists $conn->{disconnecting};
196
197         $conn->{disconnecting} = 1;
198     my $sock = delete $conn->{sock};
199         $conn->{state} = 'E';
200         $conn->{timeout}->del if $conn->{timeout};
201
202         # be careful to delete the correct one
203         my $call;
204         if ($call = $conn->{call}) {
205                 my $ref = $conns{$call};
206                 delete $conns{$call} if $ref && $ref == $conn;
207         }
208         $call ||= 'unallocated';
209         dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
210         
211         unless ($main::is_win) {
212                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
213         }
214
215         # get rid of any references
216         for (keys %$conn) {
217                 if (ref($conn->{$_})) {
218                         delete $conn->{$_};
219                 }
220         }
221
222         return unless defined($sock);
223     set_event_handler ($sock, read => undef, write => undef, error => undef);
224     shutdown($sock, 3);
225         close($sock);
226 }
227
228 sub send_now {
229     my ($conn, $msg) = @_;
230     $conn->enqueue($msg);
231     $conn->_send (1); # 1 ==> flush
232 }
233
234 sub send_later {
235     my ($conn, $msg) = @_;
236     $conn->enqueue($msg);
237     my $sock = $conn->{sock};
238     return unless defined($sock);
239     set_event_handler ($sock, write => sub {$conn->_send(0)});
240 }
241
242 sub enqueue {
243     my $conn = shift;
244     push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
245 }
246
247 sub _send {
248     my ($conn, $flush) = @_;
249     my $sock = $conn->{sock};
250     return unless defined($sock);
251     my $rq = $conn->{outqueue};
252
253     # If $flush is set, set the socket to blocking, and send all
254     # messages in the queue - return only if there's an error
255     # If $flush is 0 (deferred mode) make the socket non-blocking, and
256     # return to the event loop only after every message, or if it
257     # is likely to block in the middle of a message.
258
259         if ($conn->{blocking} != $flush) {
260                 blocking($sock, $flush);
261                 $conn->{blocking} = $flush;
262         }
263     my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
264
265     while (@$rq) {
266         my $msg            = $rq->[0];
267                 my $mlth           = length($msg);
268         my $bytes_to_write = $mlth - $offset;
269         my $bytes_written  = 0;
270                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
271         while ($bytes_to_write > 0) {
272             $bytes_written = syswrite ($sock, $msg,
273                                        $bytes_to_write, $offset);
274             if (!defined($bytes_written)) {
275                 if (_err_will_block($!)) {
276                     # Should happen only in deferred mode. Record how
277                     # much we have already sent.
278                     $conn->{send_offset} = $offset;
279                     # Event handler should already be set, so we will
280                     # be called back eventually, and will resume sending
281                     return 1;
282                 } else {    # Uh, oh
283                                         &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
284                                         $conn->disconnect;
285                     return 0; # fail. Message remains in queue ..
286                 }
287             } elsif (isdbg('raw')) {
288                                 my $call = $conn->{call} || 'none';
289                                 dbgdump('raw', "$call send $bytes_written: ", $msg);
290                         }
291             $offset         += $bytes_written;
292             $bytes_to_write -= $bytes_written;
293         }
294         delete $conn->{send_offset};
295         $offset = 0;
296         shift @$rq;
297         #last unless $flush; # Go back to select and wait
298                             # for it to fire again.
299     }
300     # Call me back if queue has not been drained.
301     unless (@$rq) {
302         set_event_handler ($sock, write => undef);
303                 if (exists $conn->{close_on_empty}) {
304                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
305                         $conn->disconnect; 
306                 }
307     }
308     1;  # Success
309 }
310
311 sub dup_sock
312 {
313         my $conn = shift;
314         my $oldsock = $conn->{sock};
315         my $rc = $rd_callbacks{$oldsock};
316         my $wc = $wt_callbacks{$oldsock};
317         my $ec = $er_callbacks{$oldsock};
318         my $sock = $oldsock->new_from_fd($oldsock, "w+");
319         if ($sock) {
320                 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
321                 $conn->{sock} = $sock;
322                 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
323                 $oldsock->close;
324         }
325 }
326
327 sub _err_will_block {
328         return 0 unless $blocking_supported;
329         return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
330 }
331
332 sub close_on_empty
333 {
334         my $conn = shift;
335         $conn->{close_on_empty} = 1;
336 }
337
338 #-----------------------------------------------------------------
339 # Receive side routines
340
341 sub new_server {
342     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
343     my ($pkg, $my_host, $my_port, $login_proc) = @_;
344         my $self = $pkg->new($login_proc);
345         
346     $self->{sock} = IO::Socket::INET->new (
347                                           LocalAddr => $my_host,
348                                           LocalPort => $my_port,
349                                           Listen    => SOMAXCONN,
350                                           Proto     => 'tcp',
351                                           Reuse     => 1);
352     die "Could not create socket: $! \n" unless $self->{sock};
353     set_event_handler ($self->{sock}, read => sub { $self->new_client }  );
354         return $self;
355 }
356
357 sub dequeue
358 {
359         my $conn = shift;
360
361         if ($conn->{msg} =~ /\n/) {
362                 my @lines = split /\r?\n/, $conn->{msg};
363                 if ($conn->{msg} =~ /\n$/) {
364                         delete $conn->{msg};
365                 } else {
366                         $conn->{msg} = pop @lines;
367                 }
368                 for (@lines) {
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     # Find out how much has already been received, if at all
377     my ($msg, $offset, $bytes_to_read, $bytes_read);
378     my $sock = $conn->{sock};
379     return unless defined($sock);
380
381         my @lines;
382         if ($conn->{blocking}) {
383                 blocking($sock, 0);
384                 $conn->{blocking} = 0;
385         }
386         $bytes_read = sysread ($sock, $msg, 1024, 0);
387         if (defined ($bytes_read)) {
388                 if ($bytes_read > 0) {
389                         if (isdbg('raw')) {
390                                 my $call = $conn->{call} || 'none';
391                                 dbgdump('raw', "$call read $bytes_read: ", $msg);
392                         }
393                         if ($conn->{echo}) {
394                                 my @ch = split //, $msg;
395                                 my $out;
396                                 for (@ch) {
397                                         if (/[\cH\x7f]/) {
398                                                 $out .= "\cH \cH";
399                                                 $conn->{msg} =~ s/.$//;
400                                         } else {
401                                                 $out .= $_;
402                                                 $conn->{msg} .= $_;
403                                         }
404                                 }
405                                 if (defined $out) {
406                                         set_event_handler ($sock, write => sub{$conn->_send(0)});
407                                         push @{$conn->{outqueue}}, $out;
408                                 }
409                         } else {
410                                 $conn->{msg} .= $msg;
411                         }
412                 } 
413         } else {
414                 if (_err_will_block($!)) {
415                         return ; 
416                 } else {
417                         $bytes_read = 0;
418                 }
419     }
420
421 FINISH:
422     if (defined $bytes_read && $bytes_read == 0) {
423                 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
424                 $conn->disconnect;
425     } else {
426                 unless ($conn->{disable_read}) {
427                         $conn->dequeue if exists $conn->{msg};
428                 }
429         }
430 }
431
432 sub new_client {
433         my $server_conn = shift;
434     my $sock = $server_conn->{sock}->accept();
435         if ($sock) {
436                 my $conn = $server_conn->new($server_conn->{rproc});
437                 $conn->{sock} = $sock;
438                 blocking($sock, 0);
439                 $conn->{blocking} = 0;
440                 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
441                 $conn->{sort} = 'Incoming';
442                 if ($eproc) {
443                         $conn->{eproc} = $eproc;
444                         set_event_handler ($sock, error => $eproc);
445                 }
446                 if ($rproc) {
447                         $conn->{rproc} = $rproc;
448                         my $callback = sub {$conn->_rcv};
449                         set_event_handler ($sock, read => $callback);
450                 } else {  # Login failed
451                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
452                         $conn->disconnect();
453                 }
454         } else {
455                 dbg("Msg: error on accept ($!)") if isdbg('err');
456         }
457 }
458
459 sub close_server
460 {
461         my $conn = shift;
462         set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
463         $conn->{sock}->close;
464 }
465
466 # close all clients (this is for forking really)
467 sub close_all_clients
468 {
469         foreach my $conn (values %conns) {
470                 $conn->disconnect;
471         }
472 }
473
474 sub disable_read
475 {
476         my $conn = shift;
477         set_event_handler ($conn->{sock}, read => undef);
478         return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
479 }
480
481 #
482 #----------------------------------------------------
483 # Event loop routines used by both client and server
484
485 sub set_event_handler {
486     shift unless ref($_[0]); # shift if first arg is package name
487     my ($handle, %args) = @_;
488     my $callback;
489     if (exists $args{'write'}) {
490         $callback = $args{'write'};
491         if ($callback) {
492             $wt_callbacks{$handle} = $callback;
493             $wt_handles->add($handle);
494         } else {
495             delete $wt_callbacks{$handle};
496             $wt_handles->remove($handle);
497         }
498     }
499     if (exists $args{'read'}) {
500         $callback = $args{'read'};
501         if ($callback) {
502             $rd_callbacks{$handle} = $callback;
503             $rd_handles->add($handle);
504         } else {
505             delete $rd_callbacks{$handle};
506             $rd_handles->remove($handle);
507        }
508     }
509     if (exists $args{'error'}) {
510         $callback = $args{'error'};
511         if ($callback) {
512             $er_callbacks{$handle} = $callback;
513             $er_handles->add($handle);
514         } else {
515             delete $er_callbacks{$handle};
516             $er_handles->remove($handle);
517        }
518     }
519 }
520
521 sub event_loop {
522     my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
523     my ($conn, $r, $w, $e, $rset, $wset, $eset);
524     while (1) {
525  
526        # Quit the loop if no handles left to process
527         last unless ($rd_handles->count() || $wt_handles->count());
528         
529                 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
530                 
531         foreach $e (@$eset) {
532             &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
533         }
534         foreach $r (@$rset) {
535             &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
536         }
537         foreach $w (@$wset) {
538             &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
539         }
540
541                 Timer::handler;
542                 
543         if (defined($loop_count)) {
544             last unless --$loop_count;
545         }
546     }
547 }
548
549 sub sleep
550 {
551         my ($pkg, $interval) = @_;
552         my $now = time;
553         while (time - $now < $interval) {
554                 $pkg->event_loop(10, 0.01);
555         }
556 }
557
558 sub DESTROY
559 {
560         my $conn = shift;
561         my $call = $conn->{call} || 'unallocated';
562         my $host = $conn->{peerhost} || '';
563         my $port = $conn->{peerport} || '';
564         dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');
565         $noconns--;
566 }
567
568 1;
569
570 __END__
571