From 7e6069acfdc4a93a88f9aa5d313293cc8e85bb41 Mon Sep 17 00:00:00 2001 From: Dong-hee Na Date: Sun, 17 Jun 2018 20:32:08 +0900 Subject: [PATCH] bpo-33529: Fix Infinite loop on folding email if headers has non_ascii --- Lib/email/_header_value_parser.py | 5 +++-- Lib/test/test_email/test_policy.py | 6 ++++++ .../next/Library/2018-06-17-20-28-27.bpo-33529.uoCjry.rst | 2 ++ 3 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2018-06-17-20-28-27.bpo-33529.uoCjry.rst diff --git a/Lib/email/_header_value_parser.py b/Lib/email/_header_value_parser.py index d8becee19892c8..ab40d11ebe9d27 100644 --- a/Lib/email/_header_value_parser.py +++ b/Lib/email/_header_value_parser.py @@ -2727,13 +2727,14 @@ def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset): first_part = to_encode[:text_space] ew = _ew.encode(first_part, charset=encode_as) excess = len(ew) - remaining_space + encoded_first_part = ew.split('?')[3] if excess > 0: # encode always chooses the shortest encoding, so this # is guaranteed to fit at this point. - first_part = first_part[:-excess] + encoded_first_part = encoded_first_part[:-excess] ew = _ew.encode(first_part) lines[-1] += ew - to_encode = to_encode[len(first_part):] + to_encode = to_encode[len(encoded_first_part):] if to_encode: lines.append(' ') new_last_ew = len(lines[-1]) diff --git a/Lib/test/test_email/test_policy.py b/Lib/test/test_email/test_policy.py index 8fecb8a5fcd5a8..3634d19c9511e8 100644 --- a/Lib/test/test_email/test_policy.py +++ b/Lib/test/test_email/test_policy.py @@ -237,6 +237,12 @@ def test_adding_default_policies_preserves_default_factory(self): email.policy.EmailPolicy.header_factory) self.assertEqual(newpolicy.__dict__, {'raise_on_defect': True}) + def test_non_ascii_policy(self): + policy = email.policy.default + msg = email.message.EmailMessage() + msg["Subject"] = "รก"*100 + res = policy.fold("Subject", msg["Subject"]) + self.assertEqual(len(res), 304) # XXX: Need subclassing tests. # For adding subclassed objects, make sure the usual rules apply (subclass # wins), but that the order still works (right overrides left). diff --git a/Misc/NEWS.d/next/Library/2018-06-17-20-28-27.bpo-33529.uoCjry.rst b/Misc/NEWS.d/next/Library/2018-06-17-20-28-27.bpo-33529.uoCjry.rst new file mode 100644 index 00000000000000..8a201a25d4da32 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-06-17-20-28-27.bpo-33529.uoCjry.rst @@ -0,0 +1,2 @@ +Fix infinite loop on folding email if headers has no spaces with non-ascii +characters and a size of value is over 78