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