bpo-33529, email: Fix infinite loop in email header encoding (GH-1202… · python/cpython@2fef5b0 (original) (raw)

Original file line number Diff line number Diff line change
@@ -2724,16 +2724,19 @@ def _fold_as_ew(to_encode, lines, maxlen, last_ew, ew_combine_allowed, charset):
2724 2724 lines.append(' ')
2725 2725 # XXX We'll get an infinite loop here if maxlen is <= 7
2726 2726 continue
2727 -first_part = to_encode[:text_space]
2728 -ew = _ew.encode(first_part, charset=encode_as)
2729 -excess = len(ew) - remaining_space
2730 -if excess > 0:
2731 -# encode always chooses the shortest encoding, so this
2732 -# is guaranteed to fit at this point.
2733 -first_part = first_part[:-excess]
2734 -ew = _ew.encode(first_part)
2735 -lines[-1] += ew
2736 -to_encode = to_encode[len(first_part):]
2727 +
2728 +to_encode_word = to_encode[:text_space]
2729 +encoded_word = _ew.encode(to_encode_word, charset=encode_as)
2730 +excess = len(encoded_word) - remaining_space
2731 +while excess > 0:
2732 +# Since the chunk to encode is guaranteed to fit into less than 100 characters,
2733 +# shrinking it by one at a time shouldn't take long.
2734 +to_encode_word = to_encode_word[:-1]
2735 +encoded_word = _ew.encode(to_encode_word, charset=encode_as)
2736 +excess = len(encoded_word) - remaining_space
2737 +lines[-1] += encoded_word
2738 +to_encode = to_encode[len(to_encode_word):]
2739 +
2737 2740 if to_encode:
2738 2741 lines.append(' ')
2739 2742 new_last_ew = len(lines[-1])