]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Eml.pm
571edc5c950c7ccd575e6de91ce1326f446ab788
[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 use MIME::Base64 3.05; # Perl 5.10.0 / 5.9.2
34 use MIME::QuotedPrint 3.05; # ditto
35
36 my $MIME_Header = find_encoding('MIME-Header');
37
38 use PublicInbox::EmlContentFoo qw(parse_content_type parse_content_disposition);
39 $PublicInbox::EmlContentFoo::STRICT_PARAMS = 0;
40
41 our $mime_parts_limit = 1000; # same as SpamAssassin (not in postfix AFAIK)
42
43 # the rest of the limit names are taken from postfix:
44 our $mime_nesting_limit = 20; # seems enough, Perl sucks, here
45 our $mime_boundary_length_limit = 2048; # same as postfix
46 our $header_size_limit = 102400; # same as postfix
47
48 my %MIME_ENC = (qp => \&enc_qp, base64 => \&encode_base64);
49 my %MIME_DEC = (qp => \&dec_qp, base64 => \&decode_base64);
50 $MIME_ENC{quotedprint} = $MIME_ENC{'quoted-printable'} = $MIME_ENC{qp};
51 $MIME_DEC{quotedprint} = $MIME_DEC{'quoted-printable'} = $MIME_DEC{qp};
52 $MIME_ENC{$_} = \&identity_codec for qw(7bit 8bit binary);
53
54 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
55 my %DECODE_FULL = (
56         Subject => 1,
57         'Content-Description' => 1,
58         'Content-Type' => 1, # not correct, but needed, oh well
59 );
60 our %STR_TYPE = (text => 1);
61 our %STR_SUBTYPE = (plain => 1, html => 1);
62
63 # message/* subtypes we descend into
64 our %MESSAGE_DESCEND = (
65         news => 1, # RFC 1849 (obsolete, but archives are forever)
66         rfc822 => 1, # RFC 2046
67         rfc2822 => 1, # gmime handles this (but not rfc5322)
68         global => 1, # RFC 6532
69 );
70
71 my %re_memo;
72 sub re_memo ($) {
73         my ($k) = @_;
74         # Do not normalize $k with lc/uc; instead strive to keep
75         # capitalization in our codebase consistent.
76         $re_memo{$k} ||= qr/^\Q$k\E:[ \t]*([^\n]*\r?\n # 1st line
77                                         # continuation lines:
78                                         (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
79                                         /ismx
80 }
81
82 sub hdr_truncate ($) {
83         my $len = length($_[0]);
84         substr($_[0], $header_size_limit, $len) = '';
85         my $end = rindex($_[0], "\n");
86         if ($end >= 0) {
87                 ++$end;
88                 substr($_[0], $end, $len) = '';
89                 warn "header of $len bytes truncated to $end bytes\n";
90         } else {
91                 $_[0] = '';
92                 warn <<EOF
93 header of $len bytes without `\\n' within $header_size_limit ignored
94 EOF
95         }
96 }
97
98 # compatible with our uses of Email::MIME
99 sub new {
100         my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
101         # substr() can modify the first arg in-place and to avoid
102         # memcpy/memmove on a potentially large scalar.  It does need
103         # to make a copy for $hdr, though.  Idea stolen from Email::Simple.
104
105         # We also prefer index() on common LFLF emails since it's faster
106         # and re scan can bump RSS by length($$ref) on big strings
107         if (index($$ref, "\r\n") < 0 && (my $pos = index($$ref, "\n\n")) >= 0) {
108                 # likely on *nix
109                 my $hdr = substr($$ref, 0, $pos + 2, ''); # sv_chop on $$ref
110                 chop($hdr); # lower SvCUR
111                 hdr_truncate($hdr) if length($hdr) > $header_size_limit;
112                 bless { hdr => \$hdr, crlf => "\n", bdy => $ref }, __PACKAGE__;
113         } elsif ($$ref =~ /\r?\n(\r?\n)/s) {
114                 my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
115                 substr($hdr, -(length($1))) = ''; # lower SvCUR
116                 hdr_truncate($hdr) if length($hdr) > $header_size_limit;
117                 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
118         } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
119                 # body is optional :P
120                 my $hdr = substr($$ref, 0, $header_size_limit + 1);
121                 hdr_truncate($hdr) if length($hdr) > $header_size_limit;
122                 bless { hdr => \$hdr, crlf => $1 }, __PACKAGE__;
123         } else { # nothing useful
124                 my $hdr = $$ref = '';
125                 bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
126         }
127 }
128
129 sub new_sub {
130         my (undef, $ref) = @_;
131         # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
132         $$ref =~ /\A(\r?\n)/s or return new(undef, $ref);
133         my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
134         bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
135 }
136
137 # same output as Email::Simple::Header::header_raw, but we extract
138 # headers on-demand instead of parsing them into a list which
139 # requires O(n) lookups anyways
140 sub header_raw {
141         my $re = re_memo($_[1]);
142         my @v = (${ $_[0]->{hdr} } =~ /$re/g);
143         for (@v) {
144                 # for compatibility w/ Email::Simple::Header,
145                 s/\s+\z//s;
146                 s/\A\s+//s;
147                 s/\r?\n[ \t]*/ /gs;
148         }
149         wantarray ? @v : $v[0];
150 }
151
152 # pick the first Content-Type header to match Email::MIME behavior.
153 # It's usually the right one based on historical archives.
154 sub ct ($) {
155         # PublicInbox::EmlContentFoo::content_type:
156         $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
157 }
158
159 # returns a queue of sub-parts iff it's worth descending into
160 sub mp_descend ($$) {
161         my ($self, $nr) = @_; # or $once for top-level
162         my $ct = ct($self);
163         my $type = lc($ct->{type});
164         if ($type eq 'message' && $MESSAGE_DESCEND{lc($ct->{subtype})}) {
165                 my $nxt = new(undef, body_raw($self));
166                 $self->{-call_cb} = $nxt->{is_submsg} = 1;
167                 return [ $nxt ];
168         }
169         return if $type ne 'multipart';
170         my $bnd = $ct->{attributes}->{boundary} // return; # single-part
171         return if $bnd eq '' || length($bnd) >= $mime_boundary_length_limit;
172         $bnd = quotemeta($bnd);
173
174         # this is a multipart message that didn't get descended into in
175         # public-inbox <= 1.5.0, so ensure we call the user callback for
176         # this part to not break PSGI downloads.
177         $self->{-call_cb} = $self->{is_submsg};
178
179         # "multipart" messages can exist w/o a body
180         my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
181
182         # Cut at the the first epilogue, not subsequent ones.
183         # *sigh* just the regexp match alone seems to bump RSS by
184         # length($$bdy) on a ~30M string:
185         my $epilogue_missing;
186         if ($$bdy =~ /(?:\r?\n)?^--$bnd--[ \t]*\r?$/sm) {
187                 substr($$bdy, $-[0]) = '';
188         } else {
189                 $epilogue_missing = 1;
190         }
191
192         # *Sigh* split() doesn't work in-place and return CoW strings
193         # because Perl wants to "\0"-terminate strings.  So split()
194         # again bumps RSS by length($$bdy)
195
196         # Quiet warning for "Complex regular subexpression recursion limit"
197         # in case we get many empty parts, it's harmless in this case
198         no warnings 'regexp';
199         my ($pre, @parts) = split(/(?:\r?\n)?(?:^--$bnd[ \t]*\r?\n)+/ms,
200                                 $$bdy,
201                                 # + 3 since we don't want the last part
202                                 # processed to include any other excluded
203                                 # parts ($nr starts at 1, and I suck at math)
204                                 $mime_parts_limit + 3 - $nr);
205
206         if (@parts) { # the usual path if we got this far:
207                 undef $bdy; # release memory ASAP if $nr > 0
208
209                 # compatibility with Email::MIME
210                 $parts[-1] =~ s/\n\r?\n\z/\n/s if $epilogue_missing;
211
212                 # ignore empty parts
213                 @parts = map { new_sub(undef, \$_) } grep /[^ \t\r\n]/s, @parts;
214
215                 # Keep "From: someone..." from preamble in old,
216                 # buggy versions of git-send-email, otherwise drop it
217                 # There's also a case where quoted text showed up in the
218                 # preamble
219                 # <20060515162817.65F0F1BBAE@citi.umich.edu>
220                 unshift(@parts, new_sub(undef, \$pre)) if $pre =~ /:/s;
221                 return \@parts;
222         }
223         # "multipart", but no boundary found, treat as single part
224         $self->{bdy} //= $bdy;
225         undef;
226 }
227
228 # $p = [ \@parts, $depth, $idx ]
229 # $idx[0] grows as $depth grows, $idx[1] == $p->[-1] == current part
230 # (callers need to be updated)
231 # \@parts is a queue which empties when we're done with a parent part
232
233 # same usage as PublicInbox::MsgIter::msg_iter
234 # $cb - user-supplied callback sub
235 # $arg - user-supplied arg (think pthread_create)
236 # $once - unref body scalar during iteration
237 sub each_part {
238         my ($self, $cb, $arg, $once, $all) = @_;
239         my $p = mp_descend($self, $once // 0) or
240                                         return $cb->([$self, 0, 1], $arg);
241
242         $cb->([$self, 0, 0], $arg) if ($all || $self->{-call_cb}); # rare
243
244         $p = [ $p, 0 ];
245         my @s; # our virtual stack
246         my $nr = 0;
247         while ((scalar(@{$p->[0]}) || ($p = pop @s)) &&
248                         ++$nr <= $mime_parts_limit) {
249                 ++$p->[-1]; # bump index
250                 my (undef, @idx) = @$p;
251                 @idx = (join('.', @idx));
252                 my $depth = ($idx[0] =~ tr/././) + 1;
253                 my $sub = shift @{$p->[0]};
254                 if ($depth < $mime_nesting_limit &&
255                                 (my $nxt = mp_descend($sub, $nr))) {
256                         push(@s, $p) if scalar @{$p->[0]};
257                         $p = [ $nxt, @idx, 0 ];
258                         ($all || $sub->{-call_cb}) and
259                                 $cb->([$sub, $depth, @idx], $arg);
260                 } else { # a leaf node
261                         $cb->([$sub, $depth, @idx], $arg);
262                 }
263         }
264 }
265
266 sub enc_qp {
267         # prevent MIME::QuotedPrint from encoding CR as =0D since it's
268         # against RFCs and breaks MUAs
269         $_[0] =~ s/\r\n/\n/sg;
270         encode_qp($_[0], "\r\n");
271 }
272
273 sub dec_qp {
274         # RFC 2822 requires all lines to end in CRLF, though... :<
275         $_[0] = decode_qp($_[0]);
276         $_[0] =~ s/\n/\r\n/sg;
277         $_[0]
278 }
279
280 sub identity_codec { $_[0] }
281
282 ########### compatibility section for existing Email::MIME uses #########
283
284 sub header_obj {
285         bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
286 }
287
288 sub subparts {
289         my ($self) = @_;
290         my $parts = mp_descend($self, 0) or return ();
291         my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
292         my $bdy = $self->{bdy};
293         if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
294                 $self->{preamble} = $1;
295         }
296         if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
297                 $self->{epilogue} = $1;
298         }
299         @$parts;
300 }
301
302 sub parts_set {
303         my ($self, $parts) = @_;
304
305         # we can't fully support what Email::MIME does,
306         # just what our filter code needs:
307         my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
308 ->parts_set not supported for single-part messages
309 EOF
310         my $crlf = $self->{crlf};
311         my $fin_bnd = "$crlf--$bnd--$crlf";
312         $bnd = "$crlf--$bnd$crlf";
313         ${$self->{bdy}} = join($bnd,
314                                 delete($self->{preamble}) // '',
315                                 map { $_->as_string } @$parts
316                                 ) .
317                                 $fin_bnd .
318                                 (delete($self->{epilogue}) // '');
319         undef;
320 }
321
322 sub body_set {
323         my ($self, $body) = @_;
324         my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
325         if (my $cte = header_raw($self, 'Content-Transfer-Encoding')) {
326                 my $enc = $MIME_ENC{lc($cte)} or croak("can't encode `$cte'");
327                 $$bdy = $enc->($$bdy); # in-place
328         }
329         undef;
330 }
331
332 sub body_str_set {
333         my ($self, $body_str) = @_;
334         my $charset = ct($self)->{attributes}->{charset} or
335                 Carp::confess('body_str was given, but no charset is defined');
336         body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
337 }
338
339 sub content_type { scalar header($_[0], 'Content-Type') }
340
341 # we only support raw header_set
342 sub header_set {
343         my ($self, $pfx, @vals) = @_;
344         my $re = re_memo($pfx);
345         my $hdr = $self->{hdr};
346         return $$hdr =~ s!$re!!g if !@vals;
347         $pfx .= ': ';
348         my $len = 78 - length($pfx);
349         @vals = map {;
350                 # folding differs from Email::Simple::Header,
351                 # we favor tabs for visibility (and space savings :P)
352                 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
353                         local $Text::Wrap::columns = $len;
354                         local $Text::Wrap::huge = 'overflow';
355                         $pfx . wrap('', "\t", $_) . $self->{crlf};
356                 } else {
357                         $pfx . $_ . $self->{crlf};
358                 }
359         } @vals;
360         $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
361         $$hdr .= join('', @vals); # append any leftovers not replaced
362         # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
363         undef; # we don't care for the return value
364 }
365
366 # note: we only call this method on Subject
367 sub header_str_set {
368         my ($self, $name, @vals) = @_;
369         for (@vals) {
370                 next unless /[^\x20-\x7e]/;
371                 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
372                 s/(.{1,39})/
373                         my $x = $1;
374                         utf8::encode($x); # to octets
375                         '=?UTF-8?B?'.encode_base64($x, '').'?='
376                 /xges;
377         }
378         header_set($self, $name, @vals);
379 }
380
381 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
382
383 sub filename {
384         my $dis = header_raw($_[0], 'Content-Disposition');
385         my $attrs = parse_content_disposition($dis)->{attributes};
386         my $fn = $attrs->{filename};
387         $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
388         (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
389 }
390
391 sub xs_addr_str { # helper for ->header / ->header_str
392         for (@_) { # array from header_raw()
393                 next unless /=\?/;
394                 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
395                 for (my $i = 0; $i < @g; $i += 2) {
396                         if (defined($g[$i]) && $g[$i] =~ /=\?/) {
397                                 $g[$i] = mhdr_decode($g[$i]);
398                         }
399                         my $addrs = $g[$i + 1];
400                         for my $eax (@$addrs) {
401                                 for my $m (qw(phrase comment)) {
402                                         my $v = $eax->$m;
403                                         $eax->$m(mhdr_decode($v)) if
404                                                         $v && $v =~ /=\?/;
405                                 }
406                         }
407                 }
408                 $_ = format_email_groups(@g);
409         }
410 }
411
412 eval {
413         require Email::Address::XS;
414         Email::Address::XS->import(qw(parse_email_groups format_email_groups));
415         1;
416 } or do {
417         # fallback to just decoding everything, because parsing
418         # email addresses correctly w/o C/XS is slow
419         %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
420         %DECODE_ADDRESS = ();
421 };
422
423 *header = \&header_str;
424 sub header_str {
425         my ($self, $name) = @_;
426         my @v = header_raw($self, $name);
427         if ($DECODE_ADDRESS{$name}) {
428                 xs_addr_str(@v);
429         } elsif ($DECODE_FULL{$name}) {
430                 for (@v) {
431                         $_ = mhdr_decode($_) if /=\?/;
432                 }
433         }
434         wantarray ? @v : $v[0];
435 }
436
437 sub body_raw { ${$_[0]->{bdy} // \''}; }
438
439 sub body {
440         my $raw = body_raw($_[0]);
441         my $cte = header_raw($_[0], 'Content-Transfer-Encoding') or return $raw;
442         ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) or return $raw; # For S/MIME, etc
443         my $dec = $MIME_DEC{lc($cte)} or return $raw;
444         $dec->($raw);
445 }
446
447 sub body_str {
448         my ($self) = @_;
449         my $ct = ct($self);
450         my $charset = $ct->{attributes}->{charset};
451         if (!$charset) {
452                 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
453                         return body($self);
454                 }
455                 Carp::confess("can't get body as a string for ",
456                         join("\n\t", header_raw($self, 'Content-Type')));
457         }
458         decode($charset, body($self), Encode::FB_CROAK);
459 }
460
461 sub as_string {
462         my ($self) = @_;
463         my $ret = ${ $self->{hdr} };
464         return $ret unless defined($self->{bdy});
465         $ret .= $self->{crlf};
466         $ret .= ${$self->{bdy}};
467 }
468
469 # Unlike Email::MIME::charset_set, this only changes the parsed
470 # representation of charset used for search indexing and HTML display.
471 # This does NOT affect what ->as_string returns.
472 sub charset_set {
473         ct($_[0])->{attributes}->{charset} = $_[1];
474 }
475
476 sub crlf { $_[0]->{crlf} // "\n" }
477
478 sub willneed { re_memo($_) for @_ }
479
480 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
481                 Message-ID X-Alt-Message-ID));
482
483 1;