1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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.
9 # Contains ideas and code from Email::Simple and Email::MIME
10 # (Perl Artistic License, GPL-1+)
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.
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
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),
24 # # filled in during ->each_part
25 # ct => hash ref returned by parse_content_type
27 package PublicInbox::Eml;
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
36 my $MIME_Header = find_encoding('MIME-Header');
38 use PublicInbox::EmlContentFoo qw(parse_content_type parse_content_disposition);
39 $PublicInbox::EmlContentFoo::STRICT_PARAMS = 0;
41 our $mime_parts_limit = 1000; # same as SpamAssassin (not in postfix AFAIK)
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
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);
54 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
57 'Content-Description' => 1,
58 'Content-Type' => 1, # not correct, but needed, oh well
60 our %STR_TYPE = (text => 1);
61 our %STR_SUBTYPE = (plain => 1, html => 1);
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
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
78 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
82 sub hdr_truncate ($) {
83 my $len = length($_[0]);
84 substr($_[0], $header_size_limit, $len) = '';
85 my $end = rindex($_[0], "\n");
88 substr($_[0], $end, $len) = '';
89 warn "header of $len bytes truncated to $end bytes\n";
93 header of $len bytes without `\\n' within $header_size_limit ignored
98 # compatible with our uses of Email::MIME
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.
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) {
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__;
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__;
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
141 my $re = re_memo($_[1]);
142 my @v = (${ $_[0]->{hdr} } =~ /$re/g);
144 # for compatibility w/ Email::Simple::Header,
149 wantarray ? @v : $v[0];
152 # pick the first Content-Type header to match Email::MIME behavior.
153 # It's usually the right one based on historical archives.
155 # PublicInbox::EmlContentFoo::content_type:
156 $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
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
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;
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);
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};
179 # "multipart" messages can exist w/o a body
180 my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
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]) = '';
189 $epilogue_missing = 1;
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)
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,
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);
206 if (@parts) { # the usual path if we got this far:
207 undef $bdy; # release memory ASAP if $nr > 0
209 # compatibility with Email::MIME
210 $parts[-1] =~ s/\n\r?\n\z/\n/s if $epilogue_missing;
213 @parts = map { new_sub(undef, \$_) } grep /[^ \t\r\n]/s, @parts;
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
219 # <20060515162817.65F0F1BBAE@citi.umich.edu>
220 unshift(@parts, new_sub(undef, \$pre)) if $pre =~ /:/s;
223 # "multipart", but no boundary found, treat as single part
224 $self->{bdy} //= $bdy;
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
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
238 my ($self, $cb, $arg, $once, $all) = @_;
239 my $p = mp_descend($self, $once // 0) or
240 return $cb->([$self, 0, 1], $arg);
242 $cb->([$self, 0, 0], $arg) if ($all || $self->{-call_cb}); # rare
245 my @s; # our virtual stack
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);
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");
274 # RFC 2822 requires all lines to end in CRLF, though... :<
275 $_[0] = decode_qp($_[0]);
276 $_[0] =~ s/\n/\r\n/sg;
280 sub identity_codec { $_[0] }
282 ########### compatibility section for existing Email::MIME uses #########
285 bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
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;
296 if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
297 $self->{epilogue} = $1;
303 my ($self, $parts) = @_;
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
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
318 (delete($self->{epilogue}) // '');
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
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)));
339 sub content_type { scalar header($_[0], 'Content-Type') }
341 # we only support raw 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;
348 my $len = 78 - length($pfx);
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};
357 $pfx . $_ . $self->{crlf};
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
366 # note: we only call this method on Subject
368 my ($self, $name, @vals) = @_;
370 next unless /[^\x20-\x7e]/;
371 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
374 utf8::encode($x); # to octets
375 '=?UTF-8?B?'.encode_base64($x, '').'?='
378 header_set($self, $name, @vals);
381 sub mhdr_decode ($) {
382 eval { $MIME_Header->decode($_[0], Encode::FB_DEFAULT) } // $_[0];
386 my $dis = header_raw($_[0], 'Content-Disposition');
387 my $attrs = parse_content_disposition($dis)->{attributes};
388 my $fn = $attrs->{filename};
389 $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
390 (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
393 sub xs_addr_str { # helper for ->header / ->header_str
394 for (@_) { # array from header_raw()
396 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
397 for (my $i = 0; $i < @g; $i += 2) {
398 if (defined($g[$i]) && $g[$i] =~ /=\?/) {
399 $g[$i] = mhdr_decode($g[$i]);
401 my $addrs = $g[$i + 1];
402 for my $eax (@$addrs) {
403 for my $m (qw(phrase comment)) {
405 $eax->$m(mhdr_decode($v)) if
410 $_ = format_email_groups(@g);
415 require Email::Address::XS;
416 Email::Address::XS->import(qw(parse_email_groups format_email_groups));
419 # fallback to just decoding everything, because parsing
420 # email addresses correctly w/o C/XS is slow
421 %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
422 %DECODE_ADDRESS = ();
425 *header = \&header_str;
427 my ($self, $name) = @_;
428 my @v = header_raw($self, $name);
429 if ($DECODE_ADDRESS{$name}) {
431 } elsif ($DECODE_FULL{$name}) {
433 $_ = mhdr_decode($_) if /=\?/;
436 wantarray ? @v : $v[0];
439 sub body_raw { ${$_[0]->{bdy} // \''}; }
442 my $raw = body_raw($_[0]);
443 my $cte = header_raw($_[0], 'Content-Transfer-Encoding') or return $raw;
444 ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) or return $raw; # For S/MIME, etc
445 my $dec = $MIME_DEC{lc($cte)} or return $raw;
452 my $charset = $ct->{attributes}->{charset};
454 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
457 Carp::confess("can't get body as a string for ",
458 join("\n\t", header_raw($self, 'Content-Type')));
460 decode($charset, body($self), Encode::FB_CROAK);
465 my $ret = ${ $self->{hdr} };
466 return $ret unless defined($self->{bdy});
467 $ret .= $self->{crlf};
468 $ret .= ${$self->{bdy}};
471 # Unlike Email::MIME::charset_set, this only changes the parsed
472 # representation of charset used for search indexing and HTML display.
473 # This does NOT affect what ->as_string returns.
475 ct($_[0])->{attributes}->{charset} = $_[1];
478 sub crlf { $_[0]->{crlf} // "\n" }
480 sub willneed { re_memo($_) for @_ }
482 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
483 Message-ID X-Alt-Message-ID));