]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Filter.pm
6862bb68b82d27bcd66009cafeaa8aa50dfb2585
[public-inbox.git] / lib / PublicInbox / Filter.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 #
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
16 # start with the same defaults as mailman
17 our $BAD_EXT = qr/\.(?:exe|bat|cmd|com|pif|scr|vbs|cpl)\z/i;
18 our $MIME_HTML = qr!\btext/html\b!i;
19 our $MIME_TEXT_ANY = qr!\btext/[a-z0-9\+\._-]+\b!i;
20
21 # this is highly opinionated delivery
22 # returns 0 only if there is nothing to deliver
23 sub run {
24         my ($class, $mime) = @_;
25
26         my $content_type = $mime->header('Content-Type') || 'text/plain';
27
28         # kill potentially bad/confusing headers
29         # Note: ssoma already does this, but since we mangle the message,
30         # we should do this before it gets to ssoma.
31         # We also kill Mail-{Followup,Reply}-To and Reply-To headers due to
32         # the nature of public-inbox having no real subscribers.
33         foreach my $d (qw(status lines content-length
34                         mail-followup-to mail-reply-to reply-to)) {
35                 $mime->header_set($d);
36         }
37
38         if ($content_type =~ m!\btext/plain\b!i) {
39                 return 1; # yay, nothing to do
40         } elsif ($content_type =~ $MIME_HTML) {
41                 # HTML-only, non-multipart
42                 my $body = $mime->body;
43                 my $ct_parsed = parse_content_type($content_type);
44                 dump_html(\$body, $ct_parsed->{attributes}->{charset});
45                 replace_body($mime, $body);
46                 return 1;
47         } elsif ($content_type =~ m!\bmultipart/!i) {
48                 return strip_multipart($mime, $content_type);
49         } else {
50                 replace_body($mime, "$content_type message scrubbed");
51                 return 0;
52         }
53 }
54
55 sub replace_part {
56         my ($mime, $part, $type) = ($_[0], $_[1], $_[3]);
57         # don't copy $_[2], that's the body (it may be huge)
58
59         # Email::MIME insists on setting Date:, so just set it consistently
60         # to avoid conflicts to avoid git merge conflicts in a split brain
61         # situation.
62         unless (defined $part->header('Date')) {
63                 my $date = $mime->header('Date') ||
64                            'Thu, 01 Jan 1970 00:00:00 +0000';
65                 $part->header_set('Date', $date);
66         }
67
68         $part->charset_set(undef);
69         $part->name_set(undef);
70         $part->filename_set(undef);
71         $part->format_set(undef);
72         $part->encoding_set('8bit');
73         $part->disposition_set(undef);
74         $part->content_type_set($type);
75         $part->body_set($_[2]);
76 }
77
78 # converts one part of a multipart message to text
79 sub html_part_to_text {
80         my ($mime, $part) = @_;
81         my $body = $part->body;
82         my $ct_parsed = parse_content_type($part->content_type);
83         dump_html(\$body, $ct_parsed->{attributes}->{charset});
84         replace_part($mime, $part, $body, 'text/plain');
85 }
86
87 # modifies $_[0] in place
88 sub dump_html {
89         my ($body, $charset) = @_;
90         $charset ||= 'US-ASCII';
91         my @cmd = qw(lynx -stdin -stderr -dump);
92         my $out = "";
93         my $err = "";
94
95         # be careful about remote command injection!
96         if ($charset =~ /\A([A-Za-z0-9\-]+)\z/) {
97                 push @cmd, "-assume_charset=$charset";
98         }
99         if (IPC::Run::run(\@cmd, $body, \$out, \$err)) {
100                 $out =~ s/\r\n/\n/sg;
101                 $$body = $out;
102         } else {
103                 # give them an ugly version:
104                 $$body = "public-inbox HTML conversion failed: $err\n" .
105                          $$body . "\n";
106         }
107 }
108
109 # this is to correct user errors and not expected to cover all corner cases
110 # if users don't want to hit this, they should be sending text/plain messages
111 # unfortunately, too many people send HTML mail and we'll attempt to convert
112 # it to something safer, smaller and harder-to-track.
113 sub strip_multipart {
114         my ($mime, $content_type) = @_;
115
116         my (@html, @keep);
117         my $rejected = 0;
118         my $ok = 1;
119
120         # scan through all parts once
121         $mime->walk_parts(sub {
122                 my ($part) = @_;
123                 return if $part->subparts; # walk_parts already recurses
124
125                 # some extensions are just bad, reject them outright
126                 my $fn = $part->filename;
127                 if (defined($fn) && $fn =~ $BAD_EXT) {
128                         $rejected++;
129                         return;
130                 }
131
132                 my $part_type = $part->content_type || '';
133                 if ($part_type =~ m!\btext/plain\b!i) {
134                         push @keep, $part;
135                 } elsif ($part_type =~ $MIME_HTML) {
136                         push @html, $part;
137                 } elsif ($part_type =~ $MIME_TEXT_ANY) {
138                         # Give other text attachments the benefit of the doubt,
139                         # here?  Could be source code or script the user wants
140                         # help with.
141
142                         push @keep, $part;
143                 } elsif ($part_type eq '' ||
144                          $part_type =~ m!\Aapplication/octet-stream\z!i) {
145                         # unfortunately, some mailers don't set correct types,
146                         # let messages of unknown type through but do not
147                         # change the sender-specified type
148                         if (recheck_type_ok($part)) {
149                                 push @keep, $part;
150                         } else {
151                                 $rejected++;
152                         }
153                 } elsif ($part_type =~ m!\Aapplication/pgp-signature\z!i) {
154                         # PGP signatures are not huge, we may keep them.
155                         # They can only be valid if it's the last element,
156                         # so we keep them iff the message is unmodified:
157                         if ($rejected == 0 && !@html) {
158                                 push @keep, $part;
159                         }
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) && length($cte)) {
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         ((bytes::length($s) < 0x10000) &&
230                 ($s =~ /\A([\P{XPosixPrint}\f\n\r\t]+)\z/))
231 }
232
233 1;