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