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