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