]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Eml.pm
EmlContentFoo: Email::MIME::ContentType replacement
[public-inbox.git] / lib / PublicInbox / Eml.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 #
4 # Lazy MIME parser, it still slurps the full message but keeps short
5 # lifetimes.  Unlike Email::MIME, it doesn't pre-split multipart
6 # messages or do any up-front parsing of headers besides splitting
7 # the header string from the body.
8 #
9 # Contains ideas and code from Email::Simple and Email::MIME
10 # (Perl Artistic License, GPL-1+)
11 #
12 # This aims to replace Email::MIME for our purposes, similar API
13 # but internal field names are differ if they're not 100%-compatible.
14 #
15 # Includes some proposed fixes for Email::MIME:
16 # - header-less sub parts - https://github.com/rjbs/Email-MIME/issues/14
17 # - "0" as boundary - https://github.com/rjbs/Email-MIME/issues/63
18 #
19 # $self = {
20 #       bdy => scalar ref for body (may be undef),
21 #       hdr => scalar ref for header,
22 #       crlf => "\n" or "\r\n" (scalar, not a ref),
23 #
24 #       # filled in during ->each_part
25 #       ct => hash ref returned by parse_content_type
26 # }
27 package PublicInbox::Eml;
28 use strict;
29 use v5.10.1;
30 use Carp qw(croak);
31 use Encode qw(find_encoding decode encode); # stdlib
32 use Text::Wrap qw(wrap); # stdlib, we need Perl 5.6+ for $huge
33
34 my $MIME_Header = find_encoding('MIME-Header');
35
36 use PublicInbox::EmlContentFoo qw(parse_content_type parse_content_disposition);
37 use Email::MIME::Encodings;
38 $PublicInbox::EmlContentFoo::STRICT_PARAMS = 0;
39
40 our $MAXPARTS = 1000; # same as SpamAssassin
41 our $MAXDEPTH = 20; # seems enough, Perl sucks, here
42 our $MAXBOUNDLEN = 2048; # same as postfix
43
44 my $NO_ENCODE_RE = qr/\A(?:7bit|8bit|binary)[ \t]*(?:;|$)?/i;
45 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
46 my %DECODE_FULL = (
47         Subject => 1,
48         'Content-Description' => 1,
49         'Content-Type' => 1, # not correct, but needed, oh well
50 );
51 our %STR_TYPE = (text => 1);
52 our %STR_SUBTYPE = (plain => 1, html => 1);
53
54 my %re_memo;
55 sub re_memo ($) {
56         my ($k) = @_;
57         # Do not normalize $k with lc/uc; instead strive to keep
58         # capitalization in our codebase consistent.
59         $re_memo{$k} ||= qr/^\Q$k\E:[ \t]*([^\n]*\r?\n # 1st line
60                                         # continuation lines:
61                                         (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
62                                         /ismx
63 }
64
65 # compatible with our uses of Email::MIME
66 sub new {
67         my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
68         if ($$ref =~ /(?:\r?\n(\r?\n))/gs) { # likely
69                 # This can modify $$ref in-place and to avoid memcpy/memmove
70                 # on a potentially large $$ref.  It does need to make a
71                 # copy for $hdr, though.  Idea stolen from Email::Simple
72                 my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
73                 substr($hdr, -(length($1))) = ''; # lower SvCUR
74                 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
75         } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
76                 # body is optional :P
77                 bless { hdr => \($$ref), crlf => $1 }, __PACKAGE__;
78         } else { # nothing useful
79                 my $hdr = $$ref = '';
80                 bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
81         }
82 }
83
84 sub new_sub {
85         my (undef, $ref) = @_;
86         # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
87         $$ref =~ /\A(?:(\r?\n))/gs or goto &new;
88         my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
89         bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
90 }
91
92 # same output as Email::Simple::Header::header_raw, but we extract
93 # headers on-demand instead of parsing them into a list which
94 # requires O(n) lookups anyways
95 sub header_raw {
96         my $re = re_memo($_[1]);
97         my @v = (${ $_[0]->{hdr} } =~ /$re/g);
98         for (@v) {
99                 # for compatibility w/ Email::Simple::Header,
100                 s/\s+\z//s;
101                 s/\A\s+//s;
102                 s/\r?\n[ \t]*/ /gs;
103         }
104         wantarray ? @v : $v[0];
105 }
106
107 # pick the first Content-Type header to match Email::MIME behavior.
108 # It's usually the right one based on historical archives.
109 sub ct ($) {
110         # PublicInbox::EmlContentFoo::content_type:
111         $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
112 }
113
114 sub body_decode ($$) {
115         my $cte = header_raw($_[0], 'Content-Transfer-Encoding');
116         ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) if $cte; # For S/MIME, etc
117         (!$cte || $cte =~ $NO_ENCODE_RE) ?
118                 $_[1] : Email::MIME::Encodings::decode($cte, $_[1], '7bit');
119 }
120
121 # returns a queue of sub-parts iff it's worth descending into
122 # TODO: descend into message/rfc822 parts (Email::MIME didn't)
123 sub mp_descend ($$) {
124         my ($self, $nr) = @_; # or $once for top-level
125         my $bnd = ct($self)->{attributes}->{boundary} // return; # single-part
126         return if $bnd eq '' || length($bnd) >= $MAXBOUNDLEN;
127         $bnd = quotemeta($bnd);
128
129         # "multipart" messages can exist w/o a body
130         my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
131
132         # Cut at the the first epilogue, not subsequent ones.
133         # *sigh* just the regexp match alone seems to bump RSS by
134         # length($$bdy) on a ~30M string:
135         $$bdy =~ /((?:\r?\n)?^--$bnd--[ \t]*\r?$)/gsm and
136                 substr($$bdy, pos($$bdy) - length($1)) = '';
137
138         # *Sigh* split() doesn't work in-place and return CoW strings
139         # because Perl wants to "\0"-terminate strings.  So split()
140         # again bumps RSS by length($$bdy)
141
142         # Quiet warning for "Complex regular subexpression recursion limit"
143         # in case we get many empty parts, it's harmless in this case
144         no warnings 'regexp';
145         my ($pre, @parts) = split(/(?:\r?\n)?(?:^--$bnd[ \t]*\r?\n)+/ms,
146                                 $$bdy,
147                                 # + 3 since we don't want the last part
148                                 # processed to include any other excluded
149                                 # parts ($nr starts at 1, and I suck at math)
150                                 $MAXPARTS + 3 - $nr);
151
152         if (@parts) { # the usual path if we got this far:
153                 undef $bdy; # release memory ASAP if $nr > 0
154                 @parts = grep /[^ \t\r\n]/s, @parts; # ignore empty parts
155
156                 # Keep "From: someone..." from preamble in old,
157                 # buggy versions of git-send-email, otherwise drop it
158                 # There's also a case where quoted text showed up in the
159                 # preamble
160                 # <20060515162817.65F0F1BBAE@citi.umich.edu>
161                 unshift(@parts, $pre) if $pre =~ /:/s;
162                 return \@parts;
163         }
164         # "multipart", but no boundary found, treat as single part
165         $self->{bdy} //= $bdy;
166         undef;
167 }
168
169 # $p = [ \@parts, $depth, $idx ]
170 # $idx[0] grows as $depth grows, $idx[1] == $p->[-1] == current part
171 # (callers need to be updated)
172 # \@parts is a queue which empties when we're done with a parent part
173
174 # same usage as PublicInbox::MsgIter::msg_iter
175 # $cb - user-supplied callback sub
176 # $arg - user-supplied arg (think pthread_create)
177 # $once - unref body scalar during iteration
178 sub each_part {
179         my ($self, $cb, $arg, $once) = @_;
180         my $p = mp_descend($self, $once // 0) or
181                                         return $cb->([$self, 0, 0], $arg);
182         $p = [ $p, 0 ];
183         my @s; # our virtual stack
184         my $nr = 0;
185         while ((scalar(@{$p->[0]}) || ($p = pop @s)) && ++$nr <= $MAXPARTS) {
186                 ++$p->[-1]; # bump index
187                 my (undef, @idx) = @$p;
188                 @idx = (join('.', @idx));
189                 my $depth = ($idx[0] =~ tr/././) + 1;
190                 my $sub = new_sub(undef, \(shift @{$p->[0]}));
191                 if ($depth < $MAXDEPTH && (my $nxt = mp_descend($sub, $nr))) {
192                         push(@s, $p) if scalar @{$p->[0]};
193                         $p = [ $nxt, @idx, 0 ];
194                 } else { # a leaf node
195                         $cb->([$sub, $depth, @idx], $arg);
196                 }
197         }
198 }
199
200 ########### compatibility section for existing Email::MIME uses #########
201
202 sub header_obj {
203         bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
204 }
205
206 sub subparts {
207         my ($self) = @_;
208         my $parts = mp_descend($self, 0) or return ();
209         my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
210         my $bdy = $self->{bdy};
211         if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
212                 $self->{preamble} = $1;
213         }
214         if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
215                 $self->{epilogue} = $1;
216         }
217         map { new_sub(undef, \$_) } @$parts;
218 }
219
220 sub parts_set {
221         my ($self, $parts) = @_;
222
223         # we can't fully support what Email::MIME does,
224         # just what our filter code needs:
225         my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
226 ->parts_set not supported for single-part messages
227 EOF
228         my $crlf = $self->{crlf};
229         my $fin_bnd = "$crlf--$bnd--$crlf";
230         $bnd = "$crlf--$bnd$crlf";
231         ${$self->{bdy}} = join($bnd,
232                                 delete($self->{preamble}) // '',
233                                 map { $_->as_string } @$parts
234                                 ) .
235                                 $fin_bnd .
236                                 (delete($self->{epilogue}) // '');
237         undef;
238 }
239
240 sub body_set {
241         my ($self, $body) = @_;
242         my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
243         my $cte = header_raw($self, 'Content-Transfer-Encoding');
244         if ($cte && $cte !~ $NO_ENCODE_RE) {
245                 $$bdy = Email::MIME::Encodings::encode($cte, $$bdy)
246         }
247         undef;
248 }
249
250 sub body_str_set {
251         my ($self, $body_str) = @_;
252         my $charset = ct($self)->{attributes}->{charset} or
253                 Carp::confess('body_str was given, but no charset is defined');
254         body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
255 }
256
257 sub content_type { scalar header($_[0], 'Content-Type') }
258
259 # we only support raw header_set
260 sub header_set {
261         my ($self, $pfx, @vals) = @_;
262         my $re = re_memo($pfx);
263         my $hdr = $self->{hdr};
264         return $$hdr =~ s!$re!!g if !@vals;
265         $pfx .= ': ';
266         my $len = 78 - length($pfx);
267         @vals = map {;
268                 # folding differs from Email::Simple::Header,
269                 # we favor tabs for visibility (and space savings :P)
270                 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
271                         local $Text::Wrap::columns = $len;
272                         local $Text::Wrap::huge = 'overflow';
273                         $pfx . wrap('', "\t", $_) . $self->{crlf};
274                 } else {
275                         $pfx . $_ . $self->{crlf};
276                 }
277         } @vals;
278         $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
279         $$hdr .= join('', @vals); # append any leftovers not replaced
280         # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
281         undef; # we don't care for the return value
282 }
283
284 # note: we only call this method on Subject
285 sub header_str_set {
286         my ($self, $name, @vals) = @_;
287         for (@vals) {
288                 next unless /[^\x20-\x7e]/;
289                 utf8::encode($_); # to octets
290                 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
291                 s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
292         }
293         header_set($self, $name, @vals);
294 }
295
296 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
297
298 sub filename {
299         my $dis = header_raw($_[0], 'Content-Disposition');
300         my $attrs = parse_content_disposition($dis)->{attributes};
301         my $fn = $attrs->{filename};
302         $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
303         (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
304 }
305
306 sub xs_addr_str { # helper for ->header / ->header_str
307         for (@_) { # array from header_raw()
308                 next unless /=\?/;
309                 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
310                 for (my $i = 0; $i < @g; $i += 2) {
311                         if (defined($g[$i]) && $g[$i] =~ /=\?/) {
312                                 $g[$i] = mhdr_decode($g[$i]);
313                         }
314                         my $addrs = $g[$i + 1];
315                         for my $eax (@$addrs) {
316                                 for my $m (qw(phrase comment)) {
317                                         my $v = $eax->$m;
318                                         $eax->$m(mhdr_decode($v)) if
319                                                         $v && $v =~ /=\?/;
320                                 }
321                         }
322                 }
323                 $_ = format_email_groups(@g);
324         }
325 }
326
327 eval {
328         require Email::Address::XS;
329         Email::Address::XS->import(qw(parse_email_groups format_email_groups));
330         1;
331 } or do {
332         # fallback to just decoding everything, because parsing
333         # email addresses correctly w/o C/XS is slow
334         %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
335         %DECODE_ADDRESS = ();
336 };
337
338 *header = \&header_str;
339 sub header_str {
340         my ($self, $name) = @_;
341         my @v = header_raw($self, $name);
342         if ($DECODE_ADDRESS{$name}) {
343                 xs_addr_str(@v);
344         } elsif ($DECODE_FULL{$name}) {
345                 for (@v) {
346                         $_ = mhdr_decode($_) if /=\?/;
347                 }
348         }
349         wantarray ? @v : $v[0];
350 }
351
352 sub body_raw { ${$_[0]->{bdy} // \''}; }
353
354 sub body { body_decode($_[0], body_raw($_[0])) }
355
356 sub body_str {
357         my ($self) = @_;
358         my $ct = ct($self);
359         my $charset = $ct->{attributes}->{charset};
360         if (!$charset) {
361                 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
362                         return body($self);
363                 }
364                 Carp::confess("can't get body as a string for ",
365                         join("\n\t", header_raw($self, 'Content-Type')));
366         }
367         decode($charset, body($self), Encode::FB_CROAK);
368 }
369
370 sub as_string {
371         my ($self) = @_;
372         my $ret = ${ $self->{hdr} };
373         return $ret unless defined($self->{bdy});
374         $ret .= $self->{crlf};
375         $ret .= ${$self->{bdy}};
376 }
377
378 # Unlike Email::MIME::charset_set, this only changes the parsed
379 # representation of charset used for search indexing and HTML display.
380 # This does NOT affect what ->as_string returns.
381 sub charset_set {
382         ct($_[0])->{attributes}->{charset} = $_[1];
383 }
384
385 sub crlf { $_[0]->{crlf} // "\n" }
386
387 sub willneed { re_memo($_) for @_ }
388
389 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
390                 Message-ID X-Alt-Message-ID));
391
392 1;