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
34 my $MIME_Header = find_encoding('MIME-Header');
36 # TODO remove these dependencies
37 use Email::MIME::ContentType;
38 use Email::MIME::Encodings;
39 $Email::MIME::ContentType::STRICT_PARAMS = 0;
41 our $MAXPARTS = 1000; # same as SpamAssassin
42 our $MAXDEPTH = 20; # seems enough, Perl sucks, here
43 our $MAXBOUNDLEN = 2048; # same as postfix
45 my $NO_ENCODE_RE = qr/\A(?:7bit|8bit|binary)[ \t]*(?:;|$)?/i;
46 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
49 'Content-Description' => 1,
50 'Content-Type' => 1, # not correct, but needed, oh well
52 our %STR_TYPE = (text => 1);
53 our %STR_SUBTYPE = (plain => 1, html => 1);
58 # Do not normalize $k with lc/uc; instead strive to keep
59 # capitalization in our codebase consistent.
60 $re_memo{$k} ||= qr/^\Q$k\E:[ \t]*([^\n]*\r?\n # 1st line
62 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
66 # compatible with our uses of Email::MIME
68 my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
69 if ($$ref =~ /(?:\r?\n(\r?\n))/gs) { # likely
70 # This can modify $$ref in-place and to avoid memcpy/memmove
71 # on a potentially large $$ref. It does need to make a
72 # copy for $hdr, though. Idea stolen from Email::Simple
73 my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
74 substr($hdr, -(length($1))) = ''; # lower SvCUR
75 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
76 } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
78 bless { hdr => \($$ref), crlf => $1 }, __PACKAGE__;
79 } else { # nothing useful
81 bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
86 my (undef, $ref) = @_;
87 # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
88 $$ref =~ /\A(?:(\r?\n))/gs or goto &new;
89 my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
90 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
93 # same output as Email::Simple::Header::header_raw, but we extract
94 # headers on-demand instead of parsing them into a list which
95 # requires O(n) lookups anyways
97 my $re = re_memo($_[1]);
98 my @v = (${ $_[0]->{hdr} } =~ /$re/g);
100 # for compatibility w/ Email::Simple::Header,
105 wantarray ? @v : $v[0];
108 # pick the first Content-Type header to match Email::MIME behavior.
109 # It's usually the right one based on historical archives.
111 # Email::MIME::ContentType::content_type:
112 $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
115 sub body_decode ($$) {
116 my $cte = header_raw($_[0], 'Content-Transfer-Encoding');
117 ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) if $cte; # For S/MIME, etc
118 (!$cte || $cte =~ $NO_ENCODE_RE) ?
119 $_[1] : Email::MIME::Encodings::decode($cte, $_[1], '7bit');
122 # returns a queue of sub-parts iff it's worth descending into
123 # TODO: descend into message/rfc822 parts (Email::MIME didn't)
124 sub mp_descend ($$) {
125 my ($self, $nr) = @_; # or $once for top-level
126 my $bnd = ct($self)->{attributes}->{boundary} // return; # single-part
127 return if $bnd eq '' || length($bnd) >= $MAXBOUNDLEN;
128 $bnd = quotemeta($bnd);
130 # "multipart" messages can exist w/o a body
131 my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
133 # Cut at the the first epilogue, not subsequent ones.
134 # *sigh* just the regexp match alone seems to bump RSS by
135 # length($$bdy) on a ~30M string:
136 $$bdy =~ /((?:\r?\n)?^--$bnd--[ \t]*\r?$)/gsm and
137 substr($$bdy, pos($$bdy) - length($1)) = '';
139 # *Sigh* split() doesn't work in-place and return CoW strings
140 # because Perl wants to "\0"-terminate strings. So split()
141 # again bumps RSS by length($$bdy)
143 # Quiet warning for "Complex regular subexpression recursion limit"
144 # in case we get many empty parts, it's harmless in this case
145 no warnings 'regexp';
146 my ($pre, @parts) = split(/(?:\r?\n)?(?:^--$bnd[ \t]*\r?\n)+/ms,
148 # + 3 since we don't want the last part
149 # processed to include any other excluded
150 # parts ($nr starts at 1, and I suck at math)
151 $MAXPARTS + 3 - $nr);
153 if (@parts) { # the usual path if we got this far:
154 undef $bdy; # release memory ASAP if $nr > 0
155 @parts = grep /[^ \t\r\n]/s, @parts; # ignore empty parts
157 # Keep "From: someone..." from preamble in old,
158 # buggy versions of git-send-email, otherwise drop it
159 # There's also a case where quoted text showed up in the
161 # <20060515162817.65F0F1BBAE@citi.umich.edu>
162 unshift(@parts, $pre) if $pre =~ /:/s;
165 # "multipart", but no boundary found, treat as single part
166 $self->{bdy} //= $bdy;
170 # $p = [ \@parts, $depth, $idx ]
171 # $idx[0] grows as $depth grows, $idx[1] == $p->[-1] == current part
172 # (callers need to be updated)
173 # \@parts is a queue which empties when we're done with a parent part
175 # same usage as PublicInbox::MsgIter::msg_iter
176 # $cb - user-supplied callback sub
177 # $arg - user-supplied arg (think pthread_create)
178 # $once - unref body scalar during iteration
180 my ($self, $cb, $arg, $once) = @_;
181 my $p = mp_descend($self, $once // 0) or
182 return $cb->([$self, 0, 0], $arg);
184 my @s; # our virtual stack
186 while ((scalar(@{$p->[0]}) || ($p = pop @s)) && ++$nr <= $MAXPARTS) {
187 ++$p->[-1]; # bump index
188 my (undef, @idx) = @$p;
189 @idx = (join('.', @idx));
190 my $depth = ($idx[0] =~ tr/././) + 1;
191 my $sub = new_sub(undef, \(shift @{$p->[0]}));
192 if ($depth < $MAXDEPTH && (my $nxt = mp_descend($sub, $nr))) {
193 push(@s, $p) if scalar @{$p->[0]};
194 $p = [ $nxt, @idx, 0 ];
195 } else { # a leaf node
196 $cb->([$sub, $depth, @idx], $arg);
201 ########### compatibility section for existing Email::MIME uses #########
204 bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
209 my $parts = mp_descend($self, 0) or return ();
210 my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
211 my $bdy = $self->{bdy};
212 if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
213 $self->{preamble} = $1;
215 if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
216 $self->{epilogue} = $1;
218 map { new_sub(undef, \$_) } @$parts;
222 my ($self, $parts) = @_;
224 # we can't fully support what Email::MIME does,
225 # just what our filter code needs:
226 my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
227 ->parts_set not supported for single-part messages
229 my $crlf = $self->{crlf};
230 my $fin_bnd = "$crlf--$bnd--$crlf";
231 $bnd = "$crlf--$bnd$crlf";
232 ${$self->{bdy}} = join($bnd,
233 delete($self->{preamble}) // '',
234 map { $_->as_string } @$parts
237 (delete($self->{epilogue}) // '');
242 my ($self, $body) = @_;
243 my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
244 my $cte = header_raw($self, 'Content-Transfer-Encoding');
245 if ($cte && $cte !~ $NO_ENCODE_RE) {
246 $$bdy = Email::MIME::Encodings::encode($cte, $$bdy)
252 my ($self, $body_str) = @_;
253 my $charset = ct($self)->{attributes}->{charset} or
254 Carp::confess('body_str was given, but no charset is defined');
255 body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
258 sub content_type { scalar header($_[0], 'Content-Type') }
260 # we only support raw header_set
262 my ($self, $pfx, @vals) = @_;
263 my $re = re_memo($pfx);
264 my $hdr = $self->{hdr};
265 return $$hdr =~ s!$re!!g if !@vals;
267 my $len = 78 - length($pfx);
269 # folding differs from Email::Simple::Header,
270 # we favor tabs for visibility (and space savings :P)
271 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
272 local $Text::Wrap::columns = $len;
273 local $Text::Wrap::huge = 'overflow';
274 $pfx . wrap('', "\t", $_) . $self->{crlf};
276 $pfx . $_ . $self->{crlf};
279 $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
280 $$hdr .= join('', @vals); # append any leftovers not replaced
281 # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
282 undef; # we don't care for the return value
285 # note: we only call this method on Subject
287 my ($self, $name, @vals) = @_;
289 next unless /[^\x20-\x7e]/;
290 utf8::encode($_); # to octets
291 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
292 s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
294 header_set($self, $name, @vals);
297 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
300 my $dis = header_raw($_[0], 'Content-Disposition');
301 my $attrs = parse_content_disposition($dis)->{attributes};
302 my $fn = $attrs->{filename};
303 $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
304 (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
307 sub xs_addr_str { # helper for ->header / ->header_str
308 for (@_) { # array from header_raw()
310 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
311 for (my $i = 0; $i < @g; $i += 2) {
312 if (defined($g[$i]) && $g[$i] =~ /=\?/) {
313 $g[$i] = mhdr_decode($g[$i]);
315 my $addrs = $g[$i + 1];
316 for my $eax (@$addrs) {
317 for my $m (qw(phrase comment)) {
319 $eax->$m(mhdr_decode($v)) if
324 $_ = format_email_groups(@g);
329 require Email::Address::XS;
330 Email::Address::XS->import(qw(parse_email_groups format_email_groups));
333 # fallback to just decoding everything, because parsing
334 # email addresses correctly w/o C/XS is slow
335 %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
336 %DECODE_ADDRESS = ();
339 *header = \&header_str;
341 my ($self, $name) = @_;
342 my @v = header_raw($self, $name);
343 if ($DECODE_ADDRESS{$name}) {
345 } elsif ($DECODE_FULL{$name}) {
347 $_ = mhdr_decode($_) if /=\?/;
350 wantarray ? @v : $v[0];
353 sub body_raw { ${$_[0]->{bdy} // \''}; }
355 sub body { body_decode($_[0], body_raw($_[0])) }
360 my $charset = $ct->{attributes}->{charset};
362 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
365 Carp::confess("can't get body as a string for ",
366 join("\n\t", header_raw($self, 'Content-Type')));
368 decode($charset, body($self), Encode::FB_CROAK);
373 my $ret = ${ $self->{hdr} };
374 return $ret unless defined($self->{bdy});
375 $ret .= $self->{crlf};
376 $ret .= ${$self->{bdy}};
379 # Unlike Email::MIME::charset_set, this only changes the parsed
380 # representation of charset used for search indexing and HTML display.
381 # This does NOT affect what ->as_string returns.
383 ct($_[0])->{attributes}->{charset} = $_[1];
386 sub crlf { $_[0]->{crlf} // "\n" }
388 sub willneed { re_memo($_) for @_ }
390 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
391 Message-ID X-Alt-Message-ID));