]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox-mda
177c891e593b4640946ee8d054f15cac67f4469b
[public-inbox.git] / public-inbox-mda
1 #!/usr/bin/perl -w
2 # Copyright (C) 2013, Eric Wong <normalperson@yhbt.net> and all contributors
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
4 use strict;
5 use warnings;
6 use Email::Filter;
7 use PublicInbox::Filter;
8 use IPC::Run qw(run);
9 my $usage = "public-inbox-mda main_repo fail_repo < rfc2822_message";
10 my $filter = Email::Filter->new(emergency => "~/emergency.mbox");
11 my $main_repo = shift @ARGV or die "Usage: $usage\n";
12 my $fail_repo = shift @ARGV or die "Usage: $usage\n";
13 my $max = 1024 * 500; # same as spamc
14
15 my $filtered;
16 if (length($filter->simple->as_string) <= $max
17     && do_spamc($filter->simple, \$filtered)) {
18         # update our message with SA headers (in case our filter rejects it)
19         my $simple = Email::Simple->new($filtered);
20         $filtered = undef;
21         $filter->simple($simple);
22
23         if (PublicInbox::Filter->run($simple)) {
24                 # run spamc again on the HTML-free message
25                 if (do_spamc($simple, \$filtered)) {
26                         $filter->simple(Email::Simple->new($filtered));
27                         $filter->pipe("ssoma-mda", $main_repo);
28                 } else {
29                         $filter->pipe("ssoma-mda", $fail_repo);
30                 }
31         } else {
32                 # PublicInbox::Filter nuked everything, oops :x
33                 $filter->pipe("ssoma-mda", $fail_repo);
34         }
35 } else {
36         # if SA thinks it's spam or there's an error:
37         # don't bother with our own filtering
38         $filter->pipe("ssoma-mda", $fail_repo);
39 }
40 die "Email::Filter failed to exit\n";
41
42 # we depend on "report_safe 0" in /etc/spamassassin/*.cf with --headers
43 # not using Email::Filter->pipe here since we want the stdout of
44 # the command even on failure (spamc will set $? on error).
45 sub do_spamc {
46         my ($simple, $out) = @_;
47         eval {
48                 my $orig = $simple->as_string;
49                 run([qw/spamc -E --headers/], \$orig, $out);
50         };
51
52         return ($@ || $? || !defined($$out) || length($$out) == 0) ? 0 : 1;
53 }