From 8e274f08e799aa15fc8ee4296817f26eb2cea096 Mon Sep 17 00:00:00 2001 From: Ben Darnell Date: Sat, 6 Aug 2011 13:23:35 -0700 Subject: [PATCH] Speed up _convert_header_value --- tornado/web.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/tornado/web.py b/tornado/web.py index 4ea6dc79..eb344158 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -243,21 +243,23 @@ class RequestHandler(object): self._list_headers.append((name, self._convert_header_value(value))) def _convert_header_value(self, value): - if isinstance(value, (unicode, bytes_type)): - value = utf8(value) - # If \n is allowed into the header, it is possible to inject - # additional headers or split the request. Also cap length to - # prevent obviously erroneous values. - safe_value = re.sub(b(r"[\x00-\x1f]"), b(" "), value)[:4000] - if safe_value != value: - raise ValueError("Unsafe header value %r", value) + if isinstance(value, bytes_type): + pass + elif isinstance(value, unicode): + value = value.encode('utf-8') + elif isinstance(value, (int, long)): + # return immediately since we know the converted value will be safe + return str(value) elif isinstance(value, datetime.datetime): t = calendar.timegm(value.utctimetuple()) - value = email.utils.formatdate(t, localtime=False, usegmt=True) - elif isinstance(value, int) or isinstance(value, long): - value = str(value) + return email.utils.formatdate(t, localtime=False, usegmt=True) else: raise TypeError("Unsupported header value %r" % value) + # If \n is allowed into the header, it is possible to inject + # additional headers or split the request. Also cap length to + # prevent obviously erroneous values. + if len(value) > 4000 or re.match(b(r"[\x00-\x1f]"), value): + raise ValueError("Unsafe header value %r", value) return value