Change DXUser->get* to DXUser::get*
[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 =~ /[^\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') {
477                                                         my @t;
478                                                         for (@val) {
479                                                                 s/\*//g;
480                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
481                                                         }
482                                                         $s .= "(" . join(' || ', @t) . ")";
483                                                 } elsif ($fref->[1] eq 'c') {
484                                                         my @t;
485                                                         for (@val) {
486                                                                 s/\*//g;
487                                                                 push @t, "\$r->[$fref->[2]]=~/^\U$_/";
488                                                         }
489                                                         $s .= "(" . join(' || ', @t) . ")";
490                                                 } elsif ($fref->[1] eq 'n') {
491                                                         my @t;
492                                                         for (@val) {
493                                                                 return ('num', $dxchan->msg('e21', $_)) unless /^\d+$/;
494                                                                 push @t, "\$r->[$fref->[2]]==$_";
495                                                         }
496                                                         $s .= "(" . join(' || ', @t) . ")";
497                                                 } elsif ($fref->[1] =~ /^n[ciz]$/ ) {    # for DXCC, ITU, CQ Zone    
498                                                         my $cmd = $fref->[1];
499                                                         my @pre = Prefix::to_ciz($cmd, @val);
500                                                         return ('numpre', $dxchan->msg('e27', $_)) unless @pre;
501                                                         $s .= "(" . join(' || ', map {"\$r->[$fref->[2]]==$_"} @pre) . ")";
502                                                 } elsif ($fref->[1] =~ /^ns$/ ) {    # 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 .= "(" . "!\$USDB::present || grep \$r->[$fref->[2]] eq \$_, qw(" . join(' ' ,map {uc} @pre) . "))";
507                                                 } elsif ($fref->[1] eq 'r') {
508                                                         my @t;
509                                                         for (@val) {
510                                                                 return ('range', $dxchan->msg('e23', $_)) unless /^(\d+)\/(\d+)$/;
511                                                                 push @t, "(\$r->[$fref->[2]]>=$1 && \$r->[$fref->[2]]<=$2)";
512                                                         }
513                                                         $s .= "(" . join(' || ', @t) . ")";
514                                                 } elsif ($fref->[1] eq 't') {
515                                                         my @t;
516                                                         for (@val) {
517                                                                 s/\*//g;
518                                                                 push @t, "\$r->[$fref->[2]]=~/$_/i";
519                                                         }
520                                                         $s .= "(" . join(' || ', @t) . ")";
521                                                 } else {
522                                                         confess("invalid letter $fref->[1]");
523                                                 }
524                                                 ++$found;
525                                                 last;
526                                         }
527                                 }
528                                 return ('unknown', $dxchan->msg('e20', $tok)) unless $found;
529                         } else {
530                                 return ('no', $dxchan->msg('filter2', $tok));
531                         }
532                 }
533                 
534         }
535
536         # tidy up the user string
537         $user =~ s/\&\&/ and /g;
538         $user =~ s/\|\|/ or /g;
539         $user =~ s/\!/ not /g;
540         $user =~ s/\s+/ /g;
541         
542         return (0, $filter, $fno, $user, "$s");
543 }
544
545 # a filter accept/reject command
546 sub cmd
547 {
548         my ($self, $dxchan, $sort, $type, $line) = @_;
549         
550         return $dxchan->msg('filter5') unless $line;
551
552         my ($r, $filter, $fno, $user, $s) = $self->parse($dxchan, $sort, $line);
553         my $u = DXUser::get_current($user);
554         return (1, $dxchan->msg('isow', $user)) if $u && $u->isolate;
555         return (1, $filter) if $r;
556
557         my $fn = "filter$fno";
558
559         $filter->{$fn} = {} unless exists $filter->{$fn};
560         $filter->{$fn}->{$type} = {} unless exists $filter->{$fn}->{$type};
561
562         $filter->{$fn}->{$type}->{user} = $user;
563         $filter->{$fn}->{$type}->{asc} = $s;
564         $r = $filter->compile($fn, $type);
565         return (1,$r) if $r;
566         
567         $r = $filter->write;
568         return (1,$r) if $r;
569         
570         $filter->install;
571
572     return (0, $filter, $fno);
573 }
574
575 package Filter::Old;
576
577 use strict;
578 use DXVars;
579 use DXUtil;
580 use DXDebug;
581 use vars qw(@ISA);
582 @ISA = qw(Filter);
583
584 # the OLD instructions!
585 #
586 # Each filter file has the same structure:-
587 #
588 # <some comment>
589 # @in = (
590 #      [ action, fieldno, fieldsort, comparison, action data ],
591 #      ...
592 # );
593 #
594 # The action is usually 1 or 0 but could be any numeric value
595 #
596 # The fieldno is the field no in the list of fields that is presented
597 # to 'Filter::it' 
598 #
599 # The fieldsort is the type of field that we are dealing with which 
600 # currently can be 'a', 'n', 'r' or 'd'. 'a' is alphanumeric, 'n' is 
601 # numeric, 'r' is ranges of pairs of numeric values and 'd' is default.
602 #
603 # Filter::it basically goes thru the list of comparisons from top to
604 # bottom and when one matches it will return the action and the action data as a list. 
605 # The fields
606 # are the element nos of the list that is presented to Filter::it. Element
607 # 0 is the first field of the list.
608 #
609
610 #
611 # takes the reference to the filter (the first argument) and applies
612 # it to the subsequent arguments and returns the action specified.
613 #
614 sub it
615 {
616         my $self = shift;
617         my $filter = $self->{filter};            # this is now a bless ref of course but so what
618         
619         my ($action, $field, $fieldsort, $comp, $actiondata);
620         my $ref;
621
622         # default action is 1
623         $action = 1;
624         $actiondata = "";
625         return ($action, $actiondata) if !$filter;
626
627         for $ref (@{$filter}) {
628                 ($action, $field, $fieldsort, $comp, $actiondata) = @{$ref};
629                 if ($fieldsort eq 'n') {
630                         my $val = $_[$field];
631                         return ($action, $actiondata)  if grep $_ == $val, @{$comp};
632                 } elsif ($fieldsort eq 'r') {
633                         my $val = $_[$field];
634                         my $i;
635                         my @range = @{$comp};
636                         for ($i = 0; $i < @range; $i += 2) {
637                                 return ($action, $actiondata)  if $val >= $range[$i] && $val <= $range[$i+1];
638                         }
639                 } elsif ($fieldsort eq 'a') {
640                         return ($action, $actiondata)  if $_[$field] =~ m{$comp};
641                 } else {
642                         return ($action, $actiondata);      # the default action
643                 }
644         }
645 }
646
647 sub print
648 {
649         my $self = shift;
650         my $call = shift;
651         my $sort = shift;
652         my $flag = shift || "";
653         return "$call: Old Style Filter $flag $sort";
654 }
655
656 1;
657 __END__