add various eph timings and variables to control them
[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:$my_port",
348 #                                          LocalPort => $my_port,
349                                           Listen    => SOMAXCONN,
350                                           Proto     => 'tcp',
351                                           ReuseAddr => 1,
352                                                                                   );
353     die "Could not create socket: $! \n" unless $self->{sock};
354     set_event_handler ($self->{sock}, read => sub { $self->new_client }  );
355         return $self;
356 }
357
358 sub dequeue
359 {
360         my $conn = shift;
361
362         if ($conn->{msg} =~ /\n/) {
363                 my @lines = split /\r?\n/, $conn->{msg};
364                 if ($conn->{msg} =~ /\n$/) {
365                         delete $conn->{msg};
366                 } else {
367                         $conn->{msg} = pop @lines;
368                 }
369                 for (@lines) {
370                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
371                 }
372         }
373 }
374
375 sub _rcv {                     # Complement to _send
376     my $conn = shift; # $rcv_now complement of $flush
377     # Find out how much has already been received, if at all
378     my ($msg, $offset, $bytes_to_read, $bytes_read);
379     my $sock = $conn->{sock};
380     return unless defined($sock);
381
382         my @lines;
383         if ($conn->{blocking}) {
384                 blocking($sock, 0);
385                 $conn->{blocking} = 0;
386         }
387         $bytes_read = sysread ($sock, $msg, 1024, 0);
388         if (defined ($bytes_read)) {
389                 if ($bytes_read > 0) {
390                         if (isdbg('raw')) {
391                                 my $call = $conn->{call} || 'none';
392                                 dbgdump('raw', "$call read $bytes_read: ", $msg);
393                         }
394                         if ($conn->{echo}) {
395                                 my @ch = split //, $msg;
396                                 my $out;
397                                 for (@ch) {
398                                         if (/[\cH\x7f]/) {
399                                                 $out .= "\cH \cH";
400                                                 $conn->{msg} =~ s/.$//;
401                                         } else {
402                                                 $out .= $_;
403                                                 $conn->{msg} .= $_;
404                                         }
405                                 }
406                                 if (defined $out) {
407                                         set_event_handler ($sock, write => sub{$conn->_send(0)});
408                                         push @{$conn->{outqueue}}, $out;
409                                 }
410                         } else {
411                                 $conn->{msg} .= $msg;
412                         }
413                 } 
414         } else {
415                 if (_err_will_block($!)) {
416                         return ; 
417                 } else {
418                         $bytes_read = 0;
419                 }
420     }
421
422 FINISH:
423     if (defined $bytes_read && $bytes_read == 0) {
424                 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
425                 $conn->disconnect;
426     } else {
427                 unless ($conn->{disable_read}) {
428                         $conn->dequeue if exists $conn->{msg};
429                 }
430         }
431 }
432
433 sub new_client {
434         my $server_conn = shift;
435     my $sock = $server_conn->{sock}->accept();
436         if ($sock) {
437                 my $conn = $server_conn->new($server_conn->{rproc});
438                 $conn->{sock} = $sock;
439                 blocking($sock, 0);
440                 $conn->{blocking} = 0;
441                 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
442                 $conn->{sort} = 'Incoming';
443                 if ($eproc) {
444                         $conn->{eproc} = $eproc;
445                         set_event_handler ($sock, error => $eproc);
446                 }
447                 if ($rproc) {
448                         $conn->{rproc} = $rproc;
449                         my $callback = sub {$conn->_rcv};
450                         set_event_handler ($sock, read => $callback);
451                 } else {  # Login failed
452                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
453                         $conn->disconnect();
454                 }
455         } else {
456                 dbg("Msg: error on accept ($!)") if isdbg('err');
457         }
458 }
459
460 sub close_server
461 {
462         my $conn = shift;
463         set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
464         $conn->{sock}->close;
465 }
466
467 # close all clients (this is for forking really)
468 sub close_all_clients
469 {
470         foreach my $conn (values %conns) {
471                 $conn->disconnect;
472         }
473 }
474
475 sub disable_read
476 {
477         my $conn = shift;
478         set_event_handler ($conn->{sock}, read => undef);
479         return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
480 }
481
482 #
483 #----------------------------------------------------
484 # Event loop routines used by both client and server
485
486 sub set_event_handler {
487     shift unless ref($_[0]); # shift if first arg is package name
488     my ($handle, %args) = @_;
489     my $callback;
490     if (exists $args{'write'}) {
491         $callback = $args{'write'};
492         if ($callback) {
493             $wt_callbacks{$handle} = $callback;
494             $wt_handles->add($handle);
495         } else {
496             delete $wt_callbacks{$handle};
497             $wt_handles->remove($handle);
498         }
499     }
500     if (exists $args{'read'}) {
501         $callback = $args{'read'};
502         if ($callback) {
503             $rd_callbacks{$handle} = $callback;
504             $rd_handles->add($handle);
505         } else {
506             delete $rd_callbacks{$handle};
507             $rd_handles->remove($handle);
508        }
509     }
510     if (exists $args{'error'}) {
511         $callback = $args{'error'};
512         if ($callback) {
513             $er_callbacks{$handle} = $callback;
514             $er_handles->add($handle);
515         } else {
516             delete $er_callbacks{$handle};
517             $er_handles->remove($handle);
518        }
519     }
520 }
521
522 sub event_loop {
523     my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
524     my ($conn, $r, $w, $e, $rset, $wset, $eset);
525     while (1) {
526  
527        # Quit the loop if no handles left to process
528         last unless ($rd_handles->count() || $wt_handles->count());
529         
530                 ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
531                 
532         foreach $e (@$eset) {
533             &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
534         }
535         foreach $r (@$rset) {
536             &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
537         }
538         foreach $w (@$wset) {
539             &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
540         }
541
542                 Timer::handler;
543                 
544         if (defined($loop_count)) {
545             last unless --$loop_count;
546         }
547     }
548 }
549
550 sub sleep
551 {
552         my ($pkg, $interval) = @_;
553         my $now = time;
554         while (time - $now < $interval) {
555                 $pkg->event_loop(10, 0.01);
556         }
557 }
558
559 sub DESTROY
560 {
561         my $conn = shift;
562         my $call = $conn->{call} || 'unallocated';
563         my $host = $conn->{peerhost} || '';
564         my $port = $conn->{peerport} || '';
565         dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');
566         $noconns--;
567 }
568
569 1;
570
571 __END__
572