http_headers.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # -*- test-case-name: twisted.web.test.test_http_headers -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. An API for storing HTTP header names and values.
  6. """
  7. from typing import (
  8. AnyStr,
  9. ClassVar,
  10. Dict,
  11. Iterator,
  12. List,
  13. Mapping,
  14. Optional,
  15. Sequence,
  16. Tuple,
  17. TypeVar,
  18. Union,
  19. overload,
  20. )
  21. from twisted.python.compat import cmp, comparable
  22. from twisted.web._abnf import _istoken
  23. class InvalidHeaderName(ValueError):
  24. """
  25. HTTP header names must be tokens, per RFC 9110 section 5.1.
  26. """
  27. _T = TypeVar("_T")
  28. def _sanitizeLinearWhitespace(headerComponent: bytes) -> bytes:
  29. r"""
  30. Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header
  31. value with a single space.
  32. @param headerComponent: The header value to sanitize.
  33. @return: The sanitized header value.
  34. """
  35. return b" ".join(headerComponent.splitlines())
  36. @comparable
  37. class Headers:
  38. """
  39. Stores HTTP headers in a key and multiple value format.
  40. When passed L{str}, header names (e.g. 'Content-Type')
  41. are encoded using ISO-8859-1 and header values (e.g.
  42. 'text/html;charset=utf-8') are encoded using UTF-8. Some methods that return
  43. values will return them in the same type as the name given.
  44. If the header keys or values cannot be encoded or decoded using the rules
  45. above, using just L{bytes} arguments to the methods of this class will
  46. ensure no decoding or encoding is done, and L{Headers} will treat the keys
  47. and values as opaque byte strings.
  48. @ivar _rawHeaders: A L{dict} mapping header names as L{bytes} to L{list}s of
  49. header values as L{bytes}.
  50. """
  51. __slots__ = ["_rawHeaders"]
  52. def __init__(
  53. self,
  54. rawHeaders: Optional[Mapping[AnyStr, Sequence[AnyStr]]] = None,
  55. ) -> None:
  56. self._rawHeaders: Dict[bytes, List[bytes]] = {}
  57. if rawHeaders is not None:
  58. for name, values in rawHeaders.items():
  59. self.setRawHeaders(name, values)
  60. def __repr__(self) -> str:
  61. """
  62. Return a string fully describing the headers set on this object.
  63. """
  64. return "{}({!r})".format(
  65. self.__class__.__name__,
  66. self._rawHeaders,
  67. )
  68. def __cmp__(self, other):
  69. """
  70. Define L{Headers} instances as being equal to each other if they have
  71. the same raw headers.
  72. """
  73. if isinstance(other, Headers):
  74. return cmp(
  75. sorted(self._rawHeaders.items()), sorted(other._rawHeaders.items())
  76. )
  77. return NotImplemented
  78. def copy(self):
  79. """
  80. Return a copy of itself with the same headers set.
  81. @return: A new L{Headers}
  82. """
  83. return self.__class__(self._rawHeaders)
  84. def hasHeader(self, name: AnyStr) -> bool:
  85. """
  86. Check for the existence of a given header.
  87. @param name: The name of the HTTP header to check for.
  88. @return: C{True} if the header exists, otherwise C{False}.
  89. """
  90. return _nameEncoder.encode(name) in self._rawHeaders
  91. def removeHeader(self, name: AnyStr) -> None:
  92. """
  93. Remove the named header from this header object.
  94. @param name: The name of the HTTP header to remove.
  95. @return: L{None}
  96. """
  97. self._rawHeaders.pop(_nameEncoder.encode(name), None)
  98. def setRawHeaders(
  99. self, name: Union[str, bytes], values: Sequence[Union[str, bytes]]
  100. ) -> None:
  101. """
  102. Sets the raw representation of the given header.
  103. @param name: The name of the HTTP header to set the values for.
  104. @param values: A list of strings each one being a header value of
  105. the given name.
  106. @raise TypeError: Raised if C{values} is not a sequence of L{bytes}
  107. or L{str}, or if C{name} is not L{bytes} or L{str}.
  108. @return: L{None}
  109. """
  110. _name = _nameEncoder.encode(name)
  111. encodedValues: List[bytes] = []
  112. for v in values:
  113. if isinstance(v, str):
  114. _v = v.encode("utf8")
  115. else:
  116. _v = v
  117. encodedValues.append(_sanitizeLinearWhitespace(_v))
  118. self._rawHeaders[_name] = encodedValues
  119. def addRawHeader(self, name: Union[str, bytes], value: Union[str, bytes]) -> None:
  120. """
  121. Add a new raw value for the given header.
  122. @param name: The name of the header for which to set the value.
  123. @param value: The value to set for the named header.
  124. """
  125. self._rawHeaders.setdefault(_nameEncoder.encode(name), []).append(
  126. _sanitizeLinearWhitespace(
  127. value.encode("utf8") if isinstance(value, str) else value
  128. )
  129. )
  130. @overload
  131. def getRawHeaders(self, name: AnyStr) -> Optional[Sequence[AnyStr]]:
  132. ...
  133. @overload
  134. def getRawHeaders(self, name: AnyStr, default: _T) -> Union[Sequence[AnyStr], _T]:
  135. ...
  136. def getRawHeaders(
  137. self, name: AnyStr, default: Optional[_T] = None
  138. ) -> Union[Sequence[AnyStr], Optional[_T]]:
  139. """
  140. Returns a sequence of headers matching the given name as the raw string
  141. given.
  142. @param name: The name of the HTTP header to get the values of.
  143. @param default: The value to return if no header with the given C{name}
  144. exists.
  145. @return: If the named header is present, a sequence of its
  146. values. Otherwise, C{default}.
  147. """
  148. encodedName = _nameEncoder.encode(name)
  149. values = self._rawHeaders.get(encodedName, [])
  150. if not values:
  151. return default
  152. if isinstance(name, str):
  153. return [v.decode("utf8") for v in values]
  154. return values
  155. def getAllRawHeaders(self) -> Iterator[Tuple[bytes, Sequence[bytes]]]:
  156. """
  157. Return an iterator of key, value pairs of all headers contained in this
  158. object, as L{bytes}. The keys are capitalized in canonical
  159. capitalization.
  160. """
  161. return iter(self._rawHeaders.items())
  162. class _NameEncoder:
  163. """
  164. C{_NameEncoder} converts HTTP header names to L{bytes} and canonicalizies
  165. their capitalization.
  166. @cvar _caseMappings: A L{dict} that maps conventionally-capitalized
  167. header names to their canonicalized representation, for headers with
  168. unconventional capitalization.
  169. @cvar _canonicalHeaderCache: A L{dict} that maps header names to their
  170. canonicalized representation.
  171. """
  172. __slots__ = ("_canonicalHeaderCache",)
  173. _canonicalHeaderCache: Dict[Union[bytes, str], bytes]
  174. _caseMappings: ClassVar[Dict[bytes, bytes]] = {
  175. b"Content-Md5": b"Content-MD5",
  176. b"Dnt": b"DNT",
  177. b"Etag": b"ETag",
  178. b"P3p": b"P3P",
  179. b"Te": b"TE",
  180. b"Www-Authenticate": b"WWW-Authenticate",
  181. b"X-Xss-Protection": b"X-XSS-Protection",
  182. }
  183. _MAX_CACHED_HEADERS: ClassVar[int] = 10_000
  184. def __init__(self):
  185. self._canonicalHeaderCache = {}
  186. def encode(self, name: Union[str, bytes]) -> bytes:
  187. """
  188. Encode the name of a header (eg 'Content-Type') to an ISO-8859-1
  189. bytestring if required. It will be canonicalized to Http-Header-Case.
  190. @raises InvalidHeaderName:
  191. If the header name contains invalid characters like whitespace
  192. or NUL.
  193. @param name: An HTTP header name
  194. @return: C{name}, encoded if required, in Header-Case
  195. """
  196. if canonicalName := self._canonicalHeaderCache.get(name):
  197. return canonicalName
  198. bytes_name = name.encode("iso-8859-1") if isinstance(name, str) else name
  199. if not _istoken(bytes_name):
  200. raise InvalidHeaderName(bytes_name)
  201. result = b"-".join([word.capitalize() for word in bytes_name.split(b"-")])
  202. # Some headers have special capitalization:
  203. if result in self._caseMappings:
  204. result = self._caseMappings[result]
  205. # In general, we should only see a very small number of header
  206. # variations in the real world, so caching them is fine. However, an
  207. # attacker could generate infinite header variations to fill up RAM, so
  208. # we cap how many we cache. The performance degradation from lack of
  209. # caching won't be that bad, and legit traffic won't hit it.
  210. if len(self._canonicalHeaderCache) < self._MAX_CACHED_HEADERS:
  211. self._canonicalHeaderCache[name] = result
  212. return result
  213. _nameEncoder = _NameEncoder()
  214. """
  215. The global name encoder.
  216. """
  217. __all__ = ["Headers"]