http_headers.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. _T = TypeVar("_T")
  23. def _sanitizeLinearWhitespace(headerComponent: bytes) -> bytes:
  24. r"""
  25. Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key
  26. or value with a single space.
  27. @param headerComponent: The header key or value to sanitize.
  28. @return: The sanitized header key or value.
  29. """
  30. return b" ".join(headerComponent.splitlines())
  31. @comparable
  32. class Headers:
  33. """
  34. Stores HTTP headers in a key and multiple value format.
  35. When passed L{str}, header names (e.g. 'Content-Type')
  36. are encoded using ISO-8859-1 and header values (e.g.
  37. 'text/html;charset=utf-8') are encoded using UTF-8. Some methods that return
  38. values will return them in the same type as the name given.
  39. If the header keys or values cannot be encoded or decoded using the rules
  40. above, using just L{bytes} arguments to the methods of this class will
  41. ensure no decoding or encoding is done, and L{Headers} will treat the keys
  42. and values as opaque byte strings.
  43. @cvar _caseMappings: A L{dict} that maps lowercase header names
  44. to their canonicalized representation, for headers with unconventional
  45. capitalization.
  46. @cvar _canonicalHeaderCache: A L{dict} that maps header names to their
  47. canonicalized representation.
  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. _caseMappings: ClassVar[Dict[bytes, bytes]] = {
  52. b"content-md5": b"Content-MD5",
  53. b"dnt": b"DNT",
  54. b"etag": b"ETag",
  55. b"p3p": b"P3P",
  56. b"te": b"TE",
  57. b"www-authenticate": b"WWW-Authenticate",
  58. b"x-xss-protection": b"X-XSS-Protection",
  59. }
  60. _canonicalHeaderCache: ClassVar[Dict[Union[bytes, str], bytes]] = {}
  61. _MAX_CACHED_HEADERS: ClassVar[int] = 10_000
  62. __slots__ = ["_rawHeaders"]
  63. def __init__(
  64. self,
  65. rawHeaders: Optional[Mapping[AnyStr, Sequence[AnyStr]]] = None,
  66. ) -> None:
  67. self._rawHeaders: Dict[bytes, List[bytes]] = {}
  68. if rawHeaders is not None:
  69. for name, values in rawHeaders.items():
  70. self.setRawHeaders(name, values)
  71. def __repr__(self) -> str:
  72. """
  73. Return a string fully describing the headers set on this object.
  74. """
  75. return "{}({!r})".format(
  76. self.__class__.__name__,
  77. self._rawHeaders,
  78. )
  79. def __cmp__(self, other):
  80. """
  81. Define L{Headers} instances as being equal to each other if they have
  82. the same raw headers.
  83. """
  84. if isinstance(other, Headers):
  85. return cmp(
  86. sorted(self._rawHeaders.items()), sorted(other._rawHeaders.items())
  87. )
  88. return NotImplemented
  89. def _encodeName(self, name: Union[str, bytes]) -> bytes:
  90. """
  91. Encode the name of a header (eg 'Content-Type') to an ISO-8859-1
  92. encoded bytestring if required. It will be canonicalized and
  93. whitespace-sanitized.
  94. @param name: A HTTP header name
  95. @return: C{name}, encoded if required, lowercased
  96. """
  97. if canonicalName := self._canonicalHeaderCache.get(name, None):
  98. return canonicalName
  99. bytes_name = name.encode("iso-8859-1") if isinstance(name, str) else name
  100. if bytes_name.lower() in self._caseMappings:
  101. # Some headers have special capitalization:
  102. result = self._caseMappings[bytes_name.lower()]
  103. else:
  104. result = _sanitizeLinearWhitespace(
  105. b"-".join([word.capitalize() for word in bytes_name.split(b"-")])
  106. )
  107. # In general, we should only see a very small number of header
  108. # variations in the real world, so caching them is fine. However, an
  109. # attacker could generate infinite header variations to fill up RAM, so
  110. # we cap how many we cache. The performance degradation from lack of
  111. # caching won't be that bad, and legit traffic won't hit it.
  112. if len(self._canonicalHeaderCache) < self._MAX_CACHED_HEADERS:
  113. self._canonicalHeaderCache[name] = result
  114. return result
  115. def copy(self):
  116. """
  117. Return a copy of itself with the same headers set.
  118. @return: A new L{Headers}
  119. """
  120. return self.__class__(self._rawHeaders)
  121. def hasHeader(self, name: AnyStr) -> bool:
  122. """
  123. Check for the existence of a given header.
  124. @param name: The name of the HTTP header to check for.
  125. @return: C{True} if the header exists, otherwise C{False}.
  126. """
  127. return self._encodeName(name) in self._rawHeaders
  128. def removeHeader(self, name: AnyStr) -> None:
  129. """
  130. Remove the named header from this header object.
  131. @param name: The name of the HTTP header to remove.
  132. @return: L{None}
  133. """
  134. self._rawHeaders.pop(self._encodeName(name), None)
  135. def setRawHeaders(
  136. self, name: Union[str, bytes], values: Sequence[Union[str, bytes]]
  137. ) -> None:
  138. """
  139. Sets the raw representation of the given header.
  140. @param name: The name of the HTTP header to set the values for.
  141. @param values: A list of strings each one being a header value of
  142. the given name.
  143. @raise TypeError: Raised if C{values} is not a sequence of L{bytes}
  144. or L{str}, or if C{name} is not L{bytes} or L{str}.
  145. @return: L{None}
  146. """
  147. _name = self._encodeName(name)
  148. encodedValues: List[bytes] = []
  149. for v in values:
  150. if isinstance(v, str):
  151. _v = v.encode("utf8")
  152. else:
  153. _v = v
  154. encodedValues.append(_sanitizeLinearWhitespace(_v))
  155. self._rawHeaders[_name] = encodedValues
  156. def addRawHeader(self, name: Union[str, bytes], value: Union[str, bytes]) -> None:
  157. """
  158. Add a new raw value for the given header.
  159. @param name: The name of the header for which to set the value.
  160. @param value: The value to set for the named header.
  161. """
  162. self._rawHeaders.setdefault(self._encodeName(name), []).append(
  163. _sanitizeLinearWhitespace(
  164. value.encode("utf8") if isinstance(value, str) else value
  165. )
  166. )
  167. @overload
  168. def getRawHeaders(self, name: AnyStr) -> Optional[Sequence[AnyStr]]:
  169. ...
  170. @overload
  171. def getRawHeaders(self, name: AnyStr, default: _T) -> Union[Sequence[AnyStr], _T]:
  172. ...
  173. def getRawHeaders(
  174. self, name: AnyStr, default: Optional[_T] = None
  175. ) -> Union[Sequence[AnyStr], Optional[_T]]:
  176. """
  177. Returns a sequence of headers matching the given name as the raw string
  178. given.
  179. @param name: The name of the HTTP header to get the values of.
  180. @param default: The value to return if no header with the given C{name}
  181. exists.
  182. @return: If the named header is present, a sequence of its
  183. values. Otherwise, C{default}.
  184. """
  185. encodedName = self._encodeName(name)
  186. values = self._rawHeaders.get(encodedName, [])
  187. if not values:
  188. return default
  189. if isinstance(name, str):
  190. return [v.decode("utf8") for v in values]
  191. return values
  192. def getAllRawHeaders(self) -> Iterator[Tuple[bytes, Sequence[bytes]]]:
  193. """
  194. Return an iterator of key, value pairs of all headers contained in this
  195. object, as L{bytes}. The keys are capitalized in canonical
  196. capitalization.
  197. """
  198. return iter(self._rawHeaders.items())
  199. __all__ = ["Headers"]