]> Sergey Matveev's repositories - public-inbox.git/blobdiff - lib/PublicInbox/Eml.pm
No ext_urls
[public-inbox.git] / lib / PublicInbox / Eml.pm
index 4508bd84c6b1b3457fa7b9247331b94694eabc51..8b999e1a88ef8d11b78e7c5bd0c022dbd7d0f7be 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright (C) 2020 all contributors <meta@public-inbox.org>
+# Copyright (C) all contributors <meta@public-inbox.org>
 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
 #
 # Lazy MIME parser, it still slurps the full message but keeps short
@@ -28,7 +28,7 @@ package PublicInbox::Eml;
 use strict;
 use v5.10.1;
 use Carp qw(croak);
-use Encode qw(find_encoding decode encode); # stdlib
+use Encode qw(find_encoding); # stdlib
 use Text::Wrap qw(wrap); # stdlib, we need Perl 5.6+ for $huge
 use MIME::Base64 3.05; # Perl 5.10.0 / 5.9.2
 use MIME::QuotedPrint 3.05; # ditto
@@ -38,9 +38,12 @@ my $MIME_Header = find_encoding('MIME-Header');
 use PublicInbox::EmlContentFoo qw(parse_content_type parse_content_disposition);
 $PublicInbox::EmlContentFoo::STRICT_PARAMS = 0;
 
-our $MAXPARTS = 1000; # same as SpamAssassin
-our $MAXDEPTH = 20; # seems enough, Perl sucks, here
-our $MAXBOUNDLEN = 2048; # same as postfix
+our $mime_parts_limit = 1000; # same as SpamAssassin (not in postfix AFAIK)
+
+# the rest of the limit names are taken from postfix:
+our $mime_nesting_limit = 20; # seems enough, Perl sucks, here
+our $mime_boundary_length_limit = 2048; # same as postfix
+our $header_size_limit = 102400; # same as postfix
 
 my %MIME_ENC = (qp => \&enc_qp, base64 => \&encode_base64);
 my %MIME_DEC = (qp => \&dec_qp, base64 => \&decode_base64);
@@ -48,7 +51,9 @@ $MIME_ENC{quotedprint} = $MIME_ENC{'quoted-printable'} = $MIME_ENC{qp};
 $MIME_DEC{quotedprint} = $MIME_DEC{'quoted-printable'} = $MIME_DEC{qp};
 $MIME_ENC{$_} = \&identity_codec for qw(7bit 8bit binary);
 
-my %DECODE_ADDRESS = map { $_ => 1 } qw(From To Cc Sender Reply-To);
+my %DECODE_ADDRESS = map {
+       ($_ => 1, "Resent-$_" => 1)
+} qw(From To Cc Sender Reply-To Bcc);
 my %DECODE_FULL = (
        Subject => 1,
        'Content-Description' => 1,
@@ -57,6 +62,14 @@ my %DECODE_FULL = (
 our %STR_TYPE = (text => 1);
 our %STR_SUBTYPE = (plain => 1, html => 1);
 
+# message/* subtypes we descend into
+our %MESSAGE_DESCEND = (
+       news => 1, # RFC 1849 (obsolete, but archives are forever)
+       rfc822 => 1, # RFC 2046
+       rfc2822 => 1, # gmime handles this (but not rfc5322)
+       global => 1, # RFC 6532
+);
+
 my %re_memo;
 sub re_memo ($) {
        my ($k) = @_;
@@ -68,30 +81,59 @@ sub re_memo ($) {
                                        /ismx
 }
 
+sub hdr_truncate ($) {
+       my $len = length($_[0]);
+       substr($_[0], $header_size_limit, $len) = '';
+       my $end = rindex($_[0], "\n");
+       if ($end >= 0) {
+               ++$end;
+               substr($_[0], $end, $len) = '';
+               warn "header of $len bytes truncated to $end bytes\n";
+       } else {
+               $_[0] = '';
+               warn <<EOF
+header of $len bytes without `\\n' within $header_size_limit ignored
+EOF
+       }
+}
+
 # compatible with our uses of Email::MIME
 sub new {
        my $ref = ref($_[1]) ? $_[1] : \(my $cpy = $_[1]);
-       if ($$ref =~ /(?:\r?\n(\r?\n))/gs) { # likely
-               # This can modify $$ref in-place and to avoid memcpy/memmove
-               # on a potentially large $$ref.  It does need to make a
-               # copy for $hdr, though.  Idea stolen from Email::Simple
-               my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
+       # substr() can modify the first arg in-place and to avoid
+       # memcpy/memmove on a potentially large scalar.  It does need
+       # to make a copy for $hdr, though.  Idea stolen from Email::Simple.
+
+       # We also prefer index() on common LFLF emails since it's faster
+       # and re scan can bump RSS by length($$ref) on big strings
+       if (index($$ref, "\r\n") < 0 && (my $pos = index($$ref, "\n\n")) >= 0) {
+               # likely on *nix
+               my $hdr = substr($$ref, 0, $pos + 2, ''); # sv_chop on $$ref
+               chop($hdr); # lower SvCUR
+               hdr_truncate($hdr) if length($hdr) > $header_size_limit;
+               bless { hdr => \$hdr, crlf => "\n", bdy => $ref }, __PACKAGE__;
+       } elsif ($$ref =~ /\r?\n(\r?\n)/s) {
+               my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
                substr($hdr, -(length($1))) = ''; # lower SvCUR
+               hdr_truncate($hdr) if length($hdr) > $header_size_limit;
                bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
        } elsif ($$ref =~ /^[a-z0-9-]+[ \t]*:/ims && $$ref =~ /(\r?\n)\z/s) {
                # body is optional :P
-               bless { hdr => \($$ref), crlf => $1 }, __PACKAGE__;
-       } else { # nothing useful
-               my $hdr = $$ref = '';
-               bless { hdr => \$hdr, crlf => "\n" }, __PACKAGE__;
+               my $hdr = substr($$ref, 0, $header_size_limit + 1);
+               hdr_truncate($hdr) if length($hdr) > $header_size_limit;
+               bless { hdr => \$hdr, crlf => $1 }, __PACKAGE__;
+       } else { # just a body w/o header?
+               my $hdr = '';
+               my $eol = ($$ref =~ /(\r?\n)/) ? $1 : "\n";
+               bless { hdr => \$hdr, crlf => $eol, bdy => $ref }, __PACKAGE__;
        }
 }
 
 sub new_sub {
        my (undef, $ref) = @_;
        # special case for messages like <85k5su9k59.fsf_-_@lola.goethe.zz>
-       $$ref =~ /\A(?:(\r?\n))/gs or goto &new;
-       my $hdr = substr($$ref, 0, pos($$ref), ''); # sv_chop on $$ref
+       $$ref =~ /\A(\r?\n)/s or return new(undef, $ref);
+       my $hdr = substr($$ref, 0, $+[0], ''); # sv_chop on $$ref
        bless { hdr => \$hdr, crlf => $1, bdy => $ref }, __PACKAGE__;
 }
 
@@ -102,6 +144,7 @@ sub header_raw {
        my $re = re_memo($_[1]);
        my @v = (${ $_[0]->{hdr} } =~ /$re/g);
        for (@v) {
+               utf8::decode($_); # SMTPUTF8
                # for compatibility w/ Email::Simple::Header,
                s/\s+\z//s;
                s/\A\s+//s;
@@ -118,13 +161,25 @@ sub ct ($) {
 }
 
 # returns a queue of sub-parts iff it's worth descending into
-# TODO: descend into message/rfc822 parts (Email::MIME didn't)
 sub mp_descend ($$) {
        my ($self, $nr) = @_; # or $once for top-level
-       my $bnd = ct($self)->{attributes}->{boundary} // return; # single-part
-       return if $bnd eq '' || length($bnd) >= $MAXBOUNDLEN;
+       my $ct = ct($self);
+       my $type = lc($ct->{type});
+       if ($type eq 'message' && $MESSAGE_DESCEND{lc($ct->{subtype})}) {
+               my $nxt = new(undef, body_raw($self));
+               $self->{-call_cb} = $nxt->{is_submsg} = 1;
+               return [ $nxt ];
+       }
+       return if $type ne 'multipart';
+       my $bnd = $ct->{attributes}->{boundary} // return; # single-part
+       return if $bnd eq '' || length($bnd) >= $mime_boundary_length_limit;
        $bnd = quotemeta($bnd);
 
+       # this is a multipart message that didn't get descended into in
+       # public-inbox <= 1.5.0, so ensure we call the user callback for
+       # this part to not break PSGI downloads.
+       $self->{-call_cb} = $self->{is_submsg};
+
        # "multipart" messages can exist w/o a body
        my $bdy = ($nr ? delete($self->{bdy}) : \(body_raw($self))) or return;
 
@@ -132,8 +187,8 @@ sub mp_descend ($$) {
        # *sigh* just the regexp match alone seems to bump RSS by
        # length($$bdy) on a ~30M string:
        my $epilogue_missing;
-       if ($$bdy =~ /((?:\r?\n)?^--$bnd--[ \t]*\r?$)/gsm) {
-               substr($$bdy, pos($$bdy) - length($1)) = '';
+       if ($$bdy =~ /(?:\r?\n)?^--$bnd--[ \t]*\r?$/sm) {
+               substr($$bdy, $-[0]) = '';
        } else {
                $epilogue_missing = 1;
        }
@@ -150,7 +205,7 @@ sub mp_descend ($$) {
                                # + 3 since we don't want the last part
                                # processed to include any other excluded
                                # parts ($nr starts at 1, and I suck at math)
-                               $MAXPARTS + 3 - $nr);
+                               $mime_parts_limit + 3 - $nr);
 
        if (@parts) { # the usual path if we got this far:
                undef $bdy; # release memory ASAP if $nr > 0
@@ -158,14 +213,15 @@ sub mp_descend ($$) {
                # compatibility with Email::MIME
                $parts[-1] =~ s/\n\r?\n\z/\n/s if $epilogue_missing;
 
-               @parts = grep /[^ \t\r\n]/s, @parts; # ignore empty parts
+               # ignore empty parts
+               @parts = map { new_sub(undef, \$_) } grep /[^ \t\r\n]/s, @parts;
 
                # Keep "From: someone..." from preamble in old,
                # buggy versions of git-send-email, otherwise drop it
                # There's also a case where quoted text showed up in the
                # preamble
                # <20060515162817.65F0F1BBAE@citi.umich.edu>
-               unshift(@parts, $pre) if $pre =~ /:/s;
+               unshift(@parts, new_sub(undef, \$pre)) if index($pre, ':') >= 0;
                return \@parts;
        }
        # "multipart", but no boundary found, treat as single part
@@ -182,22 +238,30 @@ sub mp_descend ($$) {
 # $cb - user-supplied callback sub
 # $arg - user-supplied arg (think pthread_create)
 # $once - unref body scalar during iteration
+# $all - used by IMAP server, only
 sub each_part {
-       my ($self, $cb, $arg, $once) = @_;
+       my ($self, $cb, $arg, $once, $all) = @_;
        my $p = mp_descend($self, $once // 0) or
-                                       return $cb->([$self, 0, 0], $arg);
+                                       return $cb->([$self, 0, 1], $arg);
+
+       $cb->([$self, 0, 0], $arg) if ($all || $self->{-call_cb}); # rare
+
        $p = [ $p, 0 ];
        my @s; # our virtual stack
        my $nr = 0;
-       while ((scalar(@{$p->[0]}) || ($p = pop @s)) && ++$nr <= $MAXPARTS) {
+       while ((scalar(@{$p->[0]}) || ($p = pop @s)) &&
+                       ++$nr <= $mime_parts_limit) {
                ++$p->[-1]; # bump index
                my (undef, @idx) = @$p;
                @idx = (join('.', @idx));
                my $depth = ($idx[0] =~ tr/././) + 1;
-               my $sub = new_sub(undef, \(shift @{$p->[0]}));
-               if ($depth < $MAXDEPTH && (my $nxt = mp_descend($sub, $nr))) {
+               my $sub = shift @{$p->[0]};
+               if ($depth < $mime_nesting_limit &&
+                               (my $nxt = mp_descend($sub, $nr))) {
                        push(@s, $p) if scalar @{$p->[0]};
                        $p = [ $nxt, @idx, 0 ];
+                       ($all || $sub->{-call_cb}) and
+                               $cb->([$sub, $depth, @idx], $arg);
                } else { # a leaf node
                        $cb->([$sub, $depth, @idx], $arg);
                }
@@ -237,7 +301,7 @@ sub subparts {
        if ($$bdy =~ /^--\Q$bnd\E--[ \t]*\r?\n(.+)\z/sm) {
                $self->{epilogue} = $1;
        }
-       map { new_sub(undef, \$_) } @$parts;
+       @$parts;
 }
 
 sub parts_set {
@@ -271,10 +335,18 @@ sub body_set {
 }
 
 sub body_str_set {
-       my ($self, $body_str) = @_;
-       my $charset = ct($self)->{attributes}->{charset} or
-               Carp::confess('body_str was given, but no charset is defined');
-       body_set($self, \(encode($charset, $body_str, Encode::FB_CROAK)));
+       my ($self, $str) = @_;
+       my $cs = ct($self)->{attributes}->{charset} //
+               croak('body_str was given, but no charset is defined');
+       my $enc = find_encoding($cs) // croak "unknown encoding `$cs'";
+       my $tmp;
+       {
+               my @w;
+               local $SIG{__WARN__} = sub { push @w, @_ };
+               $tmp = $enc->encode($str, Encode::FB_WARN);
+               croak(@w) if @w;
+       };
+       body_set($self, \$tmp);
 }
 
 sub content_type { scalar header($_[0], 'Content-Type') }
@@ -288,14 +360,15 @@ sub header_set {
        $pfx .= ': ';
        my $len = 78 - length($pfx);
        @vals = map {;
+               utf8::encode(my $v = $_); # to bytes, support SMTPUTF8
                # folding differs from Email::Simple::Header,
                # we favor tabs for visibility (and space savings :P)
                if (length($_) >= $len && (/\n[^ \t]/s || !/\n/s)) {
                        local $Text::Wrap::columns = $len;
                        local $Text::Wrap::huge = 'overflow';
-                       $pfx . wrap('', "\t", $_) . $self->{crlf};
+                       $pfx . wrap('', "\t", $v) . $self->{crlf};
                } else {
-                       $pfx . $_ . $self->{crlf};
+                       $pfx . $v . $self->{crlf};
                }
        } @vals;
        $$hdr =~ s!$re!shift(@vals) // ''!ge; # replace current headers, first
@@ -309,14 +382,19 @@ sub header_str_set {
        my ($self, $name, @vals) = @_;
        for (@vals) {
                next unless /[^\x20-\x7e]/;
-               utf8::encode($_); # to octets
                # 39: int((75 - length("Subject: =?UTF-8?B?".'?=') ) / 4) * 3;
-               s/(.{1,39})/'=?UTF-8?B?'.encode_base64($1, '').'?='/ges;
+               s/(.{1,39})/
+                       my $x = $1;
+                       utf8::encode($x); # to octets
+                       '=?UTF-8?B?'.encode_base64($x, '').'?='
+               /xges;
        }
        header_set($self, $name, @vals);
 }
 
-sub mhdr_decode ($) { eval { $MIME_Header->decode($_[0]) } // $_[0] }
+sub mhdr_decode ($) {
+       eval { $MIME_Header->decode($_[0], Encode::FB_DEFAULT) } // $_[0];
+}
 
 sub filename {
        my $dis = header_raw($_[0], 'Content-Disposition');
@@ -385,15 +463,20 @@ sub body {
 sub body_str {
        my ($self) = @_;
        my $ct = ct($self);
-       my $charset = $ct->{attributes}->{charset};
-       if (!$charset) {
-               if ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) {
+       my $cs = $ct->{attributes}->{charset} // do {
+               ($STR_TYPE{$ct->{type}} && $STR_SUBTYPE{$ct->{subtype}}) and
                        return body($self);
-               }
-               Carp::confess("can't get body as a string for ",
+               croak("can't get body as a string for ",
                        join("\n\t", header_raw($self, 'Content-Type')));
-       }
-       decode($charset, body($self), Encode::FB_CROAK);
+       };
+       my $enc = find_encoding($cs) or croak "unknown encoding `$cs'";
+       my $tmp = body($self);
+       # workaround https://rt.cpan.org/Public/Bug/Display.html?id=139622
+       my @w;
+       local $SIG{__WARN__} = sub { push @w, @_ };
+       my $ret = $enc->decode($tmp, Encode::FB_WARN);
+       croak(@w) if @w;
+       $ret;
 }
 
 sub as_string {
@@ -413,6 +496,33 @@ sub charset_set {
 
 sub crlf { $_[0]->{crlf} // "\n" }
 
+sub raw_size {
+       my ($self) = @_;
+       my $len = length(${$self->{hdr}});
+       defined($self->{bdy}) and
+               $len += length(${$self->{bdy}}) + length($self->{crlf});
+       $len;
+}
+
+# warnings to ignore when handling spam mailboxes and maybe other places
+sub warn_ignore {
+       my $s = "@_";
+       # Email::Address::XS warnings
+       $s =~ /^Argument contains empty /
+       || $s =~ /^Element at index [0-9]+.*? contains /
+       # PublicInbox::MsgTime
+       || $s =~ /^bogus TZ offset: .+?, ignoring and assuming \+0000/
+       || $s =~ /^bad Date: .+? in /
+       # Encode::Unicode::UTF7
+       || $s =~ /^Bad UTF7 data escape at /
+}
+
+# this expects to be RHS in this assignment: "local $SIG{__WARN__} = ..."
+sub warn_ignore_cb {
+       my $cb = $SIG{__WARN__} // \&CORE::warn;
+       sub { $cb->(@_) unless warn_ignore(@_) }
+}
+
 sub willneed { re_memo($_) for @_ }
 
 willneed(qw(From To Cc Date Subject Content-Type In-Reply-To References