Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Lib/email/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
NLCRE = re.compile(r'\r\n|\r|\n')
fcre = re.compile(r'^From ', re.MULTILINE)
NEWLINE_WITHOUT_FWSP = re.compile(r'\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]')
NEWLINE_WITHOUT_FWSP_BYTES = re.compile(br'\r\n[^ \t]|\r[^ \n\t]|\n[^ \t]')


class Generator:
Expand Down Expand Up @@ -429,7 +430,16 @@ def _write_headers(self, msg):
# This is almost the same as the string version, except for handling
# strings with 8bit bytes.
for h, v in msg.raw_items():
self._fp.write(self.policy.fold_binary(h, v))
folded = self.policy.fold_binary(h, v)
if self.policy.verify_generated_headers:
linesep = self.policy.linesep.encode()
if not folded.endswith(linesep):
raise HeaderWriteError(
f'folded header does not end with {linesep!r}: {folded!r}')
if NEWLINE_WITHOUT_FWSP_BYTES.search(folded.removesuffix(linesep)):
raise HeaderWriteError(
f'folded header contains newline: {folded!r}')
self._fp.write(folded)
# A blank line always separates headers from body
self.write(self._NL)

Expand Down
2 changes: 2 additions & 0 deletions Lib/test/test_email/test_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,8 @@ def fold(self, **kwargs):

with self.assertRaises(email.errors.HeaderWriteError):
message.as_string()
with self.assertRaises(email.errors.HeaderWriteError):
message.as_bytes()
Comment thread
sethmlarson marked this conversation as resolved.


class TestBytesGenerator(TestGeneratorBase, TestEmailBase):
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_email/test_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,10 @@ def fold(self, **kwargs):
message.as_string(),
f"{text}\nBody",
)
self.assertEqual(
Comment thread
sethmlarson marked this conversation as resolved.
message.as_bytes(),
f"{text}\nBody".encode(),
)

# XXX: Need subclassing tests.
# For adding subclassed objects, make sure the usual rules apply (subclass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:mod:`~email.generator.BytesGenerator` will now refuse to serialize (write) headers
that are unsafely folded or delimited; see
:attr:`~email.policy.Policy.verify_generated_headers`. (Contributed by Bas
Bloemsaat and Petr Viktorin in :gh:`121650`).
Loading