[1.8.x] Fixed #20889 -- Prevented BadHeaderError when Python inserts newline

Workaround for http://bugs.python.org/issue20747.
In some corner cases, Python 2 inserts a newline in a header value
despite `maxlinelen` passed in Header constructor.
Thanks Tim Graham for the review.
Backport of efb1f99f94 from master.
This commit is contained in:
Claude Paroz 2015-02-18 10:09:33 +01:00
parent 66d37e593c
commit 84e7fec88d
2 changed files with 6 additions and 2 deletions

View File

@ -166,6 +166,9 @@ class HttpResponseBase(six.Iterator):
""" """
if not isinstance(value, (bytes, six.text_type)): if not isinstance(value, (bytes, six.text_type)):
value = str(value) value = str(value)
if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
isinstance(value, six.text_type) and ('\n' in value or '\r' in value)):
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
try: try:
if six.PY3: if six.PY3:
if isinstance(value, str): if isinstance(value, str):
@ -188,8 +191,6 @@ class HttpResponseBase(six.Iterator):
else: else:
e.reason += ', HTTP response headers must be in %s format' % charset e.reason += ', HTTP response headers must be in %s format' % charset
raise raise
if str('\n') in value or str('\r') in value:
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
return value return value
def __setitem__(self, header, value): def __setitem__(self, header, value):

View File

@ -306,6 +306,9 @@ class HttpResponseTests(unittest.TestCase):
f = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88'.encode('latin-1') f = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88'.encode('latin-1')
f = f.decode('utf-8') f = f.decode('utf-8')
h['Content-Disposition'] = 'attachment; filename="%s"' % f h['Content-Disposition'] = 'attachment; filename="%s"' % f
# This one is triggering http://bugs.python.org/issue20747, that is Python
# will itself insert a newline in the header
h['Content-Disposition'] = 'attachement; filename="EdelRot_Blu\u0308te (3)-0.JPG"'
def test_newlines_in_headers(self): def test_newlines_in_headers(self):
# Bug #10188: Do not allow newlines in headers (CR or LF) # Bug #10188: Do not allow newlines in headers (CR or LF)