_headers.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import re
  2. from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
  3. from ._abnf import field_name, field_value
  4. from ._util import bytesify, LocalProtocolError, validate
  5. if TYPE_CHECKING:
  6. from ._events import Request
  7. try:
  8. from typing import Literal
  9. except ImportError:
  10. from typing_extensions import Literal # type: ignore
  11. # Facts
  12. # -----
  13. #
  14. # Headers are:
  15. # keys: case-insensitive ascii
  16. # values: mixture of ascii and raw bytes
  17. #
  18. # "Historically, HTTP has allowed field content with text in the ISO-8859-1
  19. # charset [ISO-8859-1], supporting other charsets only through use of
  20. # [RFC2047] encoding. In practice, most HTTP header field values use only a
  21. # subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD
  22. # limit their field values to US-ASCII octets. A recipient SHOULD treat other
  23. # octets in field content (obs-text) as opaque data."
  24. # And it deprecates all non-ascii values
  25. #
  26. # Leading/trailing whitespace in header names is forbidden
  27. #
  28. # Values get leading/trailing whitespace stripped
  29. #
  30. # Content-Disposition actually needs to contain unicode semantically; to
  31. # accomplish this it has a terrifically weird way of encoding the filename
  32. # itself as ascii (and even this still has lots of cross-browser
  33. # incompatibilities)
  34. #
  35. # Order is important:
  36. # "a proxy MUST NOT change the order of these field values when forwarding a
  37. # message"
  38. # (and there are several headers where the order indicates a preference)
  39. #
  40. # Multiple occurences of the same header:
  41. # "A sender MUST NOT generate multiple header fields with the same field name
  42. # in a message unless either the entire field value for that header field is
  43. # defined as a comma-separated list [or the header is Set-Cookie which gets a
  44. # special exception]" - RFC 7230. (cookies are in RFC 6265)
  45. #
  46. # So every header aside from Set-Cookie can be merged by b", ".join if it
  47. # occurs repeatedly. But, of course, they can't necessarily be split by
  48. # .split(b","), because quoting.
  49. #
  50. # Given all this mess (case insensitive, duplicates allowed, order is
  51. # important, ...), there doesn't appear to be any standard way to handle
  52. # headers in Python -- they're almost like dicts, but... actually just
  53. # aren't. For now we punt and just use a super simple representation: headers
  54. # are a list of pairs
  55. #
  56. # [(name1, value1), (name2, value2), ...]
  57. #
  58. # where all entries are bytestrings, names are lowercase and have no
  59. # leading/trailing whitespace, and values are bytestrings with no
  60. # leading/trailing whitespace. Searching and updating are done via naive O(n)
  61. # methods.
  62. #
  63. # Maybe a dict-of-lists would be better?
  64. _content_length_re = re.compile(rb"[0-9]+")
  65. _field_name_re = re.compile(field_name.encode("ascii"))
  66. _field_value_re = re.compile(field_value.encode("ascii"))
  67. class Headers(Sequence[Tuple[bytes, bytes]]):
  68. """
  69. A list-like interface that allows iterating over headers as byte-pairs
  70. of (lowercased-name, value).
  71. Internally we actually store the representation as three-tuples,
  72. including both the raw original casing, in order to preserve casing
  73. over-the-wire, and the lowercased name, for case-insensitive comparisions.
  74. r = Request(
  75. method="GET",
  76. target="/",
  77. headers=[("Host", "example.org"), ("Connection", "keep-alive")],
  78. http_version="1.1",
  79. )
  80. assert r.headers == [
  81. (b"host", b"example.org"),
  82. (b"connection", b"keep-alive")
  83. ]
  84. assert r.headers.raw_items() == [
  85. (b"Host", b"example.org"),
  86. (b"Connection", b"keep-alive")
  87. ]
  88. """
  89. __slots__ = "_full_items"
  90. def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None:
  91. self._full_items = full_items
  92. def __bool__(self) -> bool:
  93. return bool(self._full_items)
  94. def __eq__(self, other: object) -> bool:
  95. return list(self) == list(other) # type: ignore
  96. def __len__(self) -> int:
  97. return len(self._full_items)
  98. def __repr__(self) -> str:
  99. return "<Headers(%s)>" % repr(list(self))
  100. def __getitem__(self, idx: int) -> Tuple[bytes, bytes]: # type: ignore[override]
  101. _, name, value = self._full_items[idx]
  102. return (name, value)
  103. def raw_items(self) -> List[Tuple[bytes, bytes]]:
  104. return [(raw_name, value) for raw_name, _, value in self._full_items]
  105. HeaderTypes = Union[
  106. List[Tuple[bytes, bytes]],
  107. List[Tuple[bytes, str]],
  108. List[Tuple[str, bytes]],
  109. List[Tuple[str, str]],
  110. ]
  111. @overload
  112. def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
  113. ...
  114. @overload
  115. def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
  116. ...
  117. @overload
  118. def normalize_and_validate(
  119. headers: Union[Headers, HeaderTypes], _parsed: bool = False
  120. ) -> Headers:
  121. ...
  122. def normalize_and_validate(
  123. headers: Union[Headers, HeaderTypes], _parsed: bool = False
  124. ) -> Headers:
  125. new_headers = []
  126. seen_content_length = None
  127. saw_transfer_encoding = False
  128. for name, value in headers:
  129. # For headers coming out of the parser, we can safely skip some steps,
  130. # because it always returns bytes and has already run these regexes
  131. # over the data:
  132. if not _parsed:
  133. name = bytesify(name)
  134. value = bytesify(value)
  135. validate(_field_name_re, name, "Illegal header name {!r}", name)
  136. validate(_field_value_re, value, "Illegal header value {!r}", value)
  137. assert isinstance(name, bytes)
  138. assert isinstance(value, bytes)
  139. raw_name = name
  140. name = name.lower()
  141. if name == b"content-length":
  142. lengths = {length.strip() for length in value.split(b",")}
  143. if len(lengths) != 1:
  144. raise LocalProtocolError("conflicting Content-Length headers")
  145. value = lengths.pop()
  146. validate(_content_length_re, value, "bad Content-Length")
  147. if seen_content_length is None:
  148. seen_content_length = value
  149. new_headers.append((raw_name, name, value))
  150. elif seen_content_length != value:
  151. raise LocalProtocolError("conflicting Content-Length headers")
  152. elif name == b"transfer-encoding":
  153. # "A server that receives a request message with a transfer coding
  154. # it does not understand SHOULD respond with 501 (Not
  155. # Implemented)."
  156. # https://tools.ietf.org/html/rfc7230#section-3.3.1
  157. if saw_transfer_encoding:
  158. raise LocalProtocolError(
  159. "multiple Transfer-Encoding headers", error_status_hint=501
  160. )
  161. # "All transfer-coding names are case-insensitive"
  162. # -- https://tools.ietf.org/html/rfc7230#section-4
  163. value = value.lower()
  164. if value != b"chunked":
  165. raise LocalProtocolError(
  166. "Only Transfer-Encoding: chunked is supported",
  167. error_status_hint=501,
  168. )
  169. saw_transfer_encoding = True
  170. new_headers.append((raw_name, name, value))
  171. else:
  172. new_headers.append((raw_name, name, value))
  173. return Headers(new_headers)
  174. def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
  175. # Should only be used for headers whose value is a list of
  176. # comma-separated, case-insensitive values.
  177. #
  178. # The header name `name` is expected to be lower-case bytes.
  179. #
  180. # Connection: meets these criteria (including cast insensitivity).
  181. #
  182. # Content-Length: technically is just a single value (1*DIGIT), but the
  183. # standard makes reference to implementations that do multiple values, and
  184. # using this doesn't hurt. Ditto, case insensitivity doesn't things either
  185. # way.
  186. #
  187. # Transfer-Encoding: is more complex (allows for quoted strings), so
  188. # splitting on , is actually wrong. For example, this is legal:
  189. #
  190. # Transfer-Encoding: foo; options="1,2", chunked
  191. #
  192. # and should be parsed as
  193. #
  194. # foo; options="1,2"
  195. # chunked
  196. #
  197. # but this naive function will parse it as
  198. #
  199. # foo; options="1
  200. # 2"
  201. # chunked
  202. #
  203. # However, this is okay because the only thing we are going to do with
  204. # any Transfer-Encoding is reject ones that aren't just "chunked", so
  205. # both of these will be treated the same anyway.
  206. #
  207. # Expect: the only legal value is the literal string
  208. # "100-continue". Splitting on commas is harmless. Case insensitive.
  209. #
  210. out: List[bytes] = []
  211. for _, found_name, found_raw_value in headers._full_items:
  212. if found_name == name:
  213. found_raw_value = found_raw_value.lower()
  214. for found_split_value in found_raw_value.split(b","):
  215. found_split_value = found_split_value.strip()
  216. if found_split_value:
  217. out.append(found_split_value)
  218. return out
  219. def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
  220. # The header name `name` is expected to be lower-case bytes.
  221. #
  222. # Note that when we store the header we use title casing for the header
  223. # names, in order to match the conventional HTTP header style.
  224. #
  225. # Simply calling `.title()` is a blunt approach, but it's correct
  226. # here given the cases where we're using `set_comma_header`...
  227. #
  228. # Connection, Content-Length, Transfer-Encoding.
  229. new_headers: List[Tuple[bytes, bytes]] = []
  230. for found_raw_name, found_name, found_raw_value in headers._full_items:
  231. if found_name != name:
  232. new_headers.append((found_raw_name, found_raw_value))
  233. for new_value in new_values:
  234. new_headers.append((name.title(), new_value))
  235. return normalize_and_validate(new_headers)
  236. def has_expect_100_continue(request: "Request") -> bool:
  237. # https://tools.ietf.org/html/rfc7231#section-5.1.1
  238. # "A server that receives a 100-continue expectation in an HTTP/1.0 request
  239. # MUST ignore that expectation."
  240. if request.http_version < b"1.1":
  241. return False
  242. expect = get_comma_header(request.headers, b"expect")
  243. return b"100-continue" in expect