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