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