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