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