ff4ab2e868e95aff35aa6014edaa2018c98045c5
[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         my $data = ref $_[0] ? shift : \@_;
202
203         my $r = @keys > 0 ? 0 : 1;
204         foreach $key (@keys) {
205                 $filter = $self->{$key};
206                 if ($filter->{reject} && exists $filter->{reject}->{code}) {
207                         $type = 'reject';
208                         $asc = $filter->{reject}->{user};
209                         if (&{$filter->{reject}->{code}}($data)) {
210                                 $r = 0;
211                                 last;
212                         } else {
213                                 $r = 1;
214                         }               
215                 }
216                 if ($filter->{accept} && exists $filter->{accept}->{code}) {
217                         $type = 'accept';
218                         $asc = $filter->{accept}->{user};
219                         if (&{$filter->{accept}->{code}}($data)) {
220                                 $r = 1;
221                                 last;
222                         } else {
223                                 $r = 0;
224                         }                       
225                 } 
226         }
227
228         # hops are done differently (simply) 
229         my $hops = $self->{hops} if exists $self->{hops};
230
231         if (isdbg('filter')) {
232                 my $args = join '\',\'', map {defined $_ ? $_ : 'undef'} @$data;
233                 my $true = $r ? "OK " : "REJ";
234                 my $sort = $self->{sort};
235                 my $dir = $self->{name} =~ /^in_/i ? "IN " : "OUT";
236                 
237                 my $h = $hops || '';
238                 dbg("$true $dir: $type/$sort with $asc on '$args' $h") if isdbg('filter');
239         }
240         return ($r, $hops);
241 }
242
243 # this writes out the filter in a form suitable to be read in by 'read_in'
244 # It expects a list of references to filter lines
245 sub write
246 {
247         my $self = shift;
248         my $sort = $self->{sort};
249         my $name = $self->{name};
250         my $dir = "$filterbasefn/$sort";
251         my $fn = "$dir/$name";
252
253         mkdir $dir, 0775 unless -e $dir; 
254     rename $fn, "$fn.o" if -e $fn;
255         my $fh = new IO::File ">$fn";
256         if ($fh) {
257                 my $dd = new Data::Dumper([ $self ]);
258                 $dd->Indent(1);
259                 $dd->Terse(1);
260                 $dd->Quotekeys($] < 5.005 ? 1 : 0);
261                 $fh->print($dd->Dumpxs);
262                 $fh->close;
263         } else {
264                 rename "$fn.o", $fn if -e "$fn.o";
265                 return "$fn $!";
266         }
267         return undef;
268 }
269
270 sub print
271 {
272         my $self = shift;
273         my $name = shift || $self->{name};
274         my $sort = shift || $self->{sort};
275         my $flag = shift || "";
276         my @out;
277         $name =~ s/.pl$//;
278         
279         push @out, join(' ',  $name , ':', $sort, $flag);
280         my $filter;
281         my $key;
282         foreach $key (sort $self->getfilkeys) {
283                 my $filter = $self->{$key};
284                 if (exists $filter->{reject} && exists $filter->{reject}->{user}) {
285                         push @out, ' ' . join(' ', $key, 'reject', $filter->{reject}->{user});
286                 }
287                 if (exists $filter->{accept} && exists $filter->{accept}->{user}) {
288                         push @out, ' ' . join(' ', $key, 'accept', $filter->{accept}->{user});
289                 } 
290         }
291         return @out;
292 }
293
294 sub install
295 {
296         my $self = shift;
297         my $remove = shift;
298         my $name = uc $self->{name};
299         my $sort = $self->{sort};
300         my $in = "";
301         $in = "in" if $name =~ s/^IN_//;
302         $name =~ s/.PL$//;
303                 
304         my $dxchan;
305         my @dxchan;
306         if ($name eq 'NODE_DEFAULT') {
307                 @dxchan = DXChannel::get_all_nodes();
308         } elsif ($name eq 'USER_DEFAULT') {
309                 @dxchan = DXChannel::get_all_users();
310         } else {
311                 $dxchan = DXChannel->get($name);
312                 push @dxchan, $dxchan if $dxchan;
313         }
314         foreach $dxchan (@dxchan) {
315                 my $n = "$in$sort" . "filter";
316                 my $i = $in ? 'IN_' : '';
317                 my $ref = $dxchan->$n();
318                 if (!$ref || ($ref && uc $ref->{name} eq "$i$name.PL")) {
319                         $dxchan->$n($remove ? undef : $self);
320                 }
321         }
322 }
323
324 sub delete
325 {
326         my ($sort, $call, $flag, $fno) = @_;
327         
328         # look for the file
329         my $fn = getfn($sort, $call, $flag);
330         my $filter = read_in($sort, $call, $flag);
331         if ($filter) {
332                 if ($fno eq 'all') {
333                         my $key;
334                         foreach $key ($filter->getfilkeys) {
335                                 delete $filter->{$key};
336                         }
337                 } elsif (exists $filter->{"filter$fno"}) {
338                         delete $filter->{"filter$fno"}; 
339                 }
340                 
341                 # get rid 
342                 if ($filter->{hops} || $filter->getfilkeys) {
343                         $filter->install;
344                         $filter->write;
345                 } else {
346                         $filter->install(1);
347                         unlink $fn;
348                 }
349         }
350 }
351
352 package Filter::Cmd;
353
354 use strict;
355 use DXVars;
356 use DXUtil;
357 use DXDebug;
358 use vars qw(@ISA);
359 @ISA = qw(Filter);
360
361 # the general purpose command processor
362 # this is called as a subroutine not as a method
363 sub parse
364 {
365         my ($self, $dxchan, $sort, $line) = @_;
366         my $ntoken = 0;
367         my $fno = 1;
368         my $filter;
369         my ($flag, $call);
370         my $s;
371         my $user;
372         
373         # check the line for non legal characters
374         return ('ill', $dxchan->msg('e19')) if $line =~ /[^\s\w,_\-\*\/\(\)!]/;
375         
376         # add some spaces for ease of parsing
377         $line =~ s/([\(\)])/ $1 /g;
378         $line = lc $line;
379         
380         my @f = split /\s+/, $line;
381         my $conj = ' && ';
382         my $not = "";
383         while (@f) {
384                 if ($ntoken == 0) {
385                         
386                         if (@f && $dxchan->priv >= 8 && ((is_callsign(uc $f[0]) && DXUser->get(uc $f[0])) || $f[0] =~ /(?:node|user)_default/)) {
387                                 $call = shift @f;
388                                 if ($f[0] eq 'input') {
389                                         shift @f;
390                                         $flag++;
391                                 }
392                         } else {
393                                 $call = $dxchan->call;
394                         }
395
396                         if (@f && $f[0] =~ /^\d$/) {
397                                 $fno = shift @f;
398                         }
399
400                         $filter = Filter::read_in($sort, $call, $flag);
401                         $filter = Filter->new($sort, $call, $flag) if !$filter || $filter->isa('Filter::Old');
402                         
403                         $ntoken++;
404                         next;
405                 }
406
407                 # do the rest of the filter tokens
408                 if (@f) {
409                         my $tok = shift @f;
410                         if ($tok eq '(') {
411                                 if ($s) {
412                                         $s .= $conj;
413                                         $user .= $conj;
414                                         $conj = "";
415                                 }
416                                 if ($not) {
417                                         $s .= $not;
418                                         $user .= $not;
419                                         $not = "";
420                                 }
421                                 $s .= $tok;
422                                 $user .= $tok;
423                                 next;
424                         } elsif ($tok eq ')') {
425                                 $conj = ' && ';
426                                 $not ="";
427                                 $s .= $tok;
428                                 $user .= $tok;
429                                 next;
430                         } elsif ($tok eq 'all') {
431                                 $s .= '1';
432                                 $user .= $tok;
433                                 last;
434                         } elsif ($tok eq 'or') {
435                                 $conj = ' || ' if $conj ne ' || ';
436                                 next;
437                         } elsif ($tok eq 'and') {
438                                 $conj = ' && ' if $conj ne ' && ';
439                                 next;
440                         } elsif ($tok eq 'not' || $tok eq '!') {
441                                 $not = '!';
442                                 next;
443                         }
444                         if (@f) {
445                                 my $val = shift @f;
446                                 my @val = split /,/, $val;
447
448                                 if ($s) {
449                                         $s .= $conj ;
450                                         $user .= $conj;
451                                         $conj = ' && ';
452                                 }
453
454                                 if ($not) {
455                                         $s .= $not;
456                                         $user .= $not;
457                                         $not = '';
458                                 }
459
460                                 $user .= "$tok $val";
461                                 
462                                 my $fref;
463                                 my $found;
464                                 foreach $fref (@$self) {
465                                         
466                                         if ($fref->[0] eq $tok) {
467                                                 if ($fref->[4]) {
468                                                         my @nval;
469                                                         for (@val) {
470                                                                 push @nval, split(',', &{$fref->[4]}($dxchan, $_));
471                                                         }
472                                                         @val = @nval;
473                                                 }
474                                                 if ($fref->[1] eq 'a') {
475                                                         my @t;
476                                                         for (@val) {
477                                                                 s/\*//g;
478                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
479                                                         }
480                                                         $s .= "(" . join(' || ', @t) . ")";
481                                                 } elsif ($fref->[1] eq 'c') {
482                                                         my @t;
483                                                         for (@val) {
484                                                                 s/\*//g;
485                                                                 push @t, "\$r->[$fref->[2]]=~/^\U$_/";
486                                                         }
487                                                         $s .= "(" . join(' || ', @t) . ")";
488                                                 } elsif ($fref->[1] eq 'n') {
489                                                         my @t;
490                                                         for (@val) {
491                                                                 return ('num', $dxchan->msg('e21', $_)) unless /^\d+$/;
492                                                                 push @t, "\$r->[$fref->[2]]==$_";
493                                                         }
494                                                         $s .= "(" . join(' || ', @t) . ")";
495                                                 } elsif ($fref->[1] =~ /^n[ciz]$/ ) {    # for DXCC, ITU, CQ Zone    
496                                                         my $cmd = $fref->[1];
497                                                         my @pre = Prefix::to_ciz($cmd, @val);
498                                                         return ('numpre', $dxchan->msg('e27', $_)) unless @pre;
499                                                         $s .= "(" . join(' || ', map {"\$r->[$fref->[2]]==$_"} @pre) . ")";
500                                                 } elsif ($fref->[1] =~ /^ns$/ ) {    # for DXCC, ITU, CQ Zone    
501                                                         my $cmd = $fref->[1];
502                                                         my @pre = Prefix::to_ciz($cmd, @val);
503                                                         return ('numpre', $dxchan->msg('e27', $_)) unless @pre;
504                                                         $s .= "(" . "!\$USDB::present || grep \$r->[$fref->[2]] eq \$_, qw(" . join(' ' ,map {uc} @pre) . "))";
505                                                 } elsif ($fref->[1] eq 'r') {
506                                                         my @t;
507                                                         for (@val) {
508                                                                 return ('range', $dxchan->msg('e23', $_)) unless /^(\d+)\/(\d+)$/;
509                                                                 push @t, "(\$r->[$fref->[2]]>=$1 && \$r->[$fref->[2]]<=$2)";
510                                                         }
511                                                         $s .= "(" . join(' || ', @t) . ")";
512                                                 } elsif ($fref->[1] eq 't') {
513                                                         my @t;
514                                                         for (@val) {
515                                                                 s/\*//g;
516                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
517                                                         }
518                                                         $s .= "(" . join(' || ', @t) . ")";
519                                                 } else {
520                                                         confess("invalid letter $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'. 'a' is alphanumeric, 'n' is 
599 # numeric, 'r' is ranges of pairs of numeric values and 'd' is default.
600 #
601 # Filter::it basically goes thru the list of comparisons from top to
602 # bottom and when one matches it will return the action and the action data as a list. 
603 # The fields
604 # are the element nos of the list that is presented to Filter::it. Element
605 # 0 is the first field of the list.
606 #
607
608 #
609 # takes the reference to the filter (the first argument) and applies
610 # it to the subsequent arguments and returns the action specified.
611 #
612 sub it
613 {
614         my $self = shift;
615         my $filter = $self->{filter};            # this is now a bless ref of course but so what
616         
617         my ($action, $field, $fieldsort, $comp, $actiondata);
618         my $ref;
619
620         # default action is 1
621         $action = 1;
622         $actiondata = "";
623         return ($action, $actiondata) if !$filter;
624
625         for $ref (@{$filter}) {
626                 ($action, $field, $fieldsort, $comp, $actiondata) = @{$ref};
627                 if ($fieldsort eq 'n') {
628                         my $val = $_[$field];
629                         return ($action, $actiondata)  if grep $_ == $val, @{$comp};
630                 } elsif ($fieldsort eq 'r') {
631                         my $val = $_[$field];
632                         my $i;
633                         my @range = @{$comp};
634                         for ($i = 0; $i < @range; $i += 2) {
635                                 return ($action, $actiondata)  if $val >= $range[$i] && $val <= $range[$i+1];
636                         }
637                 } elsif ($fieldsort eq 'a') {
638                         return ($action, $actiondata)  if $_[$field] =~ m{$comp};
639                 } else {
640                         return ($action, $actiondata);      # the default action
641                 }
642         }
643 }
644
645 sub print
646 {
647         my $self = shift;
648         my $call = shift;
649         my $sort = shift;
650         my $flag = shift || "";
651         return "$call: Old Style Filter $flag $sort";
652 }
653
654 1;
655 __END__