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