]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Eml.pm
f022516c12cd091cd2ee6bc77212208f399b7522
[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 $MAXPARTS = 1000; # same as SpamAssassin
42 our $MAXDEPTH = 20; # seems enough, Perl sucks, here
43 our $MAXBOUNDLEN = 2048; # same as postfix
44
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);
50
51 my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
52 my %DECODE_FULL = (
53         Subject => 1,
54         'Content-Description' => 1,
55         'Content-Type' => 1, # not correct, but needed, oh well
56 );
57 our %STR_TYPE = (text => 1);
58 our %STR_SUBTYPE = (plain => 1, html => 1);
59
60 my %re_memo;
61 sub re_memo ($) {
62         my ($k) = @_;
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
66                                         # continuation lines:
67                                         (?:[^:\n]*?[ \t]+[^\n]*\r?\n)*)
68                                         /ismx
69 }
70
71 # compatible with our uses of Email::MIME
72 sub new {
73         my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
74         # substr() can modify the first arg in-place and to avoid
75         # memcpy/memmove on a potentially large scalar.  It does need
76         # to make a copy for $hdr, though.  Idea stolen from Email::Simple.
77
78         # We also prefer index() on common LFLF emails since it's faster
79         # and re scan can bump RSS by length($$ref) on big strings
80         if (index($$ref, "\r\n") < 0 && (my $pos = index($$ref, "\n\n")) >= 0) {
81                 # likely on *nix
82                 my $hdr = substr($$ref, 0, $pos + 2, ''); # sv_chop on $$ref
83                 chop($hdr); # lower SvCUR
84                 bless { hdr => \$hdr, crlf => "\n", bdy => $ref }, __PACKAGE__;
85         } elsif ($$ref =~ /\r?\n(\r?\n)/s) {
86                 my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
87                 substr($hdr, -(length($1))) = ''; # lower SvCUR
88                 bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
89         } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
90                 # body is optional :P
91                 bless { hdr => \($$ref), crlf => $1 }, __PACKAGE__;
92         } else { # nothing useful
93                 my $hdr = $$ref = '';
94                 bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
95         }
96 }
97
98 sub new_sub {
99         my (undef, $ref) = @_;
100         # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
101         $$ref =~ /\A(\r?\n)/s or goto &new;
102         my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
103         bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
104 }
105
106 # same output as Email::Simple::Header::header_raw, but we extract
107 # headers on-demand instead of parsing them into a list which
108 # requires O(n) lookups anyways
109 sub header_raw {
110         my $re = re_memo($_[1]);
111         my @v = (${ $_[0]->{hdr} } =~ /$re/g);
112         for (@v) {
113                 # for compatibility w/ Email::Simple::Header,
114                 s/\s+\z//s;
115                 s/\A\s+//s;
116                 s/\r?\n[ \t]*/ /gs;
117         }
118         wantarray ? @v : $v[0];
119 }
120
121 # pick the first Content-Type header to match Email::MIME behavior.
122 # It's usually the right one based on historical archives.
123 sub ct ($) {
124         # PublicInbox::EmlContentFoo::content_type:
125         $_[0]->{ct} //= parse_content_type(header($_[0], 'Content-Type'));
126 }
127
128 # returns a queue of sub-parts iff it's worth descending into
129 # TODO: descend into message/rfc822 parts (Email::MIME didn't)
130 sub mp_descend ($$) {
131         my ($self, $nr) = @_; # or $once for top-level
132         my $bnd = ct($self)->{attributes}->{boundary} // return; # single-part
133         return if $bnd eq '' || length($bnd) >= $MAXBOUNDLEN;
134         $bnd = quotemeta($bnd);
135
136         # "multipart" messages can exist w/o a body
137         my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
138
139         # Cut at the the first epilogue, not subsequent ones.
140         # *sigh* just the regexp match alone seems to bump RSS by
141         # length($$bdy) on a ~30M string:
142         my $epilogue_missing;
143         if ($$bdy =~ /(?:\r?\n)?^--$bnd--[ \t]*\r?$/sm) {
144                 substr($$bdy, $-[0]) = '';
145         } else {
146                 $epilogue_missing = 1;
147         }
148
149         # *Sigh* split() doesn't work in-place and return CoW strings
150         # because Perl wants to "\0"-terminate strings.  So split()
151         # again bumps RSS by length($$bdy)
152
153         # Quiet warning for "Complex regular subexpression recursion limit"
154         # in case we get many empty parts, it's harmless in this case
155         no warnings 'regexp';
156         my ($pre, @parts) = split(/(?:\r?\n)?(?:^--$bnd[ \t]*\r?\n)+/ms,
157                                 $$bdy,
158                                 # + 3 since we don't want the last part
159                                 # processed to include any other excluded
160                                 # parts ($nr starts at 1, and I suck at math)
161                                 $MAXPARTS + 3 - $nr);
162
163         if (@parts) { # the usual path if we got this far:
164                 undef $bdy; # release memory ASAP if $nr > 0
165
166                 # compatibility with Email::MIME
167                 $parts[-1] =~ s/\n\r?\n\z/\n/s if $epilogue_missing;
168
169                 @parts = grep /[^ \t\r\n]/s, @parts; # ignore empty parts
170
171                 # Keep "From: someone..." from preamble in old,
172                 # buggy versions of git-send-email, otherwise drop it
173                 # There's also a case where quoted text showed up in the
174                 # preamble
175                 # <20060515162817.65F0F1BBAE@citi.umich.edu>
176                 unshift(@parts, $pre) if $pre =~ /:/s;
177                 return \@parts;
178         }
179         # "multipart", but no boundary found, treat as single part
180         $self->{bdy} //= $bdy;
181         undef;
182 }
183
184 # $p = [ \@parts, $depth, $idx ]
185 # $idx[0] grows as $depth grows, $idx[1] == $p->[-1] == current part
186 # (callers need to be updated)
187 # \@parts is a queue which empties when we're done with a parent part
188
189 # same usage as PublicInbox::MsgIter::msg_iter
190 # $cb - user-supplied callback sub
191 # $arg - user-supplied arg (think pthread_create)
192 # $once - unref body scalar during iteration
193 sub each_part {
194         my ($self, $cb, $arg, $once) = @_;
195         my $p = mp_descend($self, $once // 0) or
196                                         return $cb->([$self, 0, 0], $arg);
197         $p = [ $p, 0 ];
198         my @s; # our virtual stack
199         my $nr = 0;
200         while ((scalar(@{$p->[0]}) || ($p = pop @s)) && ++$nr <= $MAXPARTS) {
201                 ++$p->[-1]; # bump index
202                 my (undef, @idx) = @$p;
203                 @idx = (join('.', @idx));
204                 my $depth = ($idx[0] =~ tr/././) + 1;
205                 my $sub = new_sub(undef, \(shift @{$p->[0]}));
206                 if ($depth < $MAXDEPTH && (my $nxt = mp_descend($sub, $nr))) {
207                         push(@s, $p) if scalar @{$p->[0]};
208                         $p = [ $nxt, @idx, 0 ];
209                 } else { # a leaf node
210                         $cb->([$sub, $depth, @idx], $arg);
211                 }
212         }
213 }
214
215 sub enc_qp {
216         # prevent MIME::QuotedPrint from encoding CR as =0D since it's
217         # against RFCs and breaks MUAs
218         $_[0] =~ s/\r\n/\n/sg;
219         encode_qp($_[0], "\r\n");
220 }
221
222 sub dec_qp {
223         # RFC 2822 requires all lines to end in CRLF, though... :<
224         $_[0] = decode_qp($_[0]);
225         $_[0] =~ s/\n/\r\n/sg;
226         $_[0]
227 }
228
229 sub identity_codec { $_[0] }
230
231 ########### compatibility section for existing Email::MIME uses #########
232
233 sub header_obj {
234         bless { hdr => $_[0]->{hdr}, crlf => $_[0]->{crlf} }, __PACKAGE__;
235 }
236
237 sub subparts {
238         my ($self) = @_;
239         my $parts = mp_descend($self, 0) or return ();
240         my $bnd = ct($self)->{attributes}->{boundary} // die 'BUG: no boundary';
241         my $bdy = $self->{bdy};
242         if ($$bdy =~ /\A(.*?)(?:\r?\n)?^--\Q$bnd\E[ \t]*\r?$/sm) {
243                 $self->{preamble} = $1;
244         }
245         if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
246                 $self->{epilogue} = $1;
247         }
248         map { new_sub(undef, \$_) } @$parts;
249 }
250
251 sub parts_set {
252         my ($self, $parts) = @_;
253
254         # we can't fully support what Email::MIME does,
255         # just what our filter code needs:
256         my $bnd = ct($self)->{attributes}->{boundary} // die <<EOF;
257 ->parts_set not supported for single-part messages
258 EOF
259         my $crlf = $self->{crlf};
260         my $fin_bnd = "$crlf--$bnd--$crlf";
261         $bnd = "$crlf--$bnd$crlf";
262         ${$self->{bdy}} = join($bnd,
263                                 delete($self->{preamble}) // '',
264                                 map { $_->as_string } @$parts
265                                 ) .
266                                 $fin_bnd .
267                                 (delete($self->{epilogue}) // '');
268         undef;
269 }
270
271 sub body_set {
272         my ($self, $body) = @_;
273         my $bdy = $self->{bdy} = ref($body) ? $body : \$body;
274         if (my $cte = header_raw($self, 'Content-Transfer-Encoding')) {
275                 my $enc = $MIME_ENC{lc($cte)} or croak("can't encode `$cte'");
276                 $$bdy = $enc->($$bdy); # in-place
277         }
278         undef;
279 }
280
281 sub body_str_set {
282         my ($self, $body_str) = @_;
283         my $charset = ct($self)->{attributes}->{charset} or
284                 Carp::confess('body_str was given, but no charset is defined');
285         body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
286 }
287
288 sub content_type { scalar header($_[0], 'Content-Type') }
289
290 # we only support raw header_set
291 sub header_set {
292         my ($self, $pfx, @vals) = @_;
293         my $re = re_memo($pfx);
294         my $hdr = $self->{hdr};
295         return $$hdr =~ s!$re!!g if !@vals;
296         $pfx .= ': ';
297         my $len = 78 - length($pfx);
298         @vals = map {;
299                 # folding differs from Email::Simple::Header,
300                 # we favor tabs for visibility (and space savings :P)
301                 if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
302                         local $Text::Wrap::columns = $len;
303                         local $Text::Wrap::huge = 'overflow';
304                         $pfx . wrap('', "\t", $_) . $self->{crlf};
305                 } else {
306                         $pfx . $_ . $self->{crlf};
307                 }
308         } @vals;
309         $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
310         $$hdr .= join('', @vals); # append any leftovers not replaced
311         # wantarray ? @_[2..$#_] : $_[2]; # Email::Simple::Header compat
312         undef; # we don't care for the return value
313 }
314
315 # note: we only call this method on Subject
316 sub header_str_set {
317         my ($self, $name, @vals) = @_;
318         for (@vals) {
319                 next unless /[^\x20-\x7e]/;
320                 utf8::encode($_); # to octets
321                 # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
322                 s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
323         }
324         header_set($self, $name, @vals);
325 }
326
327 sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
328
329 sub filename {
330         my $dis = header_raw($_[0], 'Content-Disposition');
331         my $attrs = parse_content_disposition($dis)->{attributes};
332         my $fn = $attrs->{filename};
333         $fn = ct($_[0])->{attributes}->{name} if !defined($fn) || $fn eq '';
334         (defined($fn) && $fn =~ /=\?/) ? mhdr_decode($fn) : $fn;
335 }
336
337 sub xs_addr_str { # helper for ->header / ->header_str
338         for (@_) { # array from header_raw()
339                 next unless /=\?/;
340                 my @g = parse_email_groups($_); # [ foo => [ E::A::X, ... ]
341                 for (my $i = 0; $i < @g; $i += 2) {
342                         if (defined($g[$i]) && $g[$i] =~ /=\?/) {
343                                 $g[$i] = mhdr_decode($g[$i]);
344                         }
345                         my $addrs = $g[$i + 1];
346                         for my $eax (@$addrs) {
347                                 for my $m (qw(phrase comment)) {
348                                         my $v = $eax->$m;
349                                         $eax->$m(mhdr_decode($v)) if
350                                                         $v && $v =~ /=\?/;
351                                 }
352                         }
353                 }
354                 $_ = format_email_groups(@g);
355         }
356 }
357
358 eval {
359         require Email::Address::XS;
360         Email::Address::XS->import(qw(parse_email_groups format_email_groups));
361         1;
362 } or do {
363         # fallback to just decoding everything, because parsing
364         # email addresses correctly w/o C/XS is slow
365         %DECODE_FULL = (%DECODE_FULL, %DECODE_ADDRESS);
366         %DECODE_ADDRESS = ();
367 };
368
369 *header = \&header_str;
370 sub header_str {
371         my ($self, $name) = @_;
372         my @v = header_raw($self, $name);
373         if ($DECODE_ADDRESS{$name}) {
374                 xs_addr_str(@v);
375         } elsif ($DECODE_FULL{$name}) {
376                 for (@v) {
377                         $_ = mhdr_decode($_) if /=\?/;
378                 }
379         }
380         wantarray ? @v : $v[0];
381 }
382
383 sub body_raw { ${$_[0]->{bdy} // \''}; }
384
385 sub body {
386         my $raw = body_raw($_[0]);
387         my $cte = header_raw($_[0], 'Content-Transfer-Encoding') or return $raw;
388         ($cte) = ($cte =~ /([a-zA-Z0-9\-]+)/) or return $raw; # For S/MIME, etc
389         my $dec = $MIME_DEC{lc($cte)} or return $raw;
390         $dec->($raw);
391 }
392
393 sub body_str {
394         my ($self) = @_;
395         my $ct = ct($self);
396         my $charset = $ct->{attributes}->{charset};
397         if (!$charset) {
398                 if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
399                         return body($self);
400                 }
401                 Carp::confess("can't get body as a string for ",
402                         join("\n\t", header_raw($self, 'Content-Type')));
403         }
404         decode($charset, body($self), Encode::FB_CROAK);
405 }
406
407 sub as_string {
408         my ($self) = @_;
409         my $ret = ${ $self->{hdr} };
410         return $ret unless defined($self->{bdy});
411         $ret .= $self->{crlf};
412         $ret .= ${$self->{bdy}};
413 }
414
415 # Unlike Email::MIME::charset_set, this only changes the parsed
416 # representation of charset used for search indexing and HTML display.
417 # This does NOT affect what ->as_string returns.
418 sub charset_set {
419         ct($_[0])->{attributes}->{charset} = $_[1];
420 }
421
422 sub crlf { $_[0]->{crlf} // "\n" }
423
424 sub willneed { re_memo($_) for @_ }
425
426 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References
427                 Message-ID X-Alt-Message-ID));
428
429 1;