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