]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Eml.pm
descend into message/(rfc822|news|global) parts
[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 goto &new;
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) = @_;
239         my $p = mp_descend($self, $once // 0) or
240                                         return $cb->([$self, 0, 0], $arg);
241
242         $cb->([$self, 0, 0], $arg) if $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                         $cb->([$sub, $depth, @idx], $arg) if $sub->{-call_cb};
259                 } else { # a leaf node
260                         $cb->([$sub, $depth, @idx], $arg);
261                 }
262         }
263 }
264
265 sub enc_qp {
266         # prevent MIME::QuotedPrint from encoding CR as =0D since it's
267         # against RFCs and breaks MUAs
268         $_[0] =~ s/\r\n/\n/sg;
269         encode_qp($_[0], "\r\n");
270 }
271
272 sub dec_qp {
273         # RFC 2822 requires all lines to end in CRLF, though... :<
274         $_[0] = decode_qp($_[0]);
275         $_[0] =~ s/\n/\r\n/sg;
276         $_[0]
277 }
278
279 sub identity_codec { $_[0] }
280
281 ########### compatibility section for existing Email::MIME uses #########
282
283 sub header_obj {
284         bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
285 }
286
287 sub subparts {
288         my ($self) = @_;
289         my $parts = mp_descend($self, 0) or return ();
290         my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
291         my $bdy = $self->{bdy};
292         if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
293                 $self->{preamble} = $1;
294         }
295         if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
296                 $self->{epilogue} = $1;
297         }
298         @$parts;
299 }
300
301 sub parts_set {
302         my ($self, $parts) = @_;
303
304         # we can't fully support what Email::MIME does,
305         # just what our filter code needs:
306         my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
307 ->parts_set not supported for single-part messages
308 EOF
309         my $crlf = $self->{crlf};
310         my $fin_bnd = "$crlf--$bnd--$crlf";
311         $bnd = "$crlf--$bnd$crlf";
312         ${$self->{bdy}} = join($bnd,
313                                 delete($self->{preamble}) // '',
314                                 map { $_->as_string } @$parts
315                                 ) .
316                                 $fin_bnd .
317                                 (delete($self->{epilogue}) // '');
318         undef;
319 }
320
321 sub body_set {
322         my ($self, $body) = @_;
323         my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
324         if (my $cte = header_raw($self, 'Content-Transfer-Encoding')) {
325                 my $enc = $MIME_ENC{lc($cte)} or croak("can't encode `$cte'");
326                 $$bdy = $enc->($$bdy); # in-place
327         }
328         undef;
329 }
330
331 sub body_str_set {
332         my ($self, $body_str) = @_;
333         my $charset = ct($self)->{attributes}->{charset} or
334                 Carp::confess('body_str was given, but no charset is defined');
335         body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
336 }
337
338 sub content_type { scalar header($_[0], 'Content-Type') }
339
340 # we only support raw header_set
341 sub header_set {
342         my ($self, $pfx, @vals) = @_;
343         my $re = re_memo($pfx);
344         my $hdr = $self->{hdr};
345         return $$hdr =~ s!$re!!g if !@vals;
346         $pfx .= ': ';
347         my $len = 78 - length($pfx);
348         @vals = map {;
349                 # folding differs from Email::Simple::Header,
350                 # we favor tabs for visibility (and space savings :P)
351                 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
352                         local $Text::Wrap::columns = $len;
353                         local $Text::Wrap::huge = 'overflow';
354                         $pfx . wrap('', "\t", $_) . $self->{crlf};
355                 } else {
356                         $pfx . $_ . $self->{crlf};
357                 }
358         } @vals;
359         $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
360         $$hdr .= join('', @vals); # append any leftovers not replaced
361         # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
362         undef; # we don't care for the return value
363 }
364
365 # note: we only call this method on Subject
366 sub header_str_set {
367         my ($self, $name, @vals) = @_;
368         for (@vals) {
369                 next unless /[^\x20-\x7e]/;
370                 utf8::encode($_); # to octets
371                 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
372                 s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
373         }
374         header_set($self, $name, @vals);
375 }
376
377 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
378
379 sub filename {
380         my $dis = header_raw($_[0], 'Content-Disposition');
381         my $attrs = parse_content_disposition($dis)->{attributes};
382         my $fn = $attrs->{filename};
383         $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
384         (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
385 }
386
387 sub xs_addr_str { # helper for ->header / ->header_str
388         for (@_) { # array from header_raw()
389                 next unless /=\?/;
390                 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
391                 for (my $i = 0; $i < @g; $i += 2) {
392                         if (defined($g[$i]) && $g[$i] =~ /=\?/) {
393                                 $g[$i] = mhdr_decode($g[$i]);
394                         }
395                         my $addrs = $g[$i + 1];
396                         for my $eax (@$addrs) {
397                                 for my $m (qw(phrase comment)) {
398                                         my $v = $eax->$m;
399                                         $eax->$m(mhdr_decode($v)) if
400                                                         $v && $v =~ /=\?/;
401                                 }
402                         }
403                 }
404                 $_ = format_email_groups(@g);
405         }
406 }
407
408 eval {
409         require Email::Address::XS;
410         Email::Address::XS->import(qw(parse_email_groups format_email_groups));
411         1;
412 } or do {
413         # fallback to just decoding everything, because parsing
414         # email addresses correctly w/o C/XS is slow
415         %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
416         %DECODE_ADDRESS = ();
417 };
418
419 *header = \&header_str;
420 sub header_str {
421         my ($self, $name) = @_;
422         my @v = header_raw($self, $name);
423         if ($DECODE_ADDRESS{$name}) {
424                 xs_addr_str(@v);
425         } elsif ($DECODE_FULL{$name}) {
426                 for (@v) {
427                         $_ = mhdr_decode($_) if /=\?/;
428                 }
429         }
430         wantarray ? @v : $v[0];
431 }
432
433 sub body_raw { ${$_[0]->{bdy} // \''}; }
434
435 sub body {
436         my $raw = body_raw($_[0]);
437         my $cte = header_raw($_[0], 'Content-Transfer-Encoding') or return $raw;
438         ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) or return $raw; # For S/MIME, etc
439         my $dec = $MIME_DEC{lc($cte)} or return $raw;
440         $dec->($raw);
441 }
442
443 sub body_str {
444         my ($self) = @_;
445         my $ct = ct($self);
446         my $charset = $ct->{attributes}->{charset};
447         if (!$charset) {
448                 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
449                         return body($self);
450                 }
451                 Carp::confess("can't get body as a string for ",
452                         join("\n\t", header_raw($self, 'Content-Type')));
453         }
454         decode($charset, body($self), Encode::FB_CROAK);
455 }
456
457 sub as_string {
458         my ($self) = @_;
459         my $ret = ${ $self->{hdr} };
460         return $ret unless defined($self->{bdy});
461         $ret .= $self->{crlf};
462         $ret .= ${$self->{bdy}};
463 }
464
465 # Unlike Email::MIME::charset_set, this only changes the parsed
466 # representation of charset used for search indexing and HTML display.
467 # This does NOT affect what ->as_string returns.
468 sub charset_set {
469         ct($_[0])->{attributes}->{charset} = $_[1];
470 }
471
472 sub crlf { $_[0]->{crlf} // "\n" }
473
474 sub willneed { re_memo($_) for @_ }
475
476 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
477                 Message-ID X-Alt-Message-ID));
478
479 1;