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