2 # Copyright (C) 2013-2018 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <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
18 use PublicInbox::MIME;
20 use PublicInbox::Config;
21 use PublicInbox::Emergency;
22 use PublicInbox::Filter::Base;
23 use PublicInbox::InboxWritable;
24 use PublicInbox::Spamcheck;
26 # n.b: hopefully we can setup the emergency path without bailing due to
27 # user error, we really want to setup the emergency destination ASAP
28 # in case there's bugs in our code or user error.
29 my $emergency = $ENV{PI_EMERGENCY} || "$ENV{HOME}/.public-inbox/emergency/";
30 $ems = PublicInbox::Emergency->new($emergency);
31 my $str = eval { local $/; <STDIN> };
32 $str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
34 my $simple = Email::Simple->new(\$str);
35 my $config = PublicInbox::Config->new;
36 my $key = 'publicinboxmda.spamcheck';
37 my $default = 'PublicInbox::Spamcheck::Spamc';
38 my $spamc = PublicInbox::Spamcheck::get($config, $key, $default);
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(67); # EX_NOUSER 5.1.1 user unknown
43 $dst->{mainrepo} or do_exit(67);
44 $dst = PublicInbox::InboxWritable->new($dst);
46 # pre-check, MDA has stricter rules than an importer might;
47 do_exit(0) unless PublicInbox::MDA->precheck($simple, $dst->{address});
52 $spam_ok = $spamc->spamcheck($ems->fh, \$str);
53 # update the emergency dump with the new message:
54 $emm = PublicInbox::Emergency->new($emergency);
57 } else { # no spam checking configured:
61 read($fh, $str, -s $fh);
64 my $mime = PublicInbox::MIME->new(\$str);
65 do_exit(0) unless $spam_ok;
67 my $fcfg = $dst->{filter} || '';
68 # -mda defaults to the strict base filter
70 $dst->{filter} = 'PublicInbox::Filter::Base';
71 } elsif ($fcfg eq 'scrub') { # legacy alias, undocumented, remove?
72 $dst->{filter} = 'PublicInbox::Filter::Mirror';
74 my $filter = $dst->filter;
75 my $ret = $filter->delivery($mime);
76 if (ref($ret) && $ret->isa('Email::MIME')) { # filter altered message
78 } elsif ($ret == PublicInbox::Filter::Base::IGNORE) {
79 do_exit(0); # chuck it to emergency
80 } elsif ($ret == PublicInbox::Filter::Base::REJECT) {
81 $! = 65; # EX_DATAERR 5.6.0 data format error
82 die $filter->err, "\n";
86 PublicInbox::MDA->set_list_headers($mime, $dst);
87 my $im = $dst->importer(0);
88 if (defined $im->add($mime)) {
91 # this message is similar to what ssoma-mda shows:
92 print STDERR "CONFLICT: Message-ID: ",
93 $mime->header_obj->header_raw('Message-ID'),