2 # Copyright (C) 2013-2015 all contributors <meta@public-inbox.org>
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
5 # Mail delivery agent for public-inbox, run from your MTA upon mail delivery
8 my $usage = 'public-inbox-mda < rfc2822_message';
13 $emm = $ems = undef; # trigger DESTROY
19 use Email::MIME::ContentType;
20 $Email::MIME::ContentType::STRICT_PARAMS = 0; # user input is imperfect
22 use PublicInbox::Config;
23 use PublicInbox::Import;
25 use PublicInbox::Emergency;
26 use PublicInbox::Filter::Base;
27 use PublicInbox::Spawn qw(popen_rd);
29 # n.b: hopefully we can setup the emergency path without bailing due to
30 # user error, we really want to setup the emergency destination ASAP
31 # in case there's bugs in our code or user error.
32 my $emergency = $ENV{PI_EMERGENCY} || "$ENV{HOME}/.public-inbox/emergency/";
33 $ems = PublicInbox::Emergency->new($emergency);
34 my $str = eval { local $/; <STDIN> };
36 my $simple = Email::Simple->new(\$str);
37 my $config = PublicInbox::Config->new;
39 my $recipient = $ENV{ORIGINAL_RECIPIENT};
40 defined $recipient or die "ORIGINAL_RECIPIENT not defined in ENV\n";
41 my $dst = $config->lookup($recipient); # first check
42 defined $dst or do_exit(1);
43 my $main_repo = $dst->{mainrepo} or do_exit(1);
45 # pre-check, MDA has stricter rules than an importer might;
46 do_exit(0) unless PublicInbox::MDA->precheck($simple, $dst->{address});
49 my $spam_ok = do_spamc($ems->fh, \$str);
51 $emm = PublicInbox::Emergency->new($emergency);
54 my $mime = Email::MIME->new(\$str);
56 do_exit(0) unless $spam_ok;
58 my $fcfg = $dst->{filter} || '';
64 } elsif ($fcfg eq 'scrub') { # TODO:
65 require PublicInbox::Filter::Mirror;
66 $filter = PublicInbox::Filter::Mirror->new;
68 $filter = PublicInbox::Filter::Base->new;
71 my $ret = $filter->delivery($mime);
72 if (ref($ret) && $ret->isa('Email::MIME')) { # filter altered message
74 } elsif ($ret == PublicInbox::Filter::Base::IGNORE) {
75 do_exit(0); # chuck it to emergency
76 } elsif ($ret == PublicInbox::Filter::Base::REJECT) {
78 die $filter->err, "\n";
81 PublicInbox::MDA->set_list_headers($mime, $dst);
82 my $git = PublicInbox::Git->new($main_repo);
83 my $im = PublicInbox::Import->new($git, $dst->{name}, $recipient);
84 if (defined $im->add($mime)) {
88 # this message is similar to what ssoma-mda shows:
89 print STDERR "CONFLICT: Message-ID: ",
90 $mime->header_obj->header_raw('Message-ID'),
95 # we depend on "report_safe 0" in /etc/spamassassin/*.cf with --headers
98 my $rdr = { 0 => fileno($in) };
99 my ($fh, $pid) = popen_rd([qw/spamc -E --headers/], undef, $rdr);
102 $r = sysread($fh, $$out, 65536, length($$out));
103 } while (defined($r) && $r != 0);
104 close $fh or die "close failed: $!\n";
107 ($? || $$out eq '') ? 0 : 1;