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