]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Filter.pm
initial commit
[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
19 # this is highly opinionated delivery
20 # returns 0 only if there is nothing to deliver
21 sub run {
22         my ($class, $simple) = @_;
23
24         my $content_type = $simple->header("Content-Type") || "text/plain";
25
26         # kill potentially bad/confusing headers
27         # Note: ssoma already does this, but since we mangle the message,
28         # we should do this before it gets to ssoma.
29         foreach my $d (qw(status lines content-length)) {
30                 $simple->header_set($d);
31         }
32
33         if ($content_type =~ m!\btext/plain\b!i) {
34                 return 1; # yay, nothing to do
35         } elsif ($content_type =~ m!\btext/html\b!i) {
36                 # HTML-only, non-multipart
37                 my $body = $simple->body;
38                 my $ct_parsed = parse_content_type($content_type);
39                 dump_html($body, $ct_parsed->{attributes}->{charset});
40                 replace_body($simple, $body);
41                 return 1;
42         } elsif ($content_type =~ m!\bmultipart/!i) {
43                 return strip_multipart($simple, $content_type);
44         } else {
45                 replace_body($simple, "$content_type message scrubbed");
46                 return 0;
47         }
48 }
49
50 sub replace_part {
51         my ($simple, $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 = $simple->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 ($simple, $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($simple, $part, $body, 'text/plain');
80 }
81
82 # modifies $_[0] in place
83 sub dump_html {
84         my $charset = $_[1] || 'US-ASCII';
85         my $cmd = "lynx -stdin -dump";
86
87         # be careful about remote command injection!
88         if ($charset =~ /\A[A-Za-z0-9\-]+\z/) {
89                 $cmd .= " -assume_charset=$charset";
90         }
91
92         my $pid = open2(my $out, my $in, $cmd);
93         print $in $_[0];
94         close $in;
95         {
96                 local $/;
97                 $_[0] = <$out>;
98         }
99         waitpid($pid, 0);
100 }
101
102 # this is to correct user errors and not expected to cover all corner cases
103 # if users don't want to hit this, they should be sending text/plain messages
104 # unfortunately, too many people send HTML mail and we'll attempt to convert
105 # it to something safer, smaller and harder-to-track.
106 sub strip_multipart {
107         my ($simple, $content_type) = @_;
108         my $mime = Email::MIME->new($simple->as_string);
109
110         my (@html, @keep);
111         my $rejected = 0;
112         my $ok = 1;
113
114         # scan through all parts once
115         $mime->walk_parts(sub {
116                 my ($part) = @_;
117                 return if $part->subparts; # walk_parts already recurses
118
119                 # some extensions are just bad, reject them outright
120                 my $fn = $part->filename;
121                 if (defined($fn) && $fn =~ $BAD_EXT) {
122                         $rejected++;
123                         return;
124                 }
125
126                 my $part_type = $part->content_type;
127                 if ($part_type =~ m!\btext/plain\b!i) {
128                         push @keep, $part;
129                 } elsif ($part_type =~ m!\btext/html\b!i) {
130                         push @html, $part;
131                 } elsif ($part_type =~ m!\btext/[a-z0-9\+\._-]+\b!i) {
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                 } else {
138                         # reject everything else
139                         #
140                         # Yes, we drop GPG/PGP signatures because:
141                         # * hardly anybody bothers to verify signatures
142                         # * we strip/convert HTML parts, which could invalidate
143                         #   the signature
144                         # * they increase the size of messages greatly
145                         #   (especially short ones)
146                         # * they do not compress well
147                         #
148                         # Instead, rely on soft verification measures:
149                         # * content of the message is most important
150                         # * we encourage Cc: all replies, so replies go to
151                         #   the original sender
152                         # * Received, User-Agent, and similar headers
153                         #   (this is also to encourage using self-hosted mail
154                         #   servers (using 100% Free Software, of course :)
155                         #
156                         # Furthermore, identity theft is uncommon in Free/Open
157                         # Source, even in communities where signatures are rare.
158                         $rejected++;
159                 }
160         });
161
162         if ($content_type =~ m!\bmultipart/alternative\b!i) {
163                 if (scalar @keep == 1) {
164                         return collapse($simple, $keep[0]);
165                 }
166         } else { # convert HTML parts to plain text
167                 foreach my $part (@html) {
168                         html_part_to_text($simple, $part);
169                         push @keep, $part;
170                 }
171         }
172
173         if (@keep == 0) {
174                 @keep = (Email::MIME->create(
175                         attributes => {
176                                 content_type => 'text/plain',
177                                 charset => 'US-ASCII',
178                                 encoding => '8bit',
179                         },
180                         body_str => 'all attachments scrubbed by '. __PACKAGE__
181                 ));
182                 $ok = 0;
183         }
184         if (scalar(@html) || $rejected) {
185                 $mime->parts_set(\@keep);
186                 $simple->body_set($mime->body_raw);
187                 mark_changed($simple);
188         } # else: no changes
189
190         return $ok;
191 }
192
193 sub mark_changed {
194         my ($simple) = @_;
195         $simple->header_set("X-Content-Filtered-By", __PACKAGE__ ." $VERSION");
196 }
197
198 sub collapse {
199         my ($simple, $part) = @_;
200         $simple->header_set("Content-Type", $part->content_type);
201         $simple->body_set($part->body_raw);
202         mark_changed($simple);
203         return 1;
204 }
205
206 sub replace_body {
207         my $simple = $_[0];
208         $simple->body_set($_[1]);
209         $simple->header_set("Content-Type", "text/plain");
210         if ($simple->header("Content-Transfer-Encoding")) {
211                 $simple->header_set("Content-Transfer-Encoding", undef);
212         }
213         mark_changed($simple);
214 }
215
216 1;