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