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