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