http_headers.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 __future__ import division, absolute_import
  8. from twisted.python.compat import comparable, cmp, unicode
  9. def _dashCapitalize(name):
  10. """
  11. Return a byte string which is capitalized using '-' as a word separator.
  12. @param name: The name of the header to capitalize.
  13. @type name: L{bytes}
  14. @return: The given header capitalized using '-' as a word separator.
  15. @rtype: L{bytes}
  16. """
  17. return b'-'.join([word.capitalize() for word in name.split(b'-')])
  18. def _sanitizeLinearWhitespace(headerComponent):
  19. r"""
  20. Replace linear whitespace (C{\n}, C{\r\n}, C{\r}) in a header key
  21. or value with a single space. If C{headerComponent} is not
  22. L{bytes}, it is passed through unchanged.
  23. @param headerComponent: The header key or value to sanitize.
  24. @type headerComponent: L{bytes}
  25. @return: The sanitized header key or value.
  26. @rtype: L{bytes}
  27. """
  28. return b' '.join(headerComponent.splitlines())
  29. @comparable
  30. class Headers(object):
  31. """
  32. Stores HTTP headers in a key and multiple value format.
  33. Most methods accept L{bytes} and L{unicode}, with an internal L{bytes}
  34. representation. When passed L{unicode}, header names (e.g. 'Content-Type')
  35. are encoded using ISO-8859-1 and header values (e.g.
  36. 'text/html;charset=utf-8') are encoded using UTF-8. Some methods that return
  37. values will return them in the same type as the name given.
  38. If the header keys or values cannot be encoded or decoded using the rules
  39. above, using just L{bytes} arguments to the methods of this class will
  40. ensure no decoding or encoding is done, and L{Headers} will treat the keys
  41. and values as opaque byte strings.
  42. @cvar _caseMappings: A L{dict} that maps lowercase header names
  43. to their canonicalized representation.
  44. @ivar _rawHeaders: A L{dict} mapping header names as L{bytes} to L{list}s of
  45. header values as L{bytes}.
  46. """
  47. _caseMappings = {
  48. b'content-md5': b'Content-MD5',
  49. b'dnt': b'DNT',
  50. b'etag': b'ETag',
  51. b'p3p': b'P3P',
  52. b'te': b'TE',
  53. b'www-authenticate': b'WWW-Authenticate',
  54. b'x-xss-protection': b'X-XSS-Protection'}
  55. def __init__(self, rawHeaders=None):
  56. self._rawHeaders = {}
  57. if rawHeaders is not None:
  58. for name, values in rawHeaders.items():
  59. self.setRawHeaders(name, values)
  60. def __repr__(self):
  61. """
  62. Return a string fully describing the headers set on this object.
  63. """
  64. return '%s(%r)' % (self.__class__.__name__, self._rawHeaders,)
  65. def __cmp__(self, other):
  66. """
  67. Define L{Headers} instances as being equal to each other if they have
  68. the same raw headers.
  69. """
  70. if isinstance(other, Headers):
  71. return cmp(
  72. sorted(self._rawHeaders.items()),
  73. sorted(other._rawHeaders.items()))
  74. return NotImplemented
  75. def _encodeName(self, name):
  76. """
  77. Encode the name of a header (eg 'Content-Type') to an ISO-8859-1 encoded
  78. bytestring if required.
  79. @param name: A HTTP header name
  80. @type name: L{unicode} or L{bytes}
  81. @return: C{name}, encoded if required, lowercased
  82. @rtype: L{bytes}
  83. """
  84. if isinstance(name, unicode):
  85. return name.lower().encode('iso-8859-1')
  86. return name.lower()
  87. def _encodeValue(self, value):
  88. """
  89. Encode a single header value to a UTF-8 encoded bytestring if required.
  90. @param value: A single HTTP header value.
  91. @type value: L{bytes} or L{unicode}
  92. @return: C{value}, encoded if required
  93. @rtype: L{bytes}
  94. """
  95. if isinstance(value, unicode):
  96. return value.encode('utf8')
  97. return value
  98. def _encodeValues(self, values):
  99. """
  100. Encode a L{list} of header values to a L{list} of UTF-8 encoded
  101. bytestrings if required.
  102. @param values: A list of HTTP header values.
  103. @type values: L{list} of L{bytes} or L{unicode} (mixed types allowed)
  104. @return: C{values}, with each item encoded if required
  105. @rtype: L{list} of L{bytes}
  106. """
  107. newValues = []
  108. for value in values:
  109. newValues.append(self._encodeValue(value))
  110. return newValues
  111. def _decodeValues(self, values):
  112. """
  113. Decode a L{list} of header values into a L{list} of Unicode strings.
  114. @param values: A list of HTTP header values.
  115. @type values: L{list} of UTF-8 encoded L{bytes}
  116. @return: C{values}, with each item decoded
  117. @rtype: L{list} of L{unicode}
  118. """
  119. newValues = []
  120. for value in values:
  121. newValues.append(value.decode('utf8'))
  122. return newValues
  123. def copy(self):
  124. """
  125. Return a copy of itself with the same headers set.
  126. @return: A new L{Headers}
  127. """
  128. return self.__class__(self._rawHeaders)
  129. def hasHeader(self, name):
  130. """
  131. Check for the existence of a given header.
  132. @type name: L{bytes} or L{unicode}
  133. @param name: The name of the HTTP header to check for.
  134. @rtype: L{bool}
  135. @return: C{True} if the header exists, otherwise C{False}.
  136. """
  137. return self._encodeName(name) in self._rawHeaders
  138. def removeHeader(self, name):
  139. """
  140. Remove the named header from this header object.
  141. @type name: L{bytes} or L{unicode}
  142. @param name: The name of the HTTP header to remove.
  143. @return: L{None}
  144. """
  145. self._rawHeaders.pop(self._encodeName(name), None)
  146. def setRawHeaders(self, name, values):
  147. """
  148. Sets the raw representation of the given header.
  149. @type name: L{bytes} or L{unicode}
  150. @param name: The name of the HTTP header to set the values for.
  151. @type values: L{list} of L{bytes} or L{unicode} strings
  152. @param values: A list of strings each one being a header value of
  153. the given name.
  154. @return: L{None}
  155. """
  156. if not isinstance(values, list):
  157. raise TypeError("Header entry %r should be list but found "
  158. "instance of %r instead" % (name, type(values)))
  159. name = _sanitizeLinearWhitespace(self._encodeName(name))
  160. encodedValues = [_sanitizeLinearWhitespace(v)
  161. for v in self._encodeValues(values)]
  162. self._rawHeaders[name] = self._encodeValues(encodedValues)
  163. def addRawHeader(self, name, value):
  164. """
  165. Add a new raw value for the given header.
  166. @type name: L{bytes} or L{unicode}
  167. @param name: The name of the header for which to set the value.
  168. @type value: L{bytes} or L{unicode}
  169. @param value: The value to set for the named header.
  170. """
  171. values = self.getRawHeaders(name)
  172. if values is not None:
  173. values.append(value)
  174. else:
  175. values = [value]
  176. self.setRawHeaders(name, values)
  177. def getRawHeaders(self, name, default=None):
  178. """
  179. Returns a list of headers matching the given name as the raw string
  180. given.
  181. @type name: L{bytes} or L{unicode}
  182. @param name: The name of the HTTP header to get the values of.
  183. @param default: The value to return if no header with the given C{name}
  184. exists.
  185. @rtype: L{list} of strings, same type as C{name} (except when
  186. C{default} is returned).
  187. @return: If the named header is present, a L{list} of its
  188. values. Otherwise, C{default}.
  189. """
  190. encodedName = self._encodeName(name)
  191. values = self._rawHeaders.get(encodedName, default)
  192. if isinstance(name, unicode) and values is not default:
  193. return self._decodeValues(values)
  194. return values
  195. def getAllRawHeaders(self):
  196. """
  197. Return an iterator of key, value pairs of all headers contained in this
  198. object, as L{bytes}. The keys are capitalized in canonical
  199. capitalization.
  200. """
  201. for k, v in self._rawHeaders.items():
  202. yield self._canonicalNameCaps(k), v
  203. def _canonicalNameCaps(self, name):
  204. """
  205. Return the canonical name for the given header.
  206. @type name: L{bytes}
  207. @param name: The all-lowercase header name to capitalize in its
  208. canonical form.
  209. @rtype: L{bytes}
  210. @return: The canonical name of the header.
  211. """
  212. return self._caseMappings.get(name, _dashCapitalize(name))
  213. __all__ = ['Headers']