Skip to content

Commit

Permalink
[PR #10014/50d23aee backport][3.11] Improve performance of serializin…
Browse files Browse the repository at this point in the history
…g headers (#10016)

Co-authored-by: J. Nick Koston <[email protected]>
  • Loading branch information
patchback[bot] and bdraco authored Nov 21, 2024
1 parent 5bcf07d commit ed15e88
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGES/10014.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved performance of serializing HTTP headers -- by :user:`bdraco`.
28 changes: 14 additions & 14 deletions aiohttp/_http_writer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -100,30 +100,24 @@ cdef inline int _write_str(Writer* writer, str s):
# --------------- _serialize_headers ----------------------

cdef str to_str(object s):
typ = type(s)
if typ is str:
if type(s) is str:
return <str>s
elif typ is _istr:
elif type(s) is _istr:
return PyObject_Str(s)
elif not isinstance(s, str):
raise TypeError("Cannot serialize non-str key {!r}".format(s))
else:
return str(s)


cdef void _safe_header(str string) except *:
if "\r" in string or "\n" in string:
raise ValueError(
"Newline or carriage return character detected in HTTP status message or "
"header. This is a potential security issue."
)


def _serialize_headers(str status_line, headers):
cdef Writer writer
cdef object key
cdef object val
cdef bytes ret
cdef str key_str
cdef str val_str

_init_writer(&writer)

Expand All @@ -136,16 +130,22 @@ def _serialize_headers(str status_line, headers):
raise

for key, val in headers.items():
_safe_header(to_str(key))
_safe_header(to_str(val))
key_str = to_str(key)
val_str = to_str(val)

if "\r" in key_str or "\n" in key_str or "\r" in val_str or "\n" in val_str:
raise ValueError(
"Newline or carriage return character detected in HTTP status message or "
"header. This is a potential security issue."
)

if _write_str(&writer, to_str(key)) < 0:
if _write_str(&writer, key_str) < 0:
raise
if _write_byte(&writer, b':') < 0:
raise
if _write_byte(&writer, b' ') < 0:
raise
if _write_str(&writer, to_str(val)) < 0:
if _write_str(&writer, val_str) < 0:
raise
if _write_byte(&writer, b'\r') < 0:
raise
Expand Down

0 comments on commit ed15e88

Please sign in to comment.