fixes
[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 $filter;
188         my @keys = sort $self->getfilkeys;
189         my $key;
190         my $type = 'Dunno';
191         my $asc = '?';
192         
193         my $r = @keys > 0 ? 0 : 1;
194         foreach $key (@keys) {
195                 $filter = $self->{$key};
196                 if ($filter->{reject} && exists $filter->{reject}->{code}) {
197                         $type = 'reject';
198                         $asc = $filter->{reject}->{user};
199                         if (&{$filter->{reject}->{code}}(\@_)) {
200                                 $r = 0;
201                                 last;
202                         } else {
203                                 $r = 1;
204                         }               
205                 }
206                 if ($filter->{accept} && exists $filter->{accept}->{code}) {
207                         $type = 'accept';
208                         $asc = $filter->{accept}->{user};
209                         if (&{$filter->{accept}->{code}}(\@_)) {
210                                 $r = 1;
211                                 last;
212                         } else {
213                                 $r = 0;
214                         }                       
215                 } 
216         }
217
218         # hops are done differently (simply) 
219         my $hops = $self->{hops} if exists $self->{hops};
220
221         if (isdbg('filter')) {
222                 my $args = join '\',\'', @_;
223                 my $true = $r ? "OK" : "REJ";
224                 my $sort = $self->{sort};
225                 $hops ||= "none";
226                 dbg('filter', "Filter: $type/$sort with $asc on '$args': $true hops: $hops");
227         }
228         return ($r, $hops);
229 }
230
231 # this writes out the filter in a form suitable to be read in by 'read_in'
232 # It expects a list of references to filter lines
233 sub write
234 {
235         my $self = shift;
236         my $sort = $self->{sort};
237         my $name = $self->{name};
238         my $dir = "$filterbasefn/$sort";
239         my $fn = "$dir/$name";
240
241         mkdir $dir, 0775 unless -e $dir; 
242     rename $fn, "$fn.o" if -e $fn;
243         my $fh = new IO::File ">$fn";
244         if ($fh) {
245                 my $dd = new Data::Dumper([ $self ]);
246                 $dd->Indent(1);
247                 $dd->Terse(1);
248                 $dd->Quotekeys($] < 5.005 ? 1 : 0);
249                 $fh->print($dd->Dumpxs);
250                 $fh->close;
251         } else {
252                 rename "$fn.o", $fn if -e "$fn.o";
253                 return "$fn $!";
254         }
255         return undef;
256 }
257
258 sub print
259 {
260         my $self = shift;
261         my $name = shift || $self->{name};
262         my $sort = shift || $self->{sort};
263         my $flag = shift || "";
264         my @out;
265         $name =~ s/.pl$//;
266         
267         push @out, join(' ',  $name , ':', $sort, $flag);
268         my $filter;
269         my $key;
270         foreach $key (sort $self->getfilkeys) {
271                 my $filter = $self->{$key};
272                 if (exists $filter->{reject} && exists $filter->{reject}->{user}) {
273                         push @out, ' ' . join(' ', $key, 'reject', $filter->{reject}->{user});
274                 }
275                 if (exists $filter->{accept} && exists $filter->{accept}->{user}) {
276                         push @out, ' ' . join(' ', $key, 'accept', $filter->{accept}->{user});
277                 } 
278         }
279         return @out;
280 }
281
282 sub install
283 {
284         my $self = shift;
285         my $remove = shift;
286         my $name = uc $self->{name};
287         my $sort = $self->{sort};
288         my $in = "in" if $name =~ s/^IN_//;
289         $name =~ s/.PL$//;
290                 
291         my $dxchan = DXChannel->get($name);
292         if ($dxchan) {
293                 my $n = "$in$sort" . "filter";
294                 $dxchan->$n($remove ? undef : $self);
295         }
296 }
297
298 sub delete
299 {
300         my ($sort, $call, $flag, $fno) = @_;
301         
302         # look for the file
303         my $fn = getfn($sort, $call, $flag);
304         my $filter = read_in($sort, $call, $flag);
305         if ($filter) {
306                 if ($fno eq 'all') {
307                         my $key;
308                         foreach $key ($filter->getfilkeys) {
309                                 delete $filter->{$key};
310                         }
311                 } elsif (exists $filter->{"filter$fno"}) {
312                         delete $filter->{"filter$fno"}; 
313                 }
314                 
315                 # get rid 
316                 if ($filter->{hops} || $filter->getfilkeys) {
317                         $filter->install;
318                         $filter->write;
319                 } else {
320                         $filter->install(1);
321                         unlink $fn;
322                 }
323         }
324 }
325
326 package Filter::Cmd;
327
328 use strict;
329 use DXVars;
330 use DXUtil;
331 use DXDebug;
332 use vars qw(@ISA);
333 @ISA = qw(Filter);
334
335 # the general purpose command processor
336 # this is called as a subroutine not as a method
337 sub parse
338 {
339         my ($self, $dxchan, $sort, $line) = @_;
340         my $ntoken = 0;
341         my $fno = 1;
342         my $filter;
343         my ($flag, $call);
344         my $s;
345         my $user;
346         
347         # check the line for non legal characters
348         return ('ill', $dxchan->msg('e19')) if $line =~ /[^\s\w,_\-\*\/\(\)]/;
349         
350         # add some spaces for ease of parsing
351         $line =~ s/([\(\)])/ $1 /g;
352         $line = lc $line;
353         
354         my @f = split /\s+/, $line;
355         my $conj = ' && ';
356         my $not = "";
357         while (@f) {
358                 if ($ntoken == 0) {
359                         
360                         if (@f && $dxchan->priv >= 8 && ((is_callsign(uc $f[0]) && DXUser->get(uc $f[0])) || $f[0] =~ /(?:node|user)_default/)) {
361                                 $call = shift @f;
362                                 if ($f[0] eq 'input') {
363                                         shift @f;
364                                         $flag++;
365                                 }
366                         } else {
367                                 $call = $dxchan->call;
368                         }
369
370                         if (@f && $f[0] =~ /^\d$/) {
371                                 $fno = shift @f;
372                         }
373
374                         $filter = Filter::read_in($sort, $call, $flag);
375                         $filter = Filter->new($sort, $call, $flag) if !$filter || $filter->isa('Filter::Old');
376                         
377                         $ntoken++;
378                         next;
379                 }
380
381                 # do the rest of the filter tokens
382                 if (@f) {
383                         my $tok = shift @f;
384                         if ($tok eq '(') {
385                                 if ($s) {
386                                         $s .= $conj;
387                                         $user .= $conj;
388                                         $conj = "";
389                                 }
390                                 if ($not) {
391                                         $s .= $not;
392                                         $user .= $not;
393                                         $not = "";
394                                 }
395                                 $s .= $tok;
396                                 $user .= $tok;
397                                 next;
398                         } elsif ($tok eq ')') {
399                                 $conj = ' && ';
400                                 $not ="";
401                                 $s .= $tok;
402                                 $user .= $tok;
403                                 next;
404                         } elsif ($tok eq 'all') {
405                                 $s .= '1';
406                                 $user .= $tok;
407                                 last;
408                         } elsif ($tok eq 'or') {
409                                 $conj = ' || ' if $conj ne ' || ';
410                                 next;
411                         } elsif ($tok eq 'and') {
412                                 $conj = ' && ' if $conj ne ' && ';
413                                 next;
414                         } elsif ($tok eq 'not' || $tok eq '!') {
415                                 $not = '!';
416                                 next;
417                         }
418                         if (@f) {
419                                 my $val = shift @f;
420                                 my @val = split /,/, $val;
421
422                                 if ($s) {
423                                         $s .= $conj ;
424                                         $s .= $not;
425                                         $user .= $conj;
426                                         $user .= $not;
427                                         $conj = ' && ';
428                                         $not = "";
429                                 }
430                                 $user .= "$tok $val";
431                                 
432                                 my $fref;
433                                 my $found;
434                                 foreach $fref (@$self) {
435                                         
436                                         if ($fref->[0] eq $tok) {
437                                                 if ($fref->[4]) {
438                                                         my @nval;
439                                                         for (@val) {
440                                                                 push @nval, split(',', &{$fref->[4]}($dxchan, $_));
441                                                         }
442                                                         @val = @nval;
443                                                 }
444                                                 if ($fref->[1] eq 'a') {
445                                                         my @t;
446                                                         for (@val) {
447                                                                 s/\*//g;
448                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
449                                                         }
450                                                         $s .= "(" . join(' || ', @t) . ")";
451                                                 } elsif ($fref->[1] eq 'c') {
452                                                         my @t;
453                                                         for (@val) {
454                                                                 s/\*//g;
455                                                                 push @t, "\$r->[$fref->[2]]=~/^\U$_/";
456                                                         }
457                                                         $s .= "(" . join(' || ', @t) . ")";
458                                                 } elsif ($fref->[1] eq 'n') {
459                                                         my @t;
460                                                         for (@val) {
461                                                                 return ('num', $dxchan->msg('e21', $_)) unless /^\d+$/;
462                                                                 push @t, "\$r->[$fref->[2]]==$_";
463                                                         }
464                                                         $s .= "(" . join(' || ', @t) . ")";
465                                                 } elsif ($fref->[1] eq 'r') {
466                                                         my @t;
467                                                         for (@val) {
468                                                                 return ('range', $dxchan->msg('e23', $_)) unless /^(\d+)\/(\d+)$/;
469                                                                 push @t, "(\$r->[$fref->[2]]>=$1 && \$r->[$fref->[2]]<=$2)";
470                                                         }
471                                                         $s .= "(" . join(' || ', @t) . ")";
472                                                 } elsif ($fref->[1] eq 't') {
473                                                         my @t;
474                                                         for (@val) {
475                                                                 s/\*//g;
476                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
477                                                         }
478                                                         $s .= "(" . join(' || ', @t) . ")";
479                                                 } else {
480                                                         confess("invalid letter $fref->[1]");
481                                                 }
482                                                 ++$found;
483                                                 last;
484                                         }
485                                 }
486                                 return ('unknown', $dxchan->msg('e20', $tok)) unless $found;
487                         } else {
488                                 return ('no', $dxchan->msg('filter2', $tok));
489                         }
490                 }
491                 
492         }
493
494         # tidy up the user string
495         $user =~ s/\&\&/ and /g;
496         $user =~ s/\|\|/ or /g;
497         $user =~ s/\!/ not /g;
498         $user =~ s/\s+/ /g;
499         
500         return (0, $filter, $fno, $user, "$s");
501 }
502
503 # a filter accept/reject command
504 sub cmd
505 {
506         my ($self, $dxchan, $sort, $type, $line) = @_;
507         
508         return $dxchan->msg('filter5') unless $line;
509
510         my ($r, $filter, $fno, $user, $s) = $self->parse($dxchan, $sort, $line);
511         return (1,$filter) if $r;
512
513         my $fn = "filter$fno";
514
515         $filter->{$fn} = {} unless exists $filter->{$fn};
516         $filter->{$fn}->{$type} = {} unless exists $filter->{$fn}->{$type};
517
518         $filter->{$fn}->{$type}->{user} = $user;
519         $filter->{$fn}->{$type}->{asc} = $s;
520         $r = $filter->compile($fn, $type);
521         return (1,$r) if $r;
522         
523         $r = $filter->write;
524         return (1,$r) if $r;
525         
526         $filter->install;
527
528     return (0, $filter, $fno);
529 }
530
531 package Filter::Old;
532
533 use strict;
534 use DXVars;
535 use DXUtil;
536 use DXDebug;
537 use vars qw(@ISA);
538 @ISA = qw(Filter);
539
540 # the OLD instructions!
541 #
542 # Each filter file has the same structure:-
543 #
544 # <some comment>
545 # @in = (
546 #      [ action, fieldno, fieldsort, comparison, action data ],
547 #      ...
548 # );
549 #
550 # The action is usually 1 or 0 but could be any numeric value
551 #
552 # The fieldno is the field no in the list of fields that is presented
553 # to 'Filter::it' 
554 #
555 # The fieldsort is the type of field that we are dealing with which 
556 # currently can be 'a', 'n', 'r' or 'd'. 'a' is alphanumeric, 'n' is 
557 # numeric, 'r' is ranges of pairs of numeric values and 'd' is default.
558 #
559 # Filter::it basically goes thru the list of comparisons from top to
560 # bottom and when one matches it will return the action and the action data as a list. 
561 # The fields
562 # are the element nos of the list that is presented to Filter::it. Element
563 # 0 is the first field of the list.
564 #
565
566 #
567 # takes the reference to the filter (the first argument) and applies
568 # it to the subsequent arguments and returns the action specified.
569 #
570 sub it
571 {
572         my $self = shift;
573         my $filter = $self->{filter};            # this is now a bless ref of course but so what
574         
575         my ($action, $field, $fieldsort, $comp, $actiondata);
576         my $ref;
577
578         # default action is 1
579         $action = 1;
580         $actiondata = "";
581         return ($action, $actiondata) if !$filter;
582
583         for $ref (@{$filter}) {
584                 ($action, $field, $fieldsort, $comp, $actiondata) = @{$ref};
585                 if ($fieldsort eq 'n') {
586                         my $val = $_[$field];
587                         return ($action, $actiondata)  if grep $_ == $val, @{$comp};
588                 } elsif ($fieldsort eq 'r') {
589                         my $val = $_[$field];
590                         my $i;
591                         my @range = @{$comp};
592                         for ($i = 0; $i < @range; $i += 2) {
593                                 return ($action, $actiondata)  if $val >= $range[$i] && $val <= $range[$i+1];
594                         }
595                 } elsif ($fieldsort eq 'a') {
596                         return ($action, $actiondata)  if $_[$field] =~ m{$comp};
597                 } else {
598                         return ($action, $actiondata);      # the default action
599                 }
600         }
601 }
602
603 sub print
604 {
605         my $self = shift;
606         my $call = shift;
607         my $sort = shift;
608         my $flag = shift || "";
609         return "$call: Old Style Filter $flag $sort";
610 }
611
612 1;
613 __END__