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