fix disconnect from peer
[spider.git] / perl / DXChannel.pm
1 #
2 # module to manage channel lists & data
3 #
4 # This is the base class for all channel operations, which is everything to do 
5 # with input and output really.
6 #
7 # The instance variable in the outside world will be generally be called $dxchan
8 #
9 # This class is 'inherited' (if that is the goobledegook for what I am doing)
10 # by various other modules. The point to understand is that the 'instance variable'
11 # is in fact what normal people would call the state vector and all useful info
12 # about a connection goes in there.
13 #
14 # Another point to note is that a vector may contain a list of other vectors. 
15 # I have simply added another variable to the vector for 'simplicity' (or laziness
16 # as it is more commonly called)
17 #
18 # PLEASE NOTE - I am a C programmer using this as a method of learning perl
19 # firstly and OO about ninthly (if you don't like the design and you can't 
20 # improve it with better OO and thus make it smaller and more efficient, then tough). 
21 #
22 # Copyright (c) 1998-2000 - Dirk Koopman G1TLH
23 #
24 #
25 #
26 package DXChannel;
27
28 use Msg;
29 use DXM;
30 use DXUtil;
31 use DXVars;
32 use DXDebug;
33 use Filter;
34 use Prefix;
35 use Route;
36
37 use strict;
38 use vars qw(%channels %valid @ISA $count $maxerrors);
39
40 %channels = ();
41 $count = 0;
42
43 %valid = (
44                   call => '0,Callsign',
45                   conn => '9,Msg Conn ref',
46                   user => '9,DXUser ref',
47                   startt => '0,Start Time,atime',
48                   t => '9,Time,atime',
49                   pc50_t => '5,Last PC50 Time,atime',
50                   priv => '9,Privilege',
51                   state => '0,Current State',
52                   oldstate => '5,Last State',
53                   list => '9,Dep Chan List',
54                   name => '0,User Name',
55                   consort => '5,Connection Type',
56                   'sort' => '5,Type of Channel',
57                   wwv => '0,Want WWV,yesno',
58                   wcy => '0,Want WCY,yesno',
59                   wx => '0,Want WX,yesno',
60                   talk => '0,Want Talk,yesno',
61                   ann => '0,Want Announce,yesno',
62                   here => '0,Here?,yesno',
63                   conf => '0,In Conference?,yesno',
64                   dx => '0,DX Spots,yesno',
65                   redirect => '0,Redirect messages to',
66                   lang => '0,Language',
67                   func => '5,Function',
68                   loc => '9,Local Vars', # used by func to store local variables in
69                   beep => '0,Want Beeps,yesno',
70                   lastread => '5,Last Msg Read',
71                   outbound => '5,outbound?,yesno',
72                   remotecmd => '9,doing rcmd,yesno',
73                   pagelth => '0,Page Length',
74                   pagedata => '9,Page Data Store',
75                   group => '0,Access Group,parray',     # used to create a group of users/nodes for some purpose or other
76                   isolate => '5,Isolate network,yesno',
77                   delayed => '5,Delayed messages,parray',
78                   annfilter => '5,Ann Filt-out',
79                   wwvfilter => '5,WWV Filt-out',
80                   wcyfilter => '5,WCY Filt-out',
81                   spotsfilter => '5,Spot Filt-out',
82                   routefilter => '5,Route Filt-out',
83                   pc92filter => '5,PC92 Route Filt-out',
84                   inannfilter => '5,Ann Filt-inp',
85                   inwwvfilter => '5,WWV Filt-inp',
86                   inwcyfilter => '5,WCY Filt-inp',
87                   inspotsfilter => '5,Spot Filt-inp',
88                   inroutefilter => '5,Route Filt-inp',
89                   inpc92filter => '5,PC92 Route Filt-inp',
90                   passwd => '9,Passwd List,yesno',
91                   pingint => '5,Ping Interval ',
92                   nopings => '5,Ping Obs Count',
93                   lastping => '5,Ping last sent,atime',
94                   pingtime => '5,Ping totaltime,parray',
95                   pingave => '0,Ping ave time',
96                   logininfo => '9,Login info req,yesno',
97                   talklist => '0,Talk List,parray',
98                   cluster => '5,Cluster data',
99                   isbasic => '9,Internal Connection', 
100                   errors => '9,Errors',
101                   route => '9,Route Data',
102                   dxcc => '0,Country Code',
103                   itu => '0,ITU Zone',
104                   cq => '0,CQ Zone',
105                   enhanced => '5,Enhanced Client,yesno',
106                   gtk => '5,Using GTK,yesno',
107                   senddbg => '8,Sending Debug,yesno',
108                   width => '0,Column Width',
109                   disconnecting => '9,Disconnecting,yesno',
110                   ann_talk => '0,Suppress Talk Anns,yesno',
111                   metric => '1,Route metric',
112                   badcount => '1,Bad Word Count',
113                   edit => '7,Edit Function',
114                   registered => '9,Registered?,yesno',
115                   prompt => '0,Required Prompt',
116                   version => '1,Node Version',
117                   build => '1,Node Build',
118                   verified => '9,Verified?,yesno',
119                   newroute => '1,New Style Routing,yesno',
120                   ve7cc => '0,VE7CC program special,yesno',
121                   lastmsgpoll => '0,Last Msg Poll,atime',
122                   inscript => '9,In a script,yesno',
123                   handle_xml => '9,Handles XML,yesno',
124                   do_pc9x => '9,Handles PC9x,yesno',
125                   inqueue => '9,Input Queue,parray',
126                   next_pc92_update => '9,Next PC92 Update,atime',
127                   next_pc92_keepalive => '9,Next PC92 KeepAlive,atime',
128                  );
129
130 $maxerrors = 20;                                # the maximum number of concurrent errors allowed before disconnection
131
132 # object destruction
133 sub DESTROY
134 {
135         my $self = shift;
136         for (keys %$self) {
137                 if (ref($self->{$_})) {
138                         delete $self->{$_};
139                 }
140         }
141         dbg("DXChannel $self->{call} destroyed ($count)") if isdbg('chan');
142         $count--;
143 }
144
145 # create a new channel object [$obj = DXChannel->new($call, $msg_conn_obj, $user_obj)]
146 sub alloc
147 {
148         my ($pkg, $call, $conn, $user) = @_;
149         my $self = {};
150
151         die "trying to create a duplicate channel for $call" if $channels{$call};
152         bless $self, $pkg;
153
154         $self->{call} = $call;
155         $self->{priv} = 0;
156         if (defined $conn && ref $conn) { # if this isn't defined then it must be a list
157                 $self->{conn} = $conn;
158                 $conn->set_on_eof(sub {$self->disconnect});
159         }
160         if (defined $user) {
161                 $self->{user} = $user;
162                 $self->{lang} = $user->lang;
163                 $user->new_group unless $user->group;
164                 $user->new_buddies unless $user->buddies;
165                 $self->{group} = $user->group;
166                 $self->{sort} = $user->sort;
167         }
168         $self->{startt} = $self->{t} = time;
169         $self->{state} = 0;
170         $self->{oldstate} = 0;
171         $self->{lang} = $main::lang if !$self->{lang};
172         $self->{func} = "";
173
174         # add in all the dxcc, itu, zone info
175         my @dxcc = Prefix::extract($call);
176         if (@dxcc > 0) {
177                 $self->{dxcc} = $dxcc[1]->dxcc;
178                 $self->{itu} = $dxcc[1]->itu;
179                 $self->{cq} = $dxcc[1]->cq;                                             
180         }
181         $self->{inqueue} = [];
182
183         $count++;
184         dbg("DXChannel $self->{call} created ($count)") if isdbg('chan');
185         return $channels{$call} = $self;
186 }
187
188 # count errors and disconnect if too many
189 # this has to be here because it can come from rcmd (DXProt) as
190 # well as DXCommandmode.
191 sub _error_out
192 {
193         my $self = shift;
194         my $e = shift;
195         if (++$self->{errors} > $maxerrors) {
196                 $self->send($self->msg('e26'));
197                 $self->disconnect;
198                 return ();
199         } else {
200                 return ($self->msg($e));
201         }
202 }
203
204 # rebless this channel as something else
205 sub rebless
206 {
207         my $self = shift;
208         my $class = shift;
209         my $new = bless $self, $class;
210         $new->{conn}->on_eof(sub {$new->disconnect});
211         return $channels{$self->{call}} = $new;
212 }
213
214 sub rec 
215 {
216         my ($self, $msg) = @_;
217         
218         # queue the message and the channel object for later processing
219         if (defined $msg) {
220                 push @{$self->{inqueue}}, $msg;
221         }
222 }
223
224 # obtain a channel object by callsign [$obj = DXChannel::get($call)]
225 sub get
226 {
227         my $call = shift;
228         return $channels{$call};
229 }
230
231 # obtain all the channel objects
232 sub get_all
233 {
234         return values(%channels);
235 }
236
237 #
238 # gimme all the ak1a nodes
239 #
240 sub get_all_nodes
241 {
242         my $ref;
243         my @out;
244         foreach $ref (values %channels) {
245                 push @out, $ref if $ref->is_node;
246         }
247         return @out;
248 }
249
250 # return a list of node calls
251 sub get_all_node_calls
252 {
253         my $ref;
254         my @out;
255         foreach $ref (values %channels) {
256                 push @out, $ref->{call} if $ref->is_node;
257         }
258         return @out;
259 }
260
261 # return a list of all users
262 sub get_all_users
263 {
264         my $ref;
265         my @out;
266         foreach $ref (values %channels) {
267                 push @out, $ref if $ref->is_user;
268         }
269         return @out;
270 }
271
272 # return a list of all user callsigns
273 sub get_all_user_calls
274 {
275         my $ref;
276         my @out;
277         foreach $ref (values %channels) {
278                 push @out, $ref->{call} if $ref->is_user;
279         }
280         return @out;
281 }
282
283 # obtain a channel object by searching for its connection reference
284 sub get_by_cnum
285 {
286         my ($pkg, $conn) = @_;
287         my $self;
288   
289         foreach $self (values(%channels)) {
290                 return $self if ($self->{conn} == $conn);
291         }
292         return undef;
293 }
294
295 # get rid of a channel object [$obj->del()]
296 sub del
297 {
298         my $self = shift;
299
300         $self->{group} = undef;         # belt and braces
301         delete $channels{$self->{call}};
302 }
303
304 # is it a bbs
305 sub is_bbs
306 {
307         my $self = shift;
308         return $self->{'sort'} eq 'B';
309 }
310
311 sub is_node
312 {
313         my $self = shift;
314         return $self->{'sort'} =~ /[ACRSXW]/;
315 }
316 # is it an ak1a node ?
317 sub is_ak1a
318 {
319         my $self = shift;
320         return $self->{'sort'} eq 'A';
321 }
322
323 # is it a user?
324 sub is_user
325 {
326         my $self = shift;
327         return $self->{'sort'} eq 'U';
328 }
329
330 # is it a clx node
331 sub is_clx
332 {
333         my $self = shift;
334         return $self->{'sort'} eq 'C';
335 }
336
337 # it is Aranea
338 sub is_aranea
339 {
340         my $self = shift;
341         return $self->{'sort'} eq 'W';
342 }
343
344 # is it a spider node
345 sub is_spider
346 {
347         my $self = shift;
348         return $self->{'sort'} eq 'S';
349 }
350
351 # is it a DXNet node
352 sub is_dxnet
353 {
354         my $self = shift;
355         return $self->{'sort'} eq 'X';
356 }
357
358 # is it a ar-cluster node
359 sub is_arcluster
360 {
361         my $self = shift;
362         return $self->{'sort'} eq 'R';
363 }
364
365 # for perl 5.004's benefit
366 sub sort
367 {
368         my $self = shift;
369         return @_ ? $self->{'sort'} = shift : $self->{'sort'} ;
370 }
371
372 # find out whether we are prepared to believe this callsign on this interface
373 sub is_believed
374 {
375         my $self = shift;
376         my $call = shift;
377         
378         return grep $call eq $_, $self->user->believe;
379 }
380
381 # handle out going messages, immediately without waiting for the select to drop
382 # this could, in theory, block
383 sub send_now
384 {
385         my $self = shift;
386         my $conn = $self->{conn};
387         return unless $conn;
388         my $sort = shift;
389         my $call = $self->{call};
390         
391         for (@_) {
392 #               chomp;
393         my @lines = split /\n/;
394                 for (@lines) {
395                         dbg("-> $sort $call $_") if $sort ne 'L' && isdbg('chan');
396                         $conn->send_now("$sort$call|$_");
397                         # debug log it, but not if it is a log message
398                 }
399         }
400         $self->{t} = time;
401 }
402
403 #
404 # send later with letter (more control)
405 #
406
407 sub send_later
408 {
409         my $self = shift;
410         my $conn = $self->{conn};
411         return unless $conn;
412         my $sort = shift;
413         my $call = $self->{call};
414         
415         for (@_) {
416 #               chomp;
417         my @lines = split /\n/;
418                 for (@lines) {
419                         dbg("-> $sort $call $_") if $sort ne 'L' && isdbg('chan');
420                         $conn->send_later("$sort$call|$_");
421                         # debug log it, but not if it is a log message
422                 }
423         }
424         $self->{t} = time;
425 }
426
427 #
428 # the normal output routine
429 #
430 sub send                                                # this is always later and always data
431 {
432         my $self = shift;
433         my $conn = $self->{conn};
434         return unless $conn;
435         my $call = $self->{call};
436
437         foreach my $l (@_) {
438                 for (ref $l ? @$l : $l) {
439                         my @lines = split /\n/;
440                         for (@lines) {
441                                 dbg("-> D $call $_") if isdbg('chan');
442                                 $conn->send_later("D$call|$_");
443                         }
444                 }
445         }
446         $self->{t} = $main::systime;
447 }
448
449 # send a file (always later)
450 sub send_file
451 {
452         my ($self, $fn) = @_;
453         my $call = $self->{call};
454         my $conn = $self->{conn};
455         my @buf;
456   
457         open(F, $fn) or die "can't open $fn for sending file ($!)";
458         @buf = <F>;
459         close(F);
460         $self->send(@buf);
461 }
462
463 # this will implement language independence (in time)
464 sub msg
465 {
466         my $self = shift;
467         return DXM::msg($self->{lang}, @_);
468 }
469
470 # stick a broadcast on the delayed queue (but only up to 20 items)
471 sub delay
472 {
473         my $self = shift;
474         my $s = shift;
475         
476         $self->{delayed} = [] unless $self->{delayed};
477         push @{$self->{delayed}}, $s;
478         if (@{$self->{delayed}} >= 20) {
479                 shift @{$self->{delayed}};   # lose oldest one
480         }
481 }
482
483 # change the state of the channel - lots of scope for debugging here :-)
484 sub state
485 {
486         my $self = shift;
487         if (@_) {
488                 $self->{oldstate} = $self->{state};
489                 $self->{state} = shift;
490                 $self->{func} = '' unless defined $self->{func};
491                 dbg("$self->{call} channel func $self->{func} state $self->{oldstate} -> $self->{state}\n") if isdbg('state');
492
493                 # if there is any queued up broadcasts then splurge them out here
494                 if ($self->{delayed} && ($self->{state} eq 'prompt' || $self->{state} eq 'talk')) {
495                         $self->send (@{$self->{delayed}});
496                         delete $self->{delayed};
497                 }
498         }
499         return $self->{state};
500 }
501
502 # disconnect this channel
503 sub disconnect
504 {
505         my $self = shift;
506         my $user = $self->{user};
507         
508         $user->close() if defined $user;
509         $self->{conn}->close_on_empty if $self->{conn};
510         $self->del();
511 }
512
513 #
514 # just close all the socket connections down without any fiddling about, cleaning, being
515 # nice to other processes and otherwise telling them what is going on.
516 #
517 # This is for the benefit of forked processes to prepare for starting new programs, they
518 # don't want or need all this baggage.
519 #
520
521 sub closeall
522 {
523         my $ref;
524         foreach $ref (values %channels) {
525                 $ref->{conn}->disconnect() if $ref->{conn};
526         }
527 }
528
529 #
530 # Tell all the users that we have come in or out (if they want to know)
531 #
532 sub tell_login
533 {
534         my ($self, $m, $call) = @_;
535         
536         $call ||= $self->{call};
537         
538         # send info to all logged in thingies
539         my @dxchan = get_all_users();
540         my $dxchan;
541         foreach $dxchan (@dxchan) {
542                 next if $dxchan == $self;
543                 next if $dxchan->{call} eq $main::mycall;
544                 $dxchan->send($dxchan->msg($m, $call)) if $dxchan->{logininfo};
545         }
546 }
547
548 #
549 # Tell all the users if a buddy is logged or out
550 #
551 sub tell_buddies
552 {
553         my ($self, $m, $call, $node) = @_;
554         
555         $call ||= $self->{call};
556         $call =~ s/-\d+$//;
557         $m .= 'n' if $node;
558         
559         # send info to all logged in thingies
560         my @dxchan = get_all_users();
561         my $dxchan;
562         foreach $dxchan (@dxchan) {
563                 next if $dxchan == $self;
564                 next if $dxchan->{call} eq $main::mycall;
565                 $dxchan->send($dxchan->msg($m, $call, $node)) if grep $_ eq $call, @{$dxchan->{user}->{buddies}} ;
566         }
567 }
568
569 # various access routines
570
571 #
572 # return a list of valid elements 
573
574
575 sub fields
576 {
577         return keys(%valid);
578 }
579
580 #
581 # return a prompt for a field
582 #
583
584 sub field_prompt
585
586         my ($self, $ele) = @_;
587         return $valid{$ele};
588 }
589
590 # take a standard input message and decode it into its standard parts
591 sub decode_input
592 {
593         my $dxchan = shift;
594         my $data = shift;
595         my ($sort, $call, $line) = $data =~ /^([A-Z])([A-Z0-9\-]{3,9})\|(.*)$/;
596
597         my $chcall = (ref $dxchan) ? $dxchan->call : "UN.KNOWN";
598         
599         # the above regexp must work
600         unless (defined $sort && defined $call && defined $line) {
601 #               $data =~ s/([\x00-\x1f\x7f-\xff])/uc sprintf("%%%02x",ord($1))/eg;
602                 dbg("DUFF Line on $chcall: $data");
603                 return ();
604         }
605
606         if(ref($dxchan) && $call ne $chcall) {
607                 dbg("DUFF Line come in for $call on wrong channel $chcall");
608                 return();
609         }
610         
611         return ($sort, $call, $line);
612 }
613
614 # broadcast a message to all clusters taking into account isolation
615 # [except those mentioned after buffer]
616 sub broadcast_nodes
617 {
618         my $s = shift;                          # the line to be rebroadcast
619         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
620         my @dxchan = get_all_nodes();
621         my $dxchan;
622         
623         # send it if it isn't the except list and isn't isolated and still has a hop count
624         foreach $dxchan (@dxchan) {
625                 next if grep $dxchan == $_, @except;
626                 next if $dxchan == $main::me;
627                 
628                 my $routeit = $dxchan->can('adjust_hops') ? $dxchan->adjust_hops($s) : $s;      # adjust its hop count by node name
629
630                 $dxchan->send($routeit) unless $dxchan->{isolate} || !$routeit;
631         }
632 }
633
634 # broadcast a message to all clusters ignoring isolation
635 # [except those mentioned after buffer]
636 sub broadcast_all_nodes
637 {
638         my $s = shift;                          # the line to be rebroadcast
639         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
640         my @dxchan = get_all_nodes();
641         my $dxchan;
642         
643         # send it if it isn't the except list and isn't isolated and still has a hop count
644         foreach $dxchan (@dxchan) {
645                 next if grep $dxchan == $_, @except;
646                 next if $dxchan == $main::me;
647
648                 my $routeit = $dxchan->can('adjust_hops') ? $dxchan->adjust_hops($s) : $s;      # adjust its hop count by node name
649                 $dxchan->send($routeit);
650         }
651 }
652
653 # broadcast to all users
654 # storing the spot or whatever until it is in a state to receive it
655 sub broadcast_users
656 {
657         my $s = shift;                          # the line to be rebroadcast
658         my $sort = shift;           # the type of transmission
659         my $fref = shift;           # a reference to an object to filter on
660         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
661         my @dxchan = get_all_users();
662         my $dxchan;
663         my @out;
664         
665         foreach $dxchan (@dxchan) {
666                 next if grep $dxchan == $_, @except;
667                 push @out, $dxchan;
668         }
669         broadcast_list($s, $sort, $fref, @out);
670 }
671
672
673 # broadcast to a list of users
674 sub broadcast_list
675 {
676         my $s = shift;
677         my $sort = shift;
678         my $fref = shift;
679         my $dxchan;
680         
681         foreach $dxchan (@_) {
682                 my $filter = 1;
683                 next if $dxchan == $main::me;
684                 
685                 if ($sort eq 'dx') {
686                     next unless $dxchan->{dx};
687                         ($filter) = $dxchan->{spotsfilter}->it(@{$fref}) if ref $fref;
688                         next unless $filter;
689                 }
690                 next if $sort eq 'ann' && !$dxchan->{ann} && $s !~ /^To\s+LOCAL\s+de\s+(?:$main::myalias|$main::mycall)/i;
691                 next if $sort eq 'wwv' && !$dxchan->{wwv};
692                 next if $sort eq 'wcy' && !$dxchan->{wcy};
693                 next if $sort eq 'wx' && !$dxchan->{wx};
694
695                 $s =~ s/\a//og unless $dxchan->{beep};
696
697                 if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'talk') {
698                         $dxchan->send($s);      
699                 } else {
700                         $dxchan->delay($s);
701                 }
702         }
703 }
704
705 sub process
706 {
707         foreach my $dxchan (get_all()) {
708
709                 while (my $data = shift @{$dxchan->{inqueue}}) {
710                         my ($sort, $call, $line) = $dxchan->decode_input($data);
711                         next unless defined $sort;
712
713                         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
714                         dbg("<- $sort $call $line") if $sort ne 'D' && isdbg('chan');
715                         if ($dxchan->{disconnecting}) {
716                                 dbg('In disconnection, ignored');
717                                 next;
718                         }
719
720                         # handle A records
721                         my $user = $dxchan->user;
722                         if ($sort eq 'A' || $sort eq 'O') {
723                                 $dxchan->start($line, $sort);
724                         } elsif ($sort eq 'I') {
725                                 die "\$user not defined for $call" if !defined $user;
726                         
727                                 # normal input
728                                 $dxchan->normal($line);
729                         } elsif ($sort eq 'Z') {
730                                 $dxchan->disconnect;
731                         } elsif ($sort eq 'D') {
732                                 ;                               # ignored (an echo)
733                         } elsif ($sort eq 'G') {
734                                 $dxchan->enhanced($line);
735                         } else {
736                                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
737                         }
738                 }
739         }
740 }
741
742 sub handle_xml
743 {
744         my $self = shift;
745         my $r = 0;
746         
747         if (DXXml::available()) {
748                 $r = $self->{handle_xml} || 0;
749         } else {
750                 delete $self->{handle_xml} if exists $self->{handle_xml};
751         }
752         return $r;
753 }
754
755 #no strict;
756 sub AUTOLOAD
757 {
758         no strict;
759         my $name = $AUTOLOAD;
760         return if $name =~ /::DESTROY$/;
761         $name =~ s/^.*:://o;
762   
763         confess "Non-existant field '$AUTOLOAD'" if !$valid{$name};
764
765         # this clever line of code creates a subroutine which takes over from autoload
766         # from OO Perl - Conway
767         *$AUTOLOAD = sub {@_ > 1 ? $_[0]->{$name} = $_[1] : $_[0]->{$name}};
768         goto &$AUTOLOAD;
769 }
770
771
772 1;
773 __END__;