]> Sergey Matveev's repositories - public-inbox.git/blob - public-inbox-mda
public-inbox-mda: reject messages without From header
[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 Email::Address;
8 use PublicInbox::Filter;
9 use IPC::Run qw(run);
10 my $usage = "public-inbox-mda main_repo fail_repo < rfc2822_message";
11 my $filter = Email::Filter->new(emergency => "~/emergency.mbox");
12 my $main_repo = shift @ARGV or die "Usage: $usage\n";
13 my $fail_repo = shift @ARGV or die "Usage: $usage\n";
14 my $max = 1024 * 500; # same as spamc
15
16 my $filtered;
17 if ($filter->simple->header("From")
18     && length($filter->simple->as_string) <= $max
19     && PublicInbox->recipient_specified($filter)
20     && do_spamc($filter->simple, \$filtered)) {
21         # update our message with SA headers (in case our filter rejects it)
22         my $simple = Email::Simple->new($filtered);
23         $filtered = undef;
24         $filter->simple($simple);
25
26         if (PublicInbox::Filter->run($simple)) {
27                 # run spamc again on the HTML-free message
28                 if (do_spamc($simple, \$filtered)) {
29                         $filter->simple(Email::Simple->new($filtered));
30                         $filter->pipe("ssoma-mda", $main_repo);
31                 } else {
32                         $filter->pipe("ssoma-mda", $fail_repo);
33                 }
34         } else {
35                 # PublicInbox::Filter nuked everything, oops :x
36                 $filter->pipe("ssoma-mda", $fail_repo);
37         }
38 } else {
39         # if SA thinks it's spam or there's an error:
40         # don't bother with our own filtering
41         $filter->pipe("ssoma-mda", $fail_repo);
42 }
43 die "Email::Filter failed to exit\n";
44
45 # we depend on "report_safe 0" in /etc/spamassassin/*.cf with --headers
46 # not using Email::Filter->pipe here since we want the stdout of
47 # the command even on failure (spamc will set $? on error).
48 sub do_spamc {
49         my ($simple, $out) = @_;
50         eval {
51                 my $orig = $simple->as_string;
52                 run([qw/spamc -E --headers/], \$orig, $out);
53         };
54
55         return ($@ || $? || !defined($$out) || length($$out) == 0) ? 0 : 1;
56 }