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