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 $MAXPARTS = 1000; # same as SpamAssassin
42 our $MAXDEPTH = 20; # seems enough, Perl sucks, here
43 our $MAXBOUNDLEN = 2048; # same as postfix
45 my %MIME_ENC = (qp => \&enc_qp, base64 => \&encode_base64);
46 my %MIME_DEC = (qp => \&dec_qp, base64 => \&decode_base64);
47 $MIME_ENC{quotedprint} = $MIME_ENC{'quoted-printable'} = $MIME_ENC{qp};
48 $MIME_DEC{quotedprint} = $MIME_DEC{'quoted-printable'} = $MIME_DEC{qp};
49 $MIME_ENC{$_} = \&identity_codec for qw(7bit 8bit binary);
51 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
54 'Content-Description' => 1,
55 'Content-Type' => 1, # not correct, but needed, oh well
57 our %STR_TYPE = (text => 1);
58 our %STR_SUBTYPE = (plain => 1, html => 1);
63 # Do not normalize $k with lc/uc; instead strive to keep
64 # capitalization in our codebase consistent.
65 $re_memo{$k} ||= qr/^\Q$k\E:[ \t]*([^\n]*\r?\n # 1st line
67 (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
71 # compatible with our uses of Email::MIME
73 my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
74 if ($$ref =~ /(?:\r?\n(\r?\n))/gs) { # likely
75 # This can modify $$ref in-place and to avoid memcpy/memmove
76 # on a potentially large $$ref. It does need to make a
77 # copy for $hdr, though. Idea stolen from Email::Simple
78 my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
79 substr($hdr, -(length($1))) = ''; # lower SvCUR
80 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
81 } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
83 bless { hdr => \($$ref), crlf => $1 }, __PACKAGE__;
84 } else { # nothing useful
86 bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
91 my (undef, $ref) = @_;
92 # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
93 $$ref =~ /\A(?:(\r?\n))/gs or goto &new;
94 my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
95 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
98 # same output as Email::Simple::Header::header_raw, but we extract
99 # headers on-demand instead of parsing them into a list which
100 # requires O(n) lookups anyways
102 my $re = re_memo($_[1]);
103 my @v = (${ $_[0]->{hdr} } =~ /$re/g);
105 # for compatibility w/ Email::Simple::Header,
110 wantarray ? @v : $v[0];
113 # pick the first Content-Type header to match Email::MIME behavior.
114 # It's usually the right one based on historical archives.
116 # PublicInbox::EmlContentFoo::content_type:
117 $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
120 # returns a queue of sub-parts iff it's worth descending into
121 # TODO: descend into message/rfc822 parts (Email::MIME didn't)
122 sub mp_descend ($$) {
123 my ($self, $nr) = @_; # or $once for top-level
124 my $bnd = ct($self)->{attributes}->{boundary} // return; # single-part
125 return if $bnd eq '' || length($bnd) >= $MAXBOUNDLEN;
126 $bnd = quotemeta($bnd);
128 # "multipart" messages can exist w/o a body
129 my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
131 # Cut at the the first epilogue, not subsequent ones.
132 # *sigh* just the regexp match alone seems to bump RSS by
133 # length($$bdy) on a ~30M string:
134 $$bdy =~ /((?:\r?\n)?^--$bnd--[ \t]*\r?$)/gsm and
135 substr($$bdy, pos($$bdy) - length($1)) = '';
137 # *Sigh* split() doesn't work in-place and return CoW strings
138 # because Perl wants to "\0"-terminate strings. So split()
139 # again bumps RSS by length($$bdy)
141 # Quiet warning for "Complex regular subexpression recursion limit"
142 # in case we get many empty parts, it's harmless in this case
143 no warnings 'regexp';
144 my ($pre, @parts) = split(/(?:\r?\n)?(?:^--$bnd[ \t]*\r?\n)+/ms,
146 # + 3 since we don't want the last part
147 # processed to include any other excluded
148 # parts ($nr starts at 1, and I suck at math)
149 $MAXPARTS + 3 - $nr);
151 if (@parts) { # the usual path if we got this far:
152 undef $bdy; # release memory ASAP if $nr > 0
153 @parts = grep /[^ \t\r\n]/s, @parts; # ignore empty parts
155 # Keep "From: someone..." from preamble in old,
156 # buggy versions of git-send-email, otherwise drop it
157 # There's also a case where quoted text showed up in the
159 # <20060515162817.65F0F1BBAE@citi.umich.edu>
160 unshift(@parts, $pre) if $pre =~ /:/s;
163 # "multipart", but no boundary found, treat as single part
164 $self->{bdy} //= $bdy;
168 # $p = [ \@parts, $depth, $idx ]
169 # $idx[0] grows as $depth grows, $idx[1] == $p->[-1] == current part
170 # (callers need to be updated)
171 # \@parts is a queue which empties when we're done with a parent part
173 # same usage as PublicInbox::MsgIter::msg_iter
174 # $cb - user-supplied callback sub
175 # $arg - user-supplied arg (think pthread_create)
176 # $once - unref body scalar during iteration
178 my ($self, $cb, $arg, $once) = @_;
179 my $p = mp_descend($self, $once // 0) or
180 return $cb->([$self, 0, 0], $arg);
182 my @s; # our virtual stack
184 while ((scalar(@{$p->[0]}) || ($p = pop @s)) && ++$nr <= $MAXPARTS) {
185 ++$p->[-1]; # bump index
186 my (undef, @idx) = @$p;
187 @idx = (join('.', @idx));
188 my $depth = ($idx[0] =~ tr/././) + 1;
189 my $sub = new_sub(undef, \(shift @{$p->[0]}));
190 if ($depth < $MAXDEPTH && (my $nxt = mp_descend($sub, $nr))) {
191 push(@s, $p) if scalar @{$p->[0]};
192 $p = [ $nxt, @idx, 0 ];
193 } else { # a leaf node
194 $cb->([$sub, $depth, @idx], $arg);
200 # prevent MIME::QuotedPrint from encoding CR as =0D since it's
201 # against RFCs and breaks MUAs
202 $_[0] =~ s/\r\n/\n/sg;
203 encode_qp($_[0], "\r\n");
207 # RFC 2822 requires all lines to end in CRLF, though... :<
208 $_[0] = decode_qp($_[0]);
209 $_[0] =~ s/\n/\r\n/sg;
213 sub identity_codec { $_[0] }
215 ########### compatibility section for existing Email::MIME uses #########
218 bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
223 my $parts = mp_descend($self, 0) or return ();
224 my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
225 my $bdy = $self->{bdy};
226 if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
227 $self->{preamble} = $1;
229 if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
230 $self->{epilogue} = $1;
232 map { new_sub(undef, \$_) } @$parts;
236 my ($self, $parts) = @_;
238 # we can't fully support what Email::MIME does,
239 # just what our filter code needs:
240 my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
241 ->parts_set not supported for single-part messages
243 my $crlf = $self->{crlf};
244 my $fin_bnd = "$crlf--$bnd--$crlf";
245 $bnd = "$crlf--$bnd$crlf";
246 ${$self->{bdy}} = join($bnd,
247 delete($self->{preamble}) // '',
248 map { $_->as_string } @$parts
251 (delete($self->{epilogue}) // '');
256 my ($self, $body) = @_;
257 my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
258 if (my $cte = header_raw($self, 'Content-Transfer-Encoding')) {
259 my $enc = $MIME_ENC{lc($cte)} or croak("can't encode `$cte'");
260 $$bdy = $enc->($$bdy); # in-place
266 my ($self, $body_str) = @_;
267 my $charset = ct($self)->{attributes}->{charset} or
268 Carp::confess('body_str was given, but no charset is defined');
269 body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
272 sub content_type { scalar header($_[0], 'Content-Type') }
274 # we only support raw header_set
276 my ($self, $pfx, @vals) = @_;
277 my $re = re_memo($pfx);
278 my $hdr = $self->{hdr};
279 return $$hdr =~ s!$re!!g if !@vals;
281 my $len = 78 - length($pfx);
283 # folding differs from Email::Simple::Header,
284 # we favor tabs for visibility (and space savings :P)
285 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
286 local $Text::Wrap::columns = $len;
287 local $Text::Wrap::huge = 'overflow';
288 $pfx . wrap('', "\t", $_) . $self->{crlf};
290 $pfx . $_ . $self->{crlf};
293 $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
294 $$hdr .= join('', @vals); # append any leftovers not replaced
295 # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
296 undef; # we don't care for the return value
299 # note: we only call this method on Subject
301 my ($self, $name, @vals) = @_;
303 next unless /[^\x20-\x7e]/;
304 utf8::encode($_); # to octets
305 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
306 s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
308 header_set($self, $name, @vals);
311 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
314 my $dis = header_raw($_[0], 'Content-Disposition');
315 my $attrs = parse_content_disposition($dis)->{attributes};
316 my $fn = $attrs->{filename};
317 $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
318 (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
321 sub xs_addr_str { # helper for ->header / ->header_str
322 for (@_) { # array from header_raw()
324 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
325 for (my $i = 0; $i < @g; $i += 2) {
326 if (defined($g[$i]) && $g[$i] =~ /=\?/) {
327 $g[$i] = mhdr_decode($g[$i]);
329 my $addrs = $g[$i + 1];
330 for my $eax (@$addrs) {
331 for my $m (qw(phrase comment)) {
333 $eax->$m(mhdr_decode($v)) if
338 $_ = format_email_groups(@g);
343 require Email::Address::XS;
344 Email::Address::XS->import(qw(parse_email_groups format_email_groups));
347 # fallback to just decoding everything, because parsing
348 # email addresses correctly w/o C/XS is slow
349 %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
350 %DECODE_ADDRESS = ();
353 *header = \&header_str;
355 my ($self, $name) = @_;
356 my @v = header_raw($self, $name);
357 if ($DECODE_ADDRESS{$name}) {
359 } elsif ($DECODE_FULL{$name}) {
361 $_ = mhdr_decode($_) if /=\?/;
364 wantarray ? @v : $v[0];
367 sub body_raw { ${$_[0]->{bdy} // \''}; }
370 my $raw = body_raw($_[0]);
371 my $cte = header_raw($_[0], 'Content-Transfer-Encoding') or return $raw;
372 ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) or return $raw; # For S/MIME, etc
373 my $dec = $MIME_DEC{lc($cte)} or return $raw;
380 my $charset = $ct->{attributes}->{charset};
382 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
385 Carp::confess("can't get body as a string for ",
386 join("\n\t", header_raw($self, 'Content-Type')));
388 decode($charset, body($self), Encode::FB_CROAK);
393 my $ret = ${ $self->{hdr} };
394 return $ret unless defined($self->{bdy});
395 $ret .= $self->{crlf};
396 $ret .= ${$self->{bdy}};
399 # Unlike Email::MIME::charset_set, this only changes the parsed
400 # representation of charset used for search indexing and HTML display.
401 # This does NOT affect what ->as_string returns.
403 ct($_[0])->{attributes}->{charset} = $_[1];
406 sub crlf { $_[0]->{crlf} // "\n" }
408 sub willneed { re_memo($_) for @_ }
410 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
411 Message-ID X-Alt-Message-ID));