Skip to content

Commit cf7279a

Browse files
committed
gh-136063: Fix quadratic complexity in email.header.decode_header
1 parent 64c20ff commit cf7279a

3 files changed

Lines changed: 71 additions & 30 deletions

File tree

‎Lib/email/header.py‎

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -87,29 +87,34 @@ def decode_header(header):
8787
# (encoded_string, encoding, charset). For unencoded strings, the last
8888
# two parts will be None.
8989
words = []
90+
# Whether the word that originally preceded words[-1] was encoded.
91+
# Whitespace between two encoded words is dropped (see below); the
92+
# check must use the original neighbours, not those left after a drop.
93+
prev_encoded = False
9094
for line in header.splitlines():
91-
parts = ecre.split(line)
92-
first = True
93-
while parts:
94-
unencoded = parts.pop(0)
95-
if first:
96-
unencoded = unencoded.lstrip()
97-
first = False
95+
# ecre has three groups, so split() returns an unencoded chunk
96+
# followed by zero or more (charset, encoding, encoded, unencoded)
97+
# groups. Iterate rather than popping from the front of the list,
98+
# which is quadratic in the number of encoded words.
99+
parts = iter(ecre.split(line))
100+
unencoded = next(parts).lstrip()
101+
while True:
98102
if unencoded:
103+
prev_encoded = bool(words) and bool(words[-1][1])
99104
words.append((unencoded, None, None))
100-
if parts:
101-
charset = parts.pop(0).lower()
102-
encoding = parts.pop(0).lower()
103-
encoded = parts.pop(0)
104-
words.append((encoded, encoding, charset))
105-
# Now loop over words and remove words that consist of whitespace
106-
# between two encoded strings.
107-
droplist = []
108-
for n, w in enumerate(words):
109-
if n>1 and w[1] and words[n-2][1] and words[n-1][0].isspace():
110-
droplist.append(n-1)
111-
for d in reversed(droplist):
112-
del words[d]
105+
charset = next(parts, None)
106+
if charset is None:
107+
break
108+
encoding = next(parts).lower()
109+
encoded = next(parts)
110+
last_encoded = bool(words) and bool(words[-1][1])
111+
# Remove a word that consists of whitespace between two
112+
# encoded strings.
113+
if prev_encoded and words[-1][0].isspace():
114+
words.pop()
115+
prev_encoded = last_encoded
116+
words.append((encoded, encoding, charset.lower()))
117+
unencoded = next(parts)
113118

114119
# The next step is to decode each encoded word by applying the reverse
115120
# base64 or quopri transformation. decoded_words is now a list of the
@@ -135,27 +140,34 @@ def decode_header(header):
135140
else:
136141
raise AssertionError('Unexpected encoding: ' + encoding)
137142
# Now convert all words to bytes and collapse consecutive runs of
138-
# similarly encoded words.
143+
# similarly encoded words. Collect each run in a list and join once,
144+
# since repeated bytes concatenation is quadratic.
139145
collapsed = []
140-
last_word = last_charset = None
146+
run = None
147+
last_charset = None
141148
for word, charset in decoded_words:
142149
if isinstance(word, str):
143150
word = bytes(word, 'raw-unicode-escape')
144-
if last_word is None:
145-
last_word = word
151+
if run is None:
152+
run = [word]
146153
last_charset = charset
147154
elif charset != last_charset:
148-
collapsed.append((last_word, last_charset))
149-
last_word = word
155+
collapsed.append((_join_run(run, last_charset), last_charset))
156+
run = [word]
150157
last_charset = charset
151-
elif last_charset is None:
152-
last_word += BSPACE + word
153158
else:
154-
last_word += word
155-
collapsed.append((last_word, last_charset))
159+
run.append(word)
160+
collapsed.append((_join_run(run, last_charset) if run else None,
161+
last_charset))
156162
return collapsed
157163

158164

165+
def _join_run(run, charset):
166+
if len(run) == 1:
167+
return run[0]
168+
return (BSPACE if charset is None else b'').join(run)
169+
170+
159171
def make_header(decoded_seq, maxlinelen=None, header_name=None,
160172
continuation_ws=' '):
161173
"""Create a Header from a sequence of pairs as returned by decode_header()

‎Lib/test/test_email/test_email.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2425,6 +2425,33 @@ def test_rfc2047_with_whitespace(self):
24252425
(b' rg ', None), (b'\xe5', 'iso-8859-1'),
24262426
(b' sbord', None)])
24272427

2428+
def test_rfc2047_whitespace_between_encoded_words(self):
2429+
# Whitespace between two encoded words is dropped, judged by the
2430+
# words' original neighbours, even if a neighbour is itself an
2431+
# encoded word that decodes to whitespace.
2432+
eq = self.assertEqual
2433+
eq(decode_header('=?utf-8?q?a?= =?utf-8?q? ?==?utf-8?q?b?= '
2434+
'=?utf-8?q?c?='),
2435+
[(b'a bc', 'utf-8')])
2436+
eq(decode_header('=?utf-8?q?a?= =?utf-8?q? ?= =?utf-8?q?b?='),
2437+
[(b'a b', 'utf-8')])
2438+
eq(decode_header('x =?utf-8?q?a?= =?iso-8859-1?q?b?= '
2439+
'=?utf-8?q?c?= y'),
2440+
[(b'x ', None), (b'a', 'utf-8'), (b'b', 'iso-8859-1'),
2441+
(b'c', 'utf-8'), (b' y', None)])
2442+
2443+
def test_rfc2047_many_encoded_words(self):
2444+
# gh-136063: decoding used to take quadratic time in the number
2445+
# of encoded words.
2446+
n = 100_000
2447+
s = ' '.join(['=?utf-8?q?ab?='] * n)
2448+
self.assertEqual(decode_header(s), [(b'ab' * n, 'utf-8')])
2449+
s = ' '.join(['=?utf-8?q?ab?=', 'x'] * n)
2450+
dh = decode_header(s)
2451+
self.assertEqual(len(dh), 2 * n)
2452+
self.assertEqual(dh[:3], [(b'ab', 'utf-8'), (b' x ', None),
2453+
(b'ab', 'utf-8')])
2454+
24282455
def test_rfc2047_B_bad_padding(self):
24292456
s = '=?iso-8859-1?B?%s?='
24302457
data = [ # only test complete bytes
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:mod:`email.header`: ensure linear complexity for :func:`~email.header.decode_header`
2+
when decoding headers containing many :rfc:`2047` encoded words.

0 commit comments

Comments
 (0)