]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/MDA.pm
move precheck to MDA namespace
[public-inbox.git] / lib / PublicInbox / MDA.pm
1 # Copyright (C) 2013, Eric Wong <normalperson@yhbt.net> and all contributors
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 package PublicInbox::MDA;
4 use strict;
5 use warnings;
6 use Email::Address;
7 use Date::Parse qw(strptime);
8 use constant MAX_SIZE => 1024 * 500; # same as spamc default
9
10 # drop plus addressing for matching
11 sub __drop_plus {
12         my ($str_addr) = @_;
13         $str_addr =~ s/\+.*\@/\@/;
14         $str_addr;
15 }
16
17 # do not allow Bcc, only Cc and To if recipient is set
18 sub precheck {
19         my ($klass, $filter, $recipient) = @_;
20         my $simple = $filter->simple;
21         my $mid = $simple->header("Message-ID");
22         return 0 unless usable_str(length('<m@h>'), $mid) && $mid =~ /\@/;
23         return 0 unless usable_str(length('u@h'), $filter->from);
24         return 0 unless usable_str(length(':o'), $simple->header("Subject"));
25         return 0 unless usable_date($simple->header("Date"));
26         return 0 if length($simple->as_string) > MAX_SIZE;
27         recipient_specified($filter, $recipient);
28 }
29
30 sub usable_str {
31         my ($len, $str) = @_;
32         defined($str) && length($str) >= $len;
33 }
34
35 sub usable_date {
36         my @t = eval { strptime(@_) };
37         scalar @t;
38 }
39
40 sub recipient_specified {
41         my ($filter, $recipient) = @_;
42         defined($recipient) or return 1; # for mass imports
43         my @recip = Email::Address->parse($recipient);
44         my $oaddr = __drop_plus($recip[0]->address);
45         $oaddr = qr/\b\Q$oaddr\E\b/i;
46         my @to = Email::Address->parse($filter->to);
47         my @cc = Email::Address->parse($filter->cc);
48         foreach my $addr (@to, @cc) {
49                 if (__drop_plus($addr->address) =~ $oaddr) {
50                         return 1;
51                 }
52         }
53         return 0;
54 }
55
56 1;