1. did some work on making talk more intelligent and fixed a>b problem.
[spider.git] / perl / Filter.pm
1 #
2 # The User/Sysop Filter module
3 #
4 # The way this works is that the filter routine is actually
5 # a predefined function that returns 0 if it is OK and 1 if it
6 # is not when presented with a list of things.
7 #
8 # This set of routines provide a means of maintaining the filter
9 # scripts which are compiled in when an entity connects.
10 #
11 # Copyright (c) 1999 Dirk Koopman G1TLH
12 #
13 # $Id$
14 #
15 # The NEW INSTRUCTIONS
16 #
17 # use the commands accept/spot|ann|wwv|wcy and reject/spot|ann|wwv|wcy
18 # also show/filter spot|ann|wwv|wcy
19 #
20 # The filters live in a directory tree of their own in $main::root/filter
21 #
22 # Each type of filter (e.g. spot, wwv) live in a tree of their own so you
23 # can have different filters for different things for the same callsign.
24 #
25
26
27 package Filter;
28
29 use DXVars;
30 use DXUtil;
31 use DXDebug;
32 use Data::Dumper;
33 use Prefix;
34
35 use strict;
36
37 use vars qw($VERSION $BRANCH);
38 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
39 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/ ) || 0;
40 $main::build += $VERSION;
41 $main::branch += $BRANCH;
42
43 use vars qw ($filterbasefn $in);
44
45 $filterbasefn = "$main::root/filter";
46 $in = undef;
47
48 # initial filter system
49 sub init
50 {
51
52 }
53
54 sub new
55 {
56         my ($class, $sort, $call, $flag) = @_;
57         $flag = ($flag) ? "in_" : "";
58         return bless {sort => $sort, name => "$flag$call.pl" }, $class;
59 }
60
61 # standard filename generator
62 sub getfn
63 {
64         my ($sort, $call, $flag) = @_;
65
66     # first uppercase
67         $flag = ($flag) ? "in_" : "";
68         $call = uc $call;
69         my $fn = "$filterbasefn/$sort/$flag$call.pl";
70
71         # otherwise lowercase
72         unless (-e $fn) {
73                 $call = lc $call;
74                 $fn = "$filterbasefn/$sort/$flag$call.pl";
75         }
76         $fn = undef unless -e $fn;
77         return $fn;
78 }
79
80 # this reads in a filter statement and returns it as a list
81
82 # The filter is stored in straight perl so that it can be parsed and read
83 # in with a 'do' statement. The 'do' statement reads the filter into
84 # @in which is a list of references
85 #
86 sub compile
87 {
88         my $self = shift;
89         my $fname = shift;
90         my $ar = shift;
91         my $ref = $self->{$fname};
92         my $rr;
93         
94         if ($ref->{$ar} && exists $ref->{$ar}->{asc}) {
95                 $ref->{$ar}->{code} = eval "sub { my \$r=shift; return $ref->{$ar}->{asc}; }" ;
96                 if ($@) {
97                         my $sort = $ref->{sort};
98                         my $name = $ref->{name};
99                         dbg("Error compiling $ar $sort $name: $@");
100                         Log('err', "Error compiling $ar $sort $name: $@");
101                 }
102                 $rr = $@;
103         }
104         return $rr;
105 }
106
107 sub read_in
108 {
109         my ($sort, $call, $flag) = @_;
110         my $fn;
111         
112         # load it
113         if ($fn = getfn($sort, $call, $flag)) {
114                 $in = undef; 
115                 my $s = readfilestr($fn);
116                 my $newin = eval $s;
117                 dbg($@) if $@;
118                 if ($in) {
119                         $newin = new('Filter::Old', $sort, $call, $flag);
120                         $newin->{filter} = $in;
121                 } else {
122                         my $filter;
123                         my $key;
124                         foreach $key ($newin->getfilkeys) {
125                                 $newin->compile($key, 'reject');
126                                 $newin->compile($key, 'accept');
127                         }
128                 }
129                 return $newin;
130         }
131         return undef;
132 }
133
134 sub getfilters
135 {
136         my $self = shift;
137         my @out;
138         my $key;
139         foreach $key (grep {/^filter/ } keys %$self) {
140                 push @out, $self->{$key};
141         }
142         return @out;
143 }
144
145 sub getfilkeys
146 {
147         my $self = shift;
148         return grep {/^filter/ } keys %$self;
149 }
150
151 #
152 # This routine accepts a composite filter with a reject rule and then an accept rule.
153 #
154 # The filter returns 0 if an entry is matched by any reject rule and also if any
155 # accept rule fails otherwise it returns 1
156 #
157 # Either set of rules may be missing meaning an implicit 'opposite' ie if it
158 # a reject then ok else if an accept then not ok.
159 #
160 # you can set a default with either an accept/xxxx all or reject/xxxx all
161 #
162 # Unlike the old system, this is kept as a hash of hashes so that you can
163 # easily change them by program.
164 #
165 # You can have 10 filter lines (0->9), they are tried in order until 
166 # one matches
167 #
168 # There is a parser that takes a Filter::Cmd object which describes all the possible
169 # things you can filter on and then converts that to a bit of perl which is compiled
170 # and stored as a function.
171 #
172 # The result of this is that in theory you can put together an arbritrarily complex 
173 # expression involving the things you can filter on including 'and' 'or' 'not' and 
174 # 'brackets'.
175 #
176 # eg:-
177 #
178 # accept/spots hf and by_zone 14,15,16 and not by pa,on
179 #  
180 # accept/spots freq 0/30000 and by_zone 4,5
181
182 # accept/spots 2 vhf and (by_zone 14,15,16 or call_dxcc 61) 
183 #
184 # no filter no implies filter 1
185 #
186 # The field nos are the same as for the 'Old' filters
187 #
188
189
190 sub it
191 {
192         my $self = shift;
193         
194         my $filter;
195         my @keys = sort $self->getfilkeys;
196         my $key;
197         my $type = 'Dunno';
198         my $asc = '?';
199
200         my $r = @keys > 0 ? 0 : 1;
201         foreach $key (@keys) {
202                 $filter = $self->{$key};
203                 if ($filter->{reject} && exists $filter->{reject}->{code}) {
204                         $type = 'reject';
205                         $asc = $filter->{reject}->{user};
206                         if (&{$filter->{reject}->{code}}(\@_)) {
207                                 $r = 0;
208                                 last;
209                         } else {
210                                 $r = 1;
211                         }               
212                 }
213                 if ($filter->{accept} && exists $filter->{accept}->{code}) {
214                         $type = 'accept';
215                         $asc = $filter->{accept}->{user};
216                         if (&{$filter->{accept}->{code}}(\@_)) {
217                                 $r = 1;
218                                 last;
219                         } else {
220                                 $r = 0;
221                         }                       
222                 } 
223         }
224
225         # hops are done differently (simply) 
226         my $hops = $self->{hops} if exists $self->{hops};
227
228         if (isdbg('filter')) {
229                 my $args = join '\',\'', map {defined $_ ? $_ : 'undef'} @_;
230                 my $true = $r ? "OK " : "REJ";
231                 my $sort = $self->{sort};
232                 my $dir = $self->{name} =~ /^in_/i ? "IN " : "OUT";
233                 
234                 my $h = $hops || '';
235                 dbg("$true $dir: $type/$sort with $asc on '$args' $h") if isdbg('filter');
236         }
237         return ($r, $hops);
238 }
239
240 # this writes out the filter in a form suitable to be read in by 'read_in'
241 # It expects a list of references to filter lines
242 sub write
243 {
244         my $self = shift;
245         my $sort = $self->{sort};
246         my $name = $self->{name};
247         my $dir = "$filterbasefn/$sort";
248         my $fn = "$dir/$name";
249
250         mkdir $dir, 0775 unless -e $dir; 
251     rename $fn, "$fn.o" if -e $fn;
252         my $fh = new IO::File ">$fn";
253         if ($fh) {
254                 my $dd = new Data::Dumper([ $self ]);
255                 $dd->Indent(1);
256                 $dd->Terse(1);
257                 $dd->Quotekeys($] < 5.005 ? 1 : 0);
258                 $fh->print($dd->Dumpxs);
259                 $fh->close;
260         } else {
261                 rename "$fn.o", $fn if -e "$fn.o";
262                 return "$fn $!";
263         }
264         return undef;
265 }
266
267 sub print
268 {
269         my $self = shift;
270         my $name = shift || $self->{name};
271         my $sort = shift || $self->{sort};
272         my $flag = shift || "";
273         my @out;
274         $name =~ s/.pl$//;
275         
276         push @out, join(' ',  $name , ':', $sort, $flag);
277         my $filter;
278         my $key;
279         foreach $key (sort $self->getfilkeys) {
280                 my $filter = $self->{$key};
281                 if (exists $filter->{reject} && exists $filter->{reject}->{user}) {
282                         push @out, ' ' . join(' ', $key, 'reject', $filter->{reject}->{user});
283                 }
284                 if (exists $filter->{accept} && exists $filter->{accept}->{user}) {
285                         push @out, ' ' . join(' ', $key, 'accept', $filter->{accept}->{user});
286                 } 
287         }
288         return @out;
289 }
290
291 sub install
292 {
293         my $self = shift;
294         my $remove = shift;
295         my $name = uc $self->{name};
296         my $sort = $self->{sort};
297         my $in = "";
298         $in = "in" if $name =~ s/^IN_//;
299         $name =~ s/.PL$//;
300                 
301         my $dxchan;
302         my @dxchan;
303         if ($name eq 'NODE_DEFAULT') {
304                 @dxchan = DXChannel::get_all_nodes();
305         } elsif ($name eq 'USER_DEFAULT') {
306                 @dxchan = DXChannel::get_all_users();
307         } else {
308                 $dxchan = DXChannel->get($name);
309                 push @dxchan, $dxchan if $dxchan;
310         }
311         foreach $dxchan (@dxchan) {
312                 my $n = "$in$sort" . "filter";
313                 my $i = $in ? 'IN_' : '';
314                 my $ref = $dxchan->$n();
315                 if (!$ref || ($ref && uc $ref->{name} eq "$i$name.PL")) {
316                         $dxchan->$n($remove ? undef : $self);
317                 }
318         }
319 }
320
321 sub delete
322 {
323         my ($sort, $call, $flag, $fno) = @_;
324         
325         # look for the file
326         my $fn = getfn($sort, $call, $flag);
327         my $filter = read_in($sort, $call, $flag);
328         if ($filter) {
329                 if ($fno eq 'all') {
330                         my $key;
331                         foreach $key ($filter->getfilkeys) {
332                                 delete $filter->{$key};
333                         }
334                 } elsif (exists $filter->{"filter$fno"}) {
335                         delete $filter->{"filter$fno"}; 
336                 }
337                 
338                 # get rid 
339                 if ($filter->{hops} || $filter->getfilkeys) {
340                         $filter->install;
341                         $filter->write;
342                 } else {
343                         $filter->install(1);
344                         unlink $fn;
345                 }
346         }
347 }
348
349 package Filter::Cmd;
350
351 use strict;
352 use DXVars;
353 use DXUtil;
354 use DXDebug;
355 use vars qw(@ISA);
356 @ISA = qw(Filter);
357
358 # the general purpose command processor
359 # this is called as a subroutine not as a method
360 sub parse
361 {
362         my ($self, $dxchan, $sort, $line) = @_;
363         my $ntoken = 0;
364         my $fno = 1;
365         my $filter;
366         my ($flag, $call);
367         my $s;
368         my $user;
369         
370         # check the line for non legal characters
371         return ('ill', $dxchan->msg('e19')) if $line =~ /[^\s\w,_\-\*\/\(\)]/;
372         
373         # add some spaces for ease of parsing
374         $line =~ s/([\(\)])/ $1 /g;
375         $line = lc $line;
376         
377         my @f = split /\s+/, $line;
378         my $conj = ' && ';
379         my $not = "";
380         while (@f) {
381                 if ($ntoken == 0) {
382                         
383                         if (@f && $dxchan->priv >= 8 && ((is_callsign(uc $f[0]) && DXUser->get(uc $f[0])) || $f[0] =~ /(?:node|user)_default/)) {
384                                 $call = shift @f;
385                                 if ($f[0] eq 'input') {
386                                         shift @f;
387                                         $flag++;
388                                 }
389                         } else {
390                                 $call = $dxchan->call;
391                         }
392
393                         if (@f && $f[0] =~ /^\d$/) {
394                                 $fno = shift @f;
395                         }
396
397                         $filter = Filter::read_in($sort, $call, $flag);
398                         $filter = Filter->new($sort, $call, $flag) if !$filter || $filter->isa('Filter::Old');
399                         
400                         $ntoken++;
401                         next;
402                 }
403
404                 # do the rest of the filter tokens
405                 if (@f) {
406                         my $tok = shift @f;
407                         if ($tok eq '(') {
408                                 if ($s) {
409                                         $s .= $conj;
410                                         $user .= $conj;
411                                         $conj = "";
412                                 }
413                                 if ($not) {
414                                         $s .= $not;
415                                         $user .= $not;
416                                         $not = "";
417                                 }
418                                 $s .= $tok;
419                                 $user .= $tok;
420                                 next;
421                         } elsif ($tok eq ')') {
422                                 $conj = ' && ';
423                                 $not ="";
424                                 $s .= $tok;
425                                 $user .= $tok;
426                                 next;
427                         } elsif ($tok eq 'all') {
428                                 $s .= '1';
429                                 $user .= $tok;
430                                 last;
431                         } elsif ($tok eq 'or') {
432                                 $conj = ' || ' if $conj ne ' || ';
433                                 next;
434                         } elsif ($tok eq 'and') {
435                                 $conj = ' && ' if $conj ne ' && ';
436                                 next;
437                         } elsif ($tok eq 'not' || $tok eq '!') {
438                                 $not = '!';
439                                 next;
440                         }
441                         if (@f) {
442                                 my $val = shift @f;
443                                 my @val = split /,/, $val;
444
445                                 if ($s) {
446                                         $s .= $conj ;
447                                         $s .= $not;
448                                         $user .= $conj;
449                                         $user .= $not;
450                                         $conj = ' && ';
451                                         $not = "";
452                                 }
453                                 $user .= "$tok $val";
454                                 
455                                 my $fref;
456                                 my $found;
457                                 foreach $fref (@$self) {
458                                         
459                                         if ($fref->[0] eq $tok) {
460                                                 if ($fref->[4]) {
461                                                         my @nval;
462                                                         for (@val) {
463                                                                 push @nval, split(',', &{$fref->[4]}($dxchan, $_));
464                                                         }
465                                                         @val = @nval;
466                                                 }
467                                                 if ($fref->[1] eq 'a') {
468                                                         my @t;
469                                                         for (@val) {
470                                                                 s/\*//g;
471                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
472                                                         }
473                                                         $s .= "(" . join(' || ', @t) . ")";
474                                                 } elsif ($fref->[1] eq 'c') {
475                                                         my @t;
476                                                         for (@val) {
477                                                                 s/\*//g;
478                                                                 push @t, "\$r->[$fref->[2]]=~/^\U$_/";
479                                                         }
480                                                         $s .= "(" . join(' || ', @t) . ")";
481                                                 } elsif ($fref->[1] eq 'n') {
482                                                         my @t;
483                                                         for (@val) {
484                                                                 return ('num', $dxchan->msg('e21', $_)) unless /^\d+$/;
485                                                                 push @t, "\$r->[$fref->[2]]==$_";
486                                                         }
487                                                         $s .= "(" . join(' || ', @t) . ")";
488                                                 } elsif ($fref->[1] =~ /^n[ciz]$/ ) {    # for DXCC, ITU, CQ Zone    
489                                                         my @n;
490                                                         my $cmd = $fref->[1];
491                                                         foreach my $v (@val) {
492                                                                 if ($v =~ /^\d+$/) {    
493                                                                         push @n, $v unless grep $_ eq $v, @n;
494                                                                 } else {
495                                                                         my @pre = Prefix::extract($v);
496                                                                         return ('numpre', $dxchan->msg('e27', $_)) unless @pre;
497                                                                         shift @pre;
498                                                                         foreach my $p (@pre) {
499                                                                                 my $n = $p->dxcc if $cmd eq 'nc' ;
500                                                                                 $n = $p->itu if $cmd eq 'ni' ;
501                                                                                 $n = $p->cq if $cmd eq 'nz' ;
502                                                                                 push @n, $n unless grep $_ eq $n, @n;
503                                                                         }
504                                                                 }
505                                                         }
506                                                         $s .= "(" . join(' || ', map {"\$r->[$fref->[2]]==$_"} @n) . ")";
507                                                 } elsif ($fref->[1] eq 'r') {
508                                                         my @t;
509                                                         for (@val) {
510                                                                 return ('range', $dxchan->msg('e23', $_)) unless /^(\d+)\/(\d+)$/;
511                                                                 push @t, "(\$r->[$fref->[2]]>=$1 && \$r->[$fref->[2]]<=$2)";
512                                                         }
513                                                         $s .= "(" . join(' || ', @t) . ")";
514                                                 } elsif ($fref->[1] eq 't') {
515                                                         my @t;
516                                                         for (@val) {
517                                                                 s/\*//g;
518                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
519                                                         }
520                                                         $s .= "(" . join(' || ', @t) . ")";
521                                                 } else {
522                                                         confess("invalid letter $fref->[1]");
523                                                 }
524                                                 ++$found;
525                                                 last;
526                                         }
527                                 }
528                                 return ('unknown', $dxchan->msg('e20', $tok)) unless $found;
529                         } else {
530                                 return ('no', $dxchan->msg('filter2', $tok));
531                         }
532                 }
533                 
534         }
535
536         # tidy up the user string
537         $user =~ s/\&\&/ and /g;
538         $user =~ s/\|\|/ or /g;
539         $user =~ s/\!/ not /g;
540         $user =~ s/\s+/ /g;
541         
542         return (0, $filter, $fno, $user, "$s");
543 }
544
545 # a filter accept/reject command
546 sub cmd
547 {
548         my ($self, $dxchan, $sort, $type, $line) = @_;
549         
550         return $dxchan->msg('filter5') unless $line;
551
552         my ($r, $filter, $fno, $user, $s) = $self->parse($dxchan, $sort, $line);
553         my $u = DXUser->get_current($user);
554         return (1, $dxchan->msg('isow', $user)) if $u && $u->isolate;
555         return (1, $filter) if $r;
556
557         my $fn = "filter$fno";
558
559         $filter->{$fn} = {} unless exists $filter->{$fn};
560         $filter->{$fn}->{$type} = {} unless exists $filter->{$fn}->{$type};
561
562         $filter->{$fn}->{$type}->{user} = $user;
563         $filter->{$fn}->{$type}->{asc} = $s;
564         $r = $filter->compile($fn, $type);
565         return (1,$r) if $r;
566         
567         $r = $filter->write;
568         return (1,$r) if $r;
569         
570         $filter->install;
571
572     return (0, $filter, $fno);
573 }
574
575 package Filter::Old;
576
577 use strict;
578 use DXVars;
579 use DXUtil;
580 use DXDebug;
581 use vars qw(@ISA);
582 @ISA = qw(Filter);
583
584 # the OLD instructions!
585 #
586 # Each filter file has the same structure:-
587 #
588 # <some comment>
589 # @in = (
590 #      [ action, fieldno, fieldsort, comparison, action data ],
591 #      ...
592 # );
593 #
594 # The action is usually 1 or 0 but could be any numeric value
595 #
596 # The fieldno is the field no in the list of fields that is presented
597 # to 'Filter::it' 
598 #
599 # The fieldsort is the type of field that we are dealing with which 
600 # currently can be 'a', 'n', 'r' or 'd'. 'a' is alphanumeric, 'n' is 
601 # numeric, 'r' is ranges of pairs of numeric values and 'd' is default.
602 #
603 # Filter::it basically goes thru the list of comparisons from top to
604 # bottom and when one matches it will return the action and the action data as a list. 
605 # The fields
606 # are the element nos of the list that is presented to Filter::it. Element
607 # 0 is the first field of the list.
608 #
609
610 #
611 # takes the reference to the filter (the first argument) and applies
612 # it to the subsequent arguments and returns the action specified.
613 #
614 sub it
615 {
616         my $self = shift;
617         my $filter = $self->{filter};            # this is now a bless ref of course but so what
618         
619         my ($action, $field, $fieldsort, $comp, $actiondata);
620         my $ref;
621
622         # default action is 1
623         $action = 1;
624         $actiondata = "";
625         return ($action, $actiondata) if !$filter;
626
627         for $ref (@{$filter}) {
628                 ($action, $field, $fieldsort, $comp, $actiondata) = @{$ref};
629                 if ($fieldsort eq 'n') {
630                         my $val = $_[$field];
631                         return ($action, $actiondata)  if grep $_ == $val, @{$comp};
632                 } elsif ($fieldsort eq 'r') {
633                         my $val = $_[$field];
634                         my $i;
635                         my @range = @{$comp};
636                         for ($i = 0; $i < @range; $i += 2) {
637                                 return ($action, $actiondata)  if $val >= $range[$i] && $val <= $range[$i+1];
638                         }
639                 } elsif ($fieldsort eq 'a') {
640                         return ($action, $actiondata)  if $_[$field] =~ m{$comp};
641                 } else {
642                         return ($action, $actiondata);      # the default action
643                 }
644         }
645 }
646
647 sub print
648 {
649         my $self = shift;
650         my $call = shift;
651         my $sort = shift;
652         my $flag = shift || "";
653         return "$call: Old Style Filter $flag $sort";
654 }
655
656 1;
657 __END__