[Rt-commit] rt branch, 4.2-on-4.0/protect-more-chars-while-decoding-headers, created. rt-4.0.12-15-g6c78d43

Alex Vandiver alexmv at bestpractical.com
Mon May 6 18:04:09 EDT 2013


The branch, 4.2-on-4.0/protect-more-chars-while-decoding-headers has been created
        at  6c78d437d02f4fc55547d17cfd0aaa3a2b2e489e (commit)

- Log -----------------------------------------------------------------
commit 7bcd6c0abcd1f9273efc020df2107baa0c59efda
Author: Ruslan Zakirov <ruz at bestpractical.com>
Date:   Mon Dec 24 22:08:18 2012 +0400

    ';' can not be used to separate emails in Cc field
    
    Semicolon is used to end a group if there is a group, but
    can not be used to separate emails without group.

diff --git a/t/mail/specials-in-encodedwords.t b/t/mail/specials-in-encodedwords.t
index f9da9c6..36efcd5 100644
--- a/t/mail/specials-in-encodedwords.t
+++ b/t/mail/specials-in-encodedwords.t
@@ -14,7 +14,7 @@ diag "specials (, and ;) in MIME encoded-words aren't treated as specials";
 From: root at localhost
 Subject: testing mime encoded specials
 Cc: a at example.com, =?utf8?q?d=40example.com=2ce=40example.com=3b?=
-    <b at example.com>; c at example.com
+    <b at example.com>, c at example.com
 Content-Type: text/plain; charset=utf8
 
 here's some content

commit fc7cabb0f09f94edce23eb70d0309b4e5a733b08
Author: Ruslan Zakirov <ruz at bestpractical.com>
Date:   Thu Jun 28 23:08:45 2012 +0300

    change how we deal with decoding structured fields
    
    When we get rid of encoded words in formatted fields (From/To/Cc,
    Content-Disposition, Content-Type...), we have to take care of
    preserving structure of the field which means quoting parts. Old code
    were using luck and magic to achieve this instead of parsing field's
    structure.
    
    We use MIME::Field::ParamVal already to deal with continued params
    (RFC2231). This module allows us to deal with separate parameters,
    decode them and deal with quotes inside or absence of those without
    guessing.
    
    Bump the version to a version which fixes a bug [1] in parsing of quoted
    strings and quoting on stringify.
    
    Similar situation with From, Cc, Bcc and other fields with mailboxes. We
    were only dealing with subset of mailbox fields, now we handle all such
    headers that are mentioned in RFC5322.
    
    Switch to Email::Address::List to parse headers with mailboxes. Allows
    us to report errors, handles obsolete emails, don't bails out on not
    ascii.
    
    Email::Address is still used and a bug [2] was discovered in the module
    that may result in unparsable string after re-composing.
    
    [1] https://rt.cpan.org/Ticket/Display.html?id=80433
    [2] https://rt.cpan.org/Ticket/Display.html?id=81170

diff --git a/lib/RT/EmailParser.pm b/lib/RT/EmailParser.pm
index d4a261e..0754870 100644
--- a/lib/RT/EmailParser.pm
+++ b/lib/RT/EmailParser.pm
@@ -526,28 +526,42 @@ we can use that removes the bandaid
 
 =cut
 
+use Email::Address::List;
+
 sub ParseEmailAddress {
     my $self = shift;
     my $address_string = shift;
 
-    $address_string =~ s/^\s+|\s+$//g;
+    my @list = Email::Address::List->parse(
+        $address_string,
+        skip_comments => 1,
+        skip_groups => 1,
+    );
+    my $logger = sub { RT->Logger->error(
+        "Unable to parse an email address from $address_string: ". shift
+    ) };
 
     my @addresses;
-    # if it looks like a username / local only email
-    if ($address_string !~ /@/ && $address_string =~ /^\w+$/) {
-        my $user = RT::User->new( RT->SystemUser );
-        my ($id, $msg) = $user->Load($address_string);
-        if ($id) {
-            push @addresses, Email::Address->new($user->Name,$user->EmailAddress);
+    foreach my $e ( @list ) {
+        if ($e->{'type'} eq 'mailbox') {
+            if ($e->{'not_ascii'}) {
+                $logger->($e->{'value'} ." contains not ASCII values");
+                next;
+            }
+            push @addresses, $e->{'value'}
+        } elsif ( $e->{'value'} =~ /^\s*(\w+)\s*$/ ) {
+            my $user = RT::User->new( RT->SystemUser );
+            $user->Load( $1 );
+            if ($user->id) {
+                push @addresses, Email::Address->new($user->Name, $user->EmailAddress);
+            } else {
+                $logger->($e->{'value'} ." is not a valid email address and is not user name");
+            }
         } else {
-            $RT::Logger->error("Unable to parse an email address from $address_string: $msg");
+            $logger->($e->{'value'} ." is not a valid email address");
         }
-    } else {
-        @addresses = Email::Address->parse($address_string);
     }
-
     return @addresses;
-
 }
 
 =head2 RescueOutlook 
diff --git a/lib/RT/I18N.pm b/lib/RT/I18N.pm
index 0e75b9f..65ae627 100644
--- a/lib/RT/I18N.pm
+++ b/lib/RT/I18N.pm
@@ -295,14 +295,65 @@ sub DecodeMIMEWordsToEncoding {
     my $str = shift;
     my $to_charset = _CanonicalizeCharset(shift);
     my $field = shift || '';
+    $RT::Logger->warning(
+        "DecodeMIMEWordsToEncoding was called without field name."
+        ."It's known to cause troubles with decoding fields properly."
+    ) unless $field;
+
+    # XXX TODO: RT doesn't currently do the right thing with mime-encoded headers
+    # We _should_ be preserving them encoded until after parsing is completed and
+    # THEN undo the mime-encoding.
+    #
+    # This routine should be translating the existing mimeencoding to utf8 but leaving
+    # things encoded.
+    #
+    # It's legal for headers to contain mime-encoded commas and semicolons which
+    # should not be treated as address separators. (Encoding == quoting here)
+    #
+    # until this is fixed, we must escape any string containing a comma or semicolon
+    # this is only a bandaid
+
+    # Some _other_ MUAs encode quotes _already_, and double quotes
+    # confuse us a lot, so only quote it if it isn't quoted
+    # already.
 
     # handle filename*=ISO-8859-1''%74%E9%73%74%2E%74%78%74, parameter value
     # continuations, and similar syntax from RFC 2231
-    if ($field =~ /^Content-(Type|Disposition)/i) {
+    if ($field =~ /^Content-/i) {
         # This concatenates continued parameters and normalizes encoded params
         # to QB encoded-words which we handle below
-        $str = MIME::Field::ParamVal->parse($str)->stringify;
+        my $params = MIME::Field::ParamVal->parse_params($str);
+        foreach my $v ( values %$params ) {
+            $v = _DecodeMIMEWordsToEncoding( $v, $to_charset );
+        }
+        $str = bless({}, 'MIME::Field::ParamVal')->set($params)->stringify;
+    }
+    elsif ( $field =~ /^(?:Resent-)?(?:To|From|B?Cc|Sender|Reply-To)$/i ) {
+        my @addresses = RT::EmailParser->ParseEmailAddress( $str );
+        foreach my $address ( @addresses ) {
+            foreach my $field (qw(phrase comment)) {
+                my $v = $address->$field() or next;
+                $v = _DecodeMIMEWordsToEncoding( $v, $to_charset );
+                $address->$field($v);
+            }
+        }
+        $str = join ', ', map $_->format, @addresses;
     }
+    else {
+        $str = _DecodeMIMEWordsToEncoding( $str, $to_charset );
+    }
+
+
+    # We might have \n without trailing whitespace, which will result in
+    # invalid headers.
+    $str =~ s/\n//g;
+
+    return ($str)
+}
+
+sub _DecodeMIMEWordsToEncoding {
+    my $str = shift;
+    my $to_charset = shift;
 
     # Pre-parse by removing all whitespace between encoded words
     my $encoded_word = qr/
@@ -330,79 +381,51 @@ sub DecodeMIMEWordsToEncoding {
                          $encoded_word
                          ([^=]*)        # trailing
                         /xgcs;
+    return $str unless @list;
+
+    # add everything that hasn't matched to the end of the latest
+    # string in array this happen when we have 'key="=?encoded?="; key="plain"'
+    $list[-1] .= substr($str, pos $str);
+
+    $str = '';
+    while (@list) {
+        my ($prefix, $charset, $encoding, $enc_str, $trailing) =
+                splice @list, 0, 5;
+        $charset  = _CanonicalizeCharset($charset);
+        $encoding = lc $encoding;
+
+        $trailing =~ s/\s?\t?$//;               # Observed from Outlook Express
+
+        if ( $encoding eq 'q' ) {
+            use MIME::QuotedPrint;
+            $enc_str =~ tr/_/ /;		# Observed from Outlook Express
+            $enc_str = decode_qp($enc_str);
+        } elsif ( $encoding eq 'b' ) {
+            use MIME::Base64;
+            $enc_str = decode_base64($enc_str);
+        } else {
+            $RT::Logger->warning("Incorrect encoding '$encoding' in '$str', "
+                ."only Q(uoted-printable) and B(ase64) are supported");
+        }
 
-    if ( @list ) {
-        # add everything that hasn't matched to the end of the latest
-        # string in array this happen when we have 'key="=?encoded?="; key="plain"'
-        $list[-1] .= substr($str, pos $str);
-
-        $str = "";
-        while (@list) {
-            my ($prefix, $charset, $encoding, $enc_str, $trailing) =
-                    splice @list, 0, 5;
-            $charset  = _CanonicalizeCharset($charset);
-            $encoding = lc $encoding;
-
-            $trailing =~ s/\s?\t?$//;               # Observed from Outlook Express
-
-            if ( $encoding eq 'q' ) {
-                use MIME::QuotedPrint;
-                $enc_str =~ tr/_/ /;		# Observed from Outlook Express
-                $enc_str = decode_qp($enc_str);
-            } elsif ( $encoding eq 'b' ) {
-                use MIME::Base64;
-                $enc_str = decode_base64($enc_str);
+        # now we have got a decoded subject, try to convert into the encoding
+        if ( $charset ne $to_charset || $charset =~ /^utf-?8(?:-strict)?$/i ) {
+            if ( Encode::find_encoding($charset) ) {
+                Encode::from_to( $enc_str, $charset, $to_charset );
             } else {
-                $RT::Logger->warning("Incorrect encoding '$encoding' in '$str', "
-                    ."only Q(uoted-printable) and B(ase64) are supported");
-            }
-
-            # now we have got a decoded subject, try to convert into the encoding
-            if ( $charset ne $to_charset || $charset =~ /^utf-?8(?:-strict)?$/i ) {
-                if ( Encode::find_encoding($charset) ) {
-                    Encode::from_to( $enc_str, $charset, $to_charset );
-                } else {
-                    $RT::Logger->warning("Charset '$charset' is not supported");
-                    $enc_str =~ s/[^[:print:]]/\357\277\275/g;
-                    Encode::from_to( $enc_str, 'UTF-8', $to_charset )
-                        unless $to_charset eq 'utf-8';
-                }
+                $RT::Logger->warning("Charset '$charset' is not supported");
+                $enc_str =~ s/[^[:print:]]/\357\277\275/g;
+                Encode::from_to( $enc_str, 'UTF-8', $to_charset )
+                    unless $to_charset eq 'utf-8';
             }
-
-            # XXX TODO: RT doesn't currently do the right thing with mime-encoded headers
-            # We _should_ be preserving them encoded until after parsing is completed and
-            # THEN undo the mime-encoding.
-            #
-            # This routine should be translating the existing mimeencoding to utf8 but leaving
-            # things encoded.
-            #
-            # It's legal for headers to contain mime-encoded commas and semicolons which
-            # should not be treated as address separators. (Encoding == quoting here)
-            #
-            # until this is fixed, we must escape any string containing a comma or semicolon
-            # this is only a bandaid
-
-            # Some _other_ MUAs encode quotes _already_, and double quotes
-            # confuse us a lot, so only quote it if it isn't quoted
-            # already.
-            $enc_str = qq{"$enc_str"}
-                if $enc_str =~ /[,;]/
-                and $enc_str !~ /^".*"$/
-                and (!$field || $field =~ /^(?:To$|From$|B?Cc$|Content-)/i);
-
-            $str .= $prefix . $enc_str . $trailing;
         }
+        $str .= $prefix . $enc_str . $trailing;
     }
 
-    # We might have \n without trailing whitespace, which will result in
-    # invalid headers.
-    $str =~ s/\n//g;
-
     return ($str)
 }
 
 
-
 =head2 _FindOrGuessCharset MIME::Entity, $head_only
 
 When handed a MIME::Entity will first attempt to read what charset the message is encoded in. Failing that, will use Encode::Guess to try to figure it out
diff --git a/sbin/rt-test-dependencies.in b/sbin/rt-test-dependencies.in
index 26593d9..6961551 100644
--- a/sbin/rt-test-dependencies.in
+++ b/sbin/rt-test-dependencies.in
@@ -200,9 +200,10 @@ Sys::Syslog 0.16
 Locale::Maketext 1.06
 Locale::Maketext::Lexicon 0.32
 Locale::Maketext::Fuzzy
-MIME::Entity 5.425
+MIME::Entity 5.504
 Mail::Mailer 1.57
-Email::Address
+Email::Address 1.897
+Email::Address::List
 Text::Wrapper 
 Time::ParseDate
 Time::HiRes 
diff --git a/t/mail/dashboards.t b/t/mail/dashboards.t
index edd4553..fe317d4 100644
--- a/t/mail/dashboards.t
+++ b/t/mail/dashboards.t
@@ -101,7 +101,7 @@ sub produces_dashboard_mail_ok { # {{{
 
     my $mail = parse_mail( $mails[0] );
     is($mail->head->get('Subject'), $subject);
-    is($mail->head->get('From'), "root\n");
+    is($mail->head->get('From'), qq{"root" <root\@localhost>\n});
     is($mail->head->get('X-RT-Dashboard-Id'), "$dashboard_id\n");
     is($mail->head->get('X-RT-Dashboard-Subscription-Id'), "$subscription_id\n");
 
diff --git a/t/mail/mime_decoding.t b/t/mail/mime_decoding.t
index 4b3e3c0..311903f 100644
--- a/t/mail/mime_decoding.t
+++ b/t/mail/mime_decoding.t
@@ -12,6 +12,11 @@ diag q{'=' char in a leading part before an encoded part};
         'key="plain"; key="мой_файл.bin"',
         "right decoding"
     );
+    is(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'content-disposition'),
+        'key="plain"; key="мой_файл.bin"',
+        "right decoding"
+    );
 }
 
 diag q{not compliant with standards, but MUAs send such field when attachment has non-ascii in name};
@@ -22,6 +27,11 @@ diag q{not compliant with standards, but MUAs send such field when attachment ha
         'attachment; filename="мой_файл.bin"',
         "right decoding"
     );
+    is(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'content-disposition'),
+        'attachment; filename="мой_файл.bin"',
+        "right decoding"
+    );
 }
 
 diag q{'=' char in a trailing part after an encoded part};
@@ -32,6 +42,11 @@ diag q{'=' char in a trailing part after an encoded part};
         'attachment; filename="мой_файл.bin"; some_prop="value"',
         "right decoding"
     );
+    is(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'content-disposition'),
+        'attachment; filename="мой_файл.bin"; some_prop="value"',
+        "right decoding"
+    );
 }
 
 diag q{regression test for #5248 from rt3.fsck.com};
@@ -39,7 +54,7 @@ diag q{regression test for #5248 from rt3.fsck.com};
     my $str = qq{Subject: =?ISO-8859-1?Q?Re=3A_=5BXXXXXX=23269=5D_=5BComment=5D_Frag?=}
         . qq{\n =?ISO-8859-1?Q?e_zu_XXXXXX--xxxxxx_/_Xxxxx=FCxxxxxxxxxx?=};
     is(
-        RT::I18N::DecodeMIMEWordsToUTF8($str),
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Subject'),
         qq{Subject: Re: [XXXXXX#269] [Comment] Frage zu XXXXXX--xxxxxx / Xxxxxüxxxxxxxxxx},
         "right decoding"
     );
@@ -53,6 +68,11 @@ diag q{newline and encoded file name};
         qq{application/vnd.ms-powerpoint;\tname="Main presentation.ppt"},
         "right decoding"
     );
+    is(
+        RT::I18N::DecodeMIMEWordsToUTF8($str,'content-type'),
+        qq{application/vnd.ms-powerpoint; name="Main presentation.ppt"},
+        "right decoding"
+    );
 }
 
 diag q{rfc2231};

commit ff728bc9082c87d3d9448270c6aa85a7fcaa4000
Author: Ruslan Zakirov <ruz at bestpractical.com>
Date:   Sat Nov 17 22:20:47 2012 +0400

    deal with hidden quotes within encoded-word
    
    After decoding a part (a param value or display name)
    may contain a quoted string inside, we de-quote and
    de-escape it just to avoid useless quotes.

diff --git a/lib/RT/I18N.pm b/lib/RT/I18N.pm
index 65ae627..6e7354d 100644
--- a/lib/RT/I18N.pm
+++ b/lib/RT/I18N.pm
@@ -325,6 +325,8 @@ sub DecodeMIMEWordsToEncoding {
         my $params = MIME::Field::ParamVal->parse_params($str);
         foreach my $v ( values %$params ) {
             $v = _DecodeMIMEWordsToEncoding( $v, $to_charset );
+            # de-quote in case those were hidden inside encoded part
+            $v =~ s/\\(.)/$1/g if $v =~ s/^"(.*)"$/$1/;
         }
         $str = bless({}, 'MIME::Field::ParamVal')->set($params)->stringify;
     }
@@ -334,6 +336,10 @@ sub DecodeMIMEWordsToEncoding {
             foreach my $field (qw(phrase comment)) {
                 my $v = $address->$field() or next;
                 $v = _DecodeMIMEWordsToEncoding( $v, $to_charset );
+                if ( $field eq 'phrase' ) {
+                    # de-quote in case quoted value were hidden inside encoded part
+                    $v =~ s/\\(.)/$1/g if $v =~ s/^"(.*)"$/$1/;
+                }
                 $address->$field($v);
             }
         }

commit 6c78d437d02f4fc55547d17cfd0aaa3a2b2e489e
Author: Thomas Sibley <trs at bestpractical.com>
Date:   Fri Oct 26 15:50:53 2012 -0700

    test more MIME word decoding cases

diff --git a/t/mail/mime_decoding.t b/t/mail/mime_decoding.t
index 311903f..afb2032 100644
--- a/t/mail/mime_decoding.t
+++ b/t/mail/mime_decoding.t
@@ -1,6 +1,7 @@
 use strict;
 use warnings;
-use RT::Test nodb => 1, tests => 13;
+use RT::Test nodb => 1, tests => undef;
+use Test::LongString;
 
 use_ok('RT::I18N');
 
@@ -116,7 +117,6 @@ diag q{canonicalize mime word encodings like gb2312};
     );
 }
 
-
 diag q{Whitespace between encoded words should be removed};
 {
     my $str = "=?utf-8?Q?=E3=82=AD?=    =?utf-8?Q?=E3=83=A3?=";
@@ -158,3 +158,63 @@ EOT
     );
 
 }
+
+diag "multiple mime words containing special chars already in quotes";
+{
+    my $str = q{attachment; filename="=?ISO-2022-JP?B?Mi4bJEIlSyVlITwlOSVqJWohPCU5GyhC?= =?ISO-2022-JP?B?LnBkZg==?="};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="2.ニュースリリース.pdf"},
+        "base64"
+    );
+
+    $str = q{attachment; filename="=?UTF-8?Q?2=2E=E3=83=8B=E3=83=A5=E3=83=BC=E3=82=B9=E3=83=AA=E3=83=AA?= =?UTF-8?Q?=E3=83=BC=E3=82=B9=2Epdf?="};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="2.ニュースリリース.pdf"},
+        "QP"
+    );
+}
+
+diag "mime word combined with text in quoted filename property";
+{
+    my $str = q{attachment; filename="=?UTF-8?B?Q2VjaSBuJ2VzdCBwYXMgdW5l?= pipe.pdf"};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="Ceci n'est pas une pipe.pdf"},
+        "base64"
+    );
+
+    $str = q{attachment; filename="=?UTF-8?B?Q2VjaSBuJ2VzdCBwYXMgdW5lLi4u?= pipe.pdf"};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="Ceci n'est pas une... pipe.pdf"},
+        "base64"
+    );
+
+    $str = q{attachment; filename="=?UTF-8?Q?Ceci n'est pas une?= pipe.pdf"};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="Ceci n'est pas une pipe.pdf"},
+        "QP"
+    );
+
+    $str = q{attachment; filename="=?UTF-8?Q?Ceci n'est pas une...?= pipe.pdf"};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="Ceci n'est pas une... pipe.pdf"},
+        "QP"
+    );
+}
+
+diag "quotes in filename";
+{
+    my $str = q{attachment; filename="=?UTF-8?B?YSAicXVvdGVkIiBmaWxl?="};
+    is_string(
+        RT::I18N::DecodeMIMEWordsToUTF8($str, 'Content-Disposition'),
+        q{attachment; filename="a \"quoted\" file"},
+        "quoted filename correctly decoded"
+    );
+}
+
+done_testing;

-----------------------------------------------------------------------


More information about the Rt-commit mailing list