]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Filter.pm
filter: use file(1) to detect mime type if octet-stream
[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::Open2;
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, $simple) = @_;
25
26         my $content_type = $simple->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                 $simple->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 = $simple->body;
43                 my $ct_parsed = parse_content_type($content_type);
44                 dump_html($body, $ct_parsed->{attributes}->{charset});
45                 replace_body($simple, $body);
46                 return 1;
47         } elsif ($content_type =~ m!\bmultipart/!i) {
48                 return strip_multipart($simple, $content_type);
49         } else {
50                 replace_body($simple, "$content_type message scrubbed");
51                 return 0;
52         }
53 }
54
55 sub replace_part {
56         my ($simple, $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 = $simple->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 ($simple, $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($simple, $part, $body, 'text/plain');
85 }
86
87 # modifies $_[0] in place
88 sub dump_html {
89         my $charset = $_[1] || 'US-ASCII';
90         my $cmd = "lynx -stdin -dump";
91
92         # be careful about remote command injection!
93         if ($charset =~ /\A[A-Za-z0-9\-]+\z/) {
94                 $cmd .= " -assume_charset=$charset";
95         }
96
97         my $pid = open2(my $out, my $in, $cmd);
98         print $in $_[0];
99         close $in;
100         {
101                 local $/;
102                 $_[0] = <$out>;
103         }
104         waitpid($pid, 0);
105 }
106
107 # this is to correct user errors and not expected to cover all corner cases
108 # if users don't want to hit this, they should be sending text/plain messages
109 # unfortunately, too many people send HTML mail and we'll attempt to convert
110 # it to something safer, smaller and harder-to-track.
111 sub strip_multipart {
112         my ($simple, $content_type) = @_;
113         my $mime = Email::MIME->new($simple->as_string);
114
115         my (@html, @keep);
116         my $rejected = 0;
117         my $ok = 1;
118
119         # scan through all parts once
120         $mime->walk_parts(sub {
121                 my ($part) = @_;
122                 return if $part->subparts; # walk_parts already recurses
123
124                 # some extensions are just bad, reject them outright
125                 my $fn = $part->filename;
126                 if (defined($fn) && $fn =~ $BAD_EXT) {
127                         $rejected++;
128                         return;
129                 }
130
131                 my $part_type = $part->content_type;
132                 if ($part_type =~ m!\btext/plain\b!i) {
133                         push @keep, $part;
134                 } elsif ($part_type =~ $MIME_HTML) {
135                         push @html, $part;
136                 } elsif ($part_type =~ $MIME_TEXT_ANY) {
137                         # Give other text attachments the benefit of the doubt,
138                         # here?  Could be source code or script the user wants
139                         # help with.
140
141                         push @keep, $part;
142                 } elsif ($part_type =~ m!\Aapplication/octet-stream\z!i) {
143                         # unfortunately, some mailers don't set correct types,
144                         # let messages of unknown type through but do not
145                         # change the sender-specified type
146                         if (recheck_type_ok($part)) {
147                                 push @keep, $part;
148                         } else {
149                                 $rejected++;
150                         }
151                 } else {
152                         # reject everything else
153                         #
154                         # Yes, we drop GPG/PGP signatures because:
155                         # * hardly anybody bothers to verify signatures
156                         # * we strip/convert HTML parts, which could invalidate
157                         #   the signature
158                         # * they increase the size of messages greatly
159                         #   (especially short ones)
160                         # * they do not compress well
161                         #
162                         # Instead, rely on soft verification measures:
163                         # * content of the message is most important
164                         # * we encourage Cc: all replies, so replies go to
165                         #   the original sender
166                         # * Received, User-Agent, and similar headers
167                         #   (this is also to encourage using self-hosted mail
168                         #   servers (using 100% Free Software, of course :)
169                         #
170                         # Furthermore, identity theft is uncommon in Free/Open
171                         # Source, even in communities where signatures are rare.
172                         $rejected++;
173                 }
174         });
175
176         if ($content_type =~ m!\bmultipart/alternative\b!i) {
177                 if (scalar @keep == 1) {
178                         return collapse($simple, $keep[0]);
179                 }
180         } else { # convert HTML parts to plain text
181                 foreach my $part (@html) {
182                         html_part_to_text($simple, $part);
183                         push @keep, $part;
184                 }
185         }
186
187         if (@keep == 0) {
188                 @keep = (Email::MIME->create(
189                         attributes => {
190                                 content_type => 'text/plain',
191                                 charset => 'US-ASCII',
192                                 encoding => '8bit',
193                         },
194                         body_str => 'all attachments scrubbed by '. __PACKAGE__
195                 ));
196                 $ok = 0;
197         }
198         if (scalar(@html) || $rejected) {
199                 $mime->parts_set(\@keep);
200                 $simple->body_set($mime->body_raw);
201                 mark_changed($simple);
202         } # else: no changes
203
204         return $ok;
205 }
206
207 sub mark_changed {
208         my ($simple) = @_;
209         $simple->header_set("X-Content-Filtered-By", __PACKAGE__ ." $VERSION");
210 }
211
212 sub collapse {
213         my ($simple, $part) = @_;
214         $simple->header_set("Content-Type", $part->content_type);
215         $simple->body_set($part->body_raw);
216         mark_changed($simple);
217         return 1;
218 }
219
220 sub replace_body {
221         my $simple = $_[0];
222         $simple->body_set($_[1]);
223         $simple->header_set("Content-Type", "text/plain");
224         if ($simple->header("Content-Transfer-Encoding")) {
225                 $simple->header_set("Content-Transfer-Encoding", undef);
226         }
227         mark_changed($simple);
228 }
229
230 # run the file(1) command to detect mime type
231 # Not using File::MMagic for now since that requires extra configuration
232 # Note: we do not rewrite the message with the detected mime type
233 sub recheck_type_ok {
234         my ($part) = @_;
235         my $cmd = "file --mime-type -b -";
236         my $pid = open2(my $out, my $in, $cmd);
237         print $in $part->body;
238         close $in;
239         my $type = eval {
240                 local $/;
241                 <$out>;
242         };
243         waitpid($pid, 0);
244         chomp $type;
245
246         (($type =~ $MIME_TEXT_ANY) && ($type !~ $MIME_HTML))
247 }
248
249 1;