]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Filter.pm
emergency: implement new emergency Maildir delivery
[public-inbox.git] / lib / PublicInbox / Filter.pm
1 # Copyright (C) 2013-2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
3 #
4 # Used to filter incoming mail for -mda and importers
5 # This only exposes one function: run
6 # Note: the settings here are highly opinionated.  Obviously, this is
7 # Free Software (AGPLv3), so you may change it if you host yourself.
8 package PublicInbox::Filter;
9 use strict;
10 use warnings;
11 use Email::MIME;
12 use Email::MIME::ContentType qw/parse_content_type/;
13 use Email::Filter;
14 use IPC::Run;
15 our $VERSION = '0.0.1';
16 use constant NO_HTML => '*** We only accept plain-text email, no HTML ***';
17 use constant TEXT_ONLY => '*** We only accept plain-text email ***';
18
19 # start with the same defaults as mailman
20 our $BAD_EXT = qr/\.(exe|bat|cmd|com|pif|scr|vbs|cpl|zip)\s*\z/i;
21 our $MIME_HTML = qr!\btext/x?html\b!i;
22 our $MIME_TEXT_ANY = qr!\btext/[a-z0-9\+\._-]+\b!i;
23
24 # this is highly opinionated delivery
25 # returns 0 only if there is nothing to deliver
26 sub run {
27         my ($class, $mime, $filter) = @_;
28
29         my $content_type = $mime->header('Content-Type') || 'text/plain';
30
31         if ($content_type =~ m!\btext/plain\b!i) {
32                 return 1; # yay, nothing to do
33         } elsif ($content_type =~ $MIME_HTML) {
34                 $filter->reject(NO_HTML) if $filter;
35                 # HTML-only, non-multipart
36                 my $body = $mime->body;
37                 my $ct_parsed = parse_content_type($content_type);
38                 dump_html(\$body, $ct_parsed->{attributes}->{charset});
39                 replace_body($mime, $body);
40                 return 1;
41         } elsif ($content_type =~ m!\bmultipart/!i) {
42                 return strip_multipart($mime, $content_type, $filter);
43         } else {
44                 $filter->reject(TEXT_ONLY) if $filter;
45                 replace_body($mime, "$content_type message scrubbed");
46                 return 0;
47         }
48 }
49
50 sub replace_part {
51         my ($mime, $part, $type) = ($_[0], $_[1], $_[3]);
52         # don't copy $_[2], that's the body (it may be huge)
53
54         # Email::MIME insists on setting Date:, so just set it consistently
55         # to avoid conflicts to avoid git merge conflicts in a split brain
56         # situation.
57         unless (defined $part->header('Date')) {
58                 my $date = $mime->header('Date') ||
59                            'Thu, 01 Jan 1970 00:00:00 +0000';
60                 $part->header_set('Date', $date);
61         }
62
63         $part->charset_set(undef);
64         $part->name_set(undef);
65         $part->filename_set(undef);
66         $part->format_set(undef);
67         $part->encoding_set('8bit');
68         $part->disposition_set(undef);
69         $part->content_type_set($type);
70         $part->body_set($_[2]);
71 }
72
73 # converts one part of a multipart message to text
74 sub html_part_to_text {
75         my ($mime, $part) = @_;
76         my $body = $part->body;
77         my $ct_parsed = parse_content_type($part->content_type);
78         dump_html(\$body, $ct_parsed->{attributes}->{charset});
79         replace_part($mime, $part, $body, 'text/plain');
80 }
81
82 # modifies $_[0] in place
83 sub dump_html {
84         my ($body, $charset) = @_;
85         $charset ||= 'US-ASCII';
86         my @cmd = qw(lynx -stdin -stderr -dump);
87         my $out = "";
88         my $err = "";
89
90         # be careful about remote command injection!
91         if ($charset =~ /\A([A-Za-z0-9\-]+)\z/) {
92                 push @cmd, "-assume_charset=$charset";
93         }
94         if (IPC::Run::run(\@cmd, $body, \$out, \$err)) {
95                 $out =~ s/\r\n/\n/sg;
96                 $$body = $out;
97         } else {
98                 # give them an ugly version:
99                 $$body = "public-inbox HTML conversion failed: $err\n" .
100                          $$body . "\n";
101         }
102 }
103
104 # this is to correct old archives during import.
105 sub strip_multipart {
106         my ($mime, $content_type, $filter) = @_;
107
108         my (@html, @keep);
109         my $rejected = 0;
110         my $ok = 1;
111
112         # scan through all parts once
113         $mime->walk_parts(sub {
114                 my ($part) = @_;
115                 return if $part->subparts; # walk_parts already recurses
116
117                 # some extensions are just bad, reject them outright
118                 my $fn = $part->filename;
119                 if (defined($fn) && $fn =~ $BAD_EXT) {
120                         $filter->reject("Bad file type: $1") if $filter;
121                         $rejected++;
122                         return;
123                 }
124
125                 my $part_type = $part->content_type || '';
126                 if ($part_type =~ m!\btext/plain\b!i) {
127                         push @keep, $part;
128                 } elsif ($part_type =~ $MIME_HTML) {
129                         $filter->reject(NO_HTML) if $filter;
130                         push @html, $part;
131                 } elsif ($part_type =~ $MIME_TEXT_ANY) {
132                         # Give other text attachments the benefit of the doubt,
133                         # here?  Could be source code or script the user wants
134                         # help with.
135
136                         push @keep, $part;
137                 } elsif ($part_type eq '' ||
138                          $part_type =~ m!\bapplication/octet-stream\b!i) {
139                         # unfortunately, some mailers don't set correct types,
140                         # let messages of unknown type through but do not
141                         # change the sender-specified type
142                         if (recheck_type_ok($part)) {
143                                 push @keep, $part;
144                         } elsif ($filter) {
145                                 $filter->reject("Bad attachment: $part_type ".
146                                                 TEXT_ONLY);
147                         } else {
148                                 $rejected++;
149                         }
150                 } elsif ($part_type =~ m!\bapplication/pgp-signature\b!i) {
151                         # PGP signatures are not huge, we may keep them.
152                         # They can only be valid if it's the last element,
153                         # so we keep them iff the message is unmodified:
154                         if ($rejected == 0 && !@html) {
155                                 push @keep, $part;
156                         }
157                 } elsif ($filter) {
158                         $filter->reject("unacceptable mime-type: $part_type ".
159                                         TEXT_ONLY);
160                 } else {
161                         # reject everything else, including non-PGP signatures
162                         $rejected++;
163                 }
164         });
165
166         if ($content_type =~ m!\bmultipart/alternative\b!i) {
167                 if (scalar @keep == 1) {
168                         return collapse($mime, $keep[0]);
169                 }
170         } else { # convert HTML parts to plain text
171                 foreach my $part (@html) {
172                         html_part_to_text($mime, $part);
173                         push @keep, $part;
174                 }
175         }
176
177         if (@keep == 0) {
178                 @keep = (Email::MIME->create(
179                         attributes => {
180                                 content_type => 'text/plain',
181                                 charset => 'US-ASCII',
182                                 encoding => '8bit',
183                         },
184                         body_str => 'all attachments scrubbed by '. __PACKAGE__
185                 ));
186                 $ok = 0;
187         }
188         if (scalar(@html) || $rejected) {
189                 $mime->parts_set(\@keep);
190                 $mime->body_set($mime->body_raw);
191                 mark_changed($mime);
192         } # else: no changes
193
194         return $ok;
195 }
196
197 sub mark_changed {
198         my ($mime) = @_;
199         $mime->header_set('X-Content-Filtered-By', __PACKAGE__ ." $VERSION");
200 }
201
202 sub collapse {
203         my ($mime, $part) = @_;
204         $mime->header_set('Content-Type', $part->content_type);
205         $mime->body_set($part->body_raw);
206         my $cte = $part->header('Content-Transfer-Encoding');
207         if (defined($cte) && $cte ne '') {
208                 $mime->header_set('Content-Transfer-Encoding', $cte);
209         }
210         mark_changed($mime);
211         return 1;
212 }
213
214 sub replace_body {
215         my $mime = $_[0];
216         $mime->body_set($_[1]);
217         $mime->header_set('Content-Type', 'text/plain');
218         if ($mime->header('Content-Transfer-Encoding')) {
219                 $mime->header_set('Content-Transfer-Encoding', undef);
220         }
221         mark_changed($mime);
222 }
223
224 # Check for display-able text, no messed up binaries
225 # Note: we can not rewrite the message with the detected mime type
226 sub recheck_type_ok {
227         my ($part) = @_;
228         my $s = $part->body;
229         ((length($s) < 0x10000) && ($s =~ /\A([[:print:]\s]+)\z/s));
230 }
231
232 1;