Handle hostnames with upper-case letters
[webmin.git] / qmailadmin / filter.pl
1 #!/usr/local/bin/perl
2 # filter.pl
3
4 # read qmail module config
5 $p = -l $0 ? readlink($0) : $0;
6 $p =~ /^(.*)\/[^\/]+$/;
7 open(CONF, "$1/config");
8 while(<CONF>) {
9         if (/^(\S+)=(.*)/) {
10                 $config{$1} = $2;
11                 }
12         }
13 close(CONF);
14
15 # read headers and body
16 $fromline = <STDIN>;
17 while(<STDIN>) {
18         $headers .= $_;
19         s/\r|\n//g;
20         if (/^(\S+):\s+(.*)/) {
21                 $header{lc($1)} = $2;
22                 }
23         elsif (!$_) { last; }
24         }
25 while(<STDIN>) {
26         $body .= $_;
27         }
28
29 # read the filter file
30 if (open(FILTER, $ARGV[0])) {
31         while(<FILTER>) {
32                 s/\r|\n//g;
33                 if (/^(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/) {
34                         push(@filter, [ $1, $2, $3, $4 ]);
35                         }
36                 elsif (/^(\S+)\s+(\S+)$/) {
37                         push(@filter, [ $1, $2 ]);
38                         }
39                 }
40         close(FILTER);
41         }
42 else {
43         print STDERR "Filter file $ARGV[0] does not exist!\n";
44         exit 1;
45         }
46
47 # run the filter to find the first matching rule
48 open(LOG, ">>$ARGV[0].log");
49 foreach $f (@filter) {
50         local $field = $f->[2] eq 'body' ? $body : $header{$f->[2]};
51         local $st = 0;
52         if ($f->[0] == 0) {
53                 $st = ($field !~ /$f->[3]/i);
54                 }
55         elsif ($f->[0] == 1) {
56                 $st = ($field =~ /$f->[3]/i);
57                 }
58         elsif ($f->[0] == 2) {
59                 $st = 1;
60                 }
61         if ($st) {
62                 # The rule matched!
63                 if ($f->[1] =~ /^\//) {
64                         # Write to a file
65                         open(MAIL, ">>$f->[1]");
66                         print MAIL $fromline;
67                         }
68                 else {
69                         # Forward to another address
70                         $f->[1] =~ s/\\/\\\\/g;
71                         $f->[1] =~ s/'/\\'/g;
72                         open(MAIL, "|$config{'qmail_dir'}/bin/qmail-inject '$f->[1]'");
73                         }
74                 print MAIL $headers;
75                 print MAIL $body;
76                 close(MAIL);
77                 $now = localtime(time());
78                 print LOG "[$now] [$header{'from'}] [",join(" ",@$f),"]\n";
79                 last;
80                 }
81         }
82