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