http.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. from __future__ import annotations
  2. import email.utils
  3. import re
  4. import typing as t
  5. import warnings
  6. from datetime import date
  7. from datetime import datetime
  8. from datetime import time
  9. from datetime import timedelta
  10. from datetime import timezone
  11. from enum import Enum
  12. from hashlib import sha1
  13. from time import mktime
  14. from time import struct_time
  15. from urllib.parse import quote
  16. from urllib.parse import unquote
  17. from urllib.request import parse_http_list as _parse_list_header
  18. from ._internal import _dt_as_utc
  19. from ._internal import _plain_int
  20. if t.TYPE_CHECKING:
  21. from _typeshed.wsgi import WSGIEnvironment
  22. _token_chars = frozenset(
  23. "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"
  24. )
  25. _etag_re = re.compile(r'([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)')
  26. _entity_headers = frozenset(
  27. [
  28. "allow",
  29. "content-encoding",
  30. "content-language",
  31. "content-length",
  32. "content-location",
  33. "content-md5",
  34. "content-range",
  35. "content-type",
  36. "expires",
  37. "last-modified",
  38. ]
  39. )
  40. _hop_by_hop_headers = frozenset(
  41. [
  42. "connection",
  43. "keep-alive",
  44. "proxy-authenticate",
  45. "proxy-authorization",
  46. "te",
  47. "trailer",
  48. "transfer-encoding",
  49. "upgrade",
  50. ]
  51. )
  52. HTTP_STATUS_CODES = {
  53. 100: "Continue",
  54. 101: "Switching Protocols",
  55. 102: "Processing",
  56. 103: "Early Hints", # see RFC 8297
  57. 200: "OK",
  58. 201: "Created",
  59. 202: "Accepted",
  60. 203: "Non Authoritative Information",
  61. 204: "No Content",
  62. 205: "Reset Content",
  63. 206: "Partial Content",
  64. 207: "Multi Status",
  65. 208: "Already Reported", # see RFC 5842
  66. 226: "IM Used", # see RFC 3229
  67. 300: "Multiple Choices",
  68. 301: "Moved Permanently",
  69. 302: "Found",
  70. 303: "See Other",
  71. 304: "Not Modified",
  72. 305: "Use Proxy",
  73. 306: "Switch Proxy", # unused
  74. 307: "Temporary Redirect",
  75. 308: "Permanent Redirect",
  76. 400: "Bad Request",
  77. 401: "Unauthorized",
  78. 402: "Payment Required", # unused
  79. 403: "Forbidden",
  80. 404: "Not Found",
  81. 405: "Method Not Allowed",
  82. 406: "Not Acceptable",
  83. 407: "Proxy Authentication Required",
  84. 408: "Request Timeout",
  85. 409: "Conflict",
  86. 410: "Gone",
  87. 411: "Length Required",
  88. 412: "Precondition Failed",
  89. 413: "Request Entity Too Large",
  90. 414: "Request URI Too Long",
  91. 415: "Unsupported Media Type",
  92. 416: "Requested Range Not Satisfiable",
  93. 417: "Expectation Failed",
  94. 418: "I'm a teapot", # see RFC 2324
  95. 421: "Misdirected Request", # see RFC 7540
  96. 422: "Unprocessable Entity",
  97. 423: "Locked",
  98. 424: "Failed Dependency",
  99. 425: "Too Early", # see RFC 8470
  100. 426: "Upgrade Required",
  101. 428: "Precondition Required", # see RFC 6585
  102. 429: "Too Many Requests",
  103. 431: "Request Header Fields Too Large",
  104. 449: "Retry With", # proprietary MS extension
  105. 451: "Unavailable For Legal Reasons",
  106. 500: "Internal Server Error",
  107. 501: "Not Implemented",
  108. 502: "Bad Gateway",
  109. 503: "Service Unavailable",
  110. 504: "Gateway Timeout",
  111. 505: "HTTP Version Not Supported",
  112. 506: "Variant Also Negotiates", # see RFC 2295
  113. 507: "Insufficient Storage",
  114. 508: "Loop Detected", # see RFC 5842
  115. 510: "Not Extended",
  116. 511: "Network Authentication Failed",
  117. }
  118. class COEP(Enum):
  119. """Cross Origin Embedder Policies"""
  120. UNSAFE_NONE = "unsafe-none"
  121. REQUIRE_CORP = "require-corp"
  122. class COOP(Enum):
  123. """Cross Origin Opener Policies"""
  124. UNSAFE_NONE = "unsafe-none"
  125. SAME_ORIGIN_ALLOW_POPUPS = "same-origin-allow-popups"
  126. SAME_ORIGIN = "same-origin"
  127. def quote_header_value(value: t.Any, allow_token: bool = True) -> str:
  128. """Add double quotes around a header value. If the header contains only ASCII token
  129. characters, it will be returned unchanged. If the header contains ``"`` or ``\\``
  130. characters, they will be escaped with an additional ``\\`` character.
  131. This is the reverse of :func:`unquote_header_value`.
  132. :param value: The value to quote. Will be converted to a string.
  133. :param allow_token: Disable to quote the value even if it only has token characters.
  134. .. versionchanged:: 3.0
  135. Passing bytes is not supported.
  136. .. versionchanged:: 3.0
  137. The ``extra_chars`` parameter is removed.
  138. .. versionchanged:: 2.3
  139. The value is quoted if it is the empty string.
  140. .. versionadded:: 0.5
  141. """
  142. value_str = str(value)
  143. if not value_str:
  144. return '""'
  145. if allow_token:
  146. token_chars = _token_chars
  147. if token_chars.issuperset(value_str):
  148. return value_str
  149. value_str = value_str.replace("\\", "\\\\").replace('"', '\\"')
  150. return f'"{value_str}"'
  151. def unquote_header_value(value: str) -> str:
  152. """Remove double quotes and decode slash-escaped ``"`` and ``\\`` characters in a
  153. header value.
  154. This is the reverse of :func:`quote_header_value`.
  155. :param value: The header value to unquote.
  156. .. versionchanged:: 3.0
  157. The ``is_filename`` parameter is removed.
  158. """
  159. if len(value) >= 2 and value[0] == value[-1] == '"':
  160. value = value[1:-1]
  161. return value.replace("\\\\", "\\").replace('\\"', '"')
  162. return value
  163. def dump_options_header(header: str | None, options: t.Mapping[str, t.Any]) -> str:
  164. """Produce a header value and ``key=value`` parameters separated by semicolons
  165. ``;``. For example, the ``Content-Type`` header.
  166. .. code-block:: python
  167. dump_options_header("text/html", {"charset": "UTF-8"})
  168. 'text/html; charset=UTF-8'
  169. This is the reverse of :func:`parse_options_header`.
  170. If a value contains non-token characters, it will be quoted.
  171. If a value is ``None``, the parameter is skipped.
  172. In some keys for some headers, a UTF-8 value can be encoded using a special
  173. ``key*=UTF-8''value`` form, where ``value`` is percent encoded. This function will
  174. not produce that format automatically, but if a given key ends with an asterisk
  175. ``*``, the value is assumed to have that form and will not be quoted further.
  176. :param header: The primary header value.
  177. :param options: Parameters to encode as ``key=value`` pairs.
  178. .. versionchanged:: 2.3
  179. Keys with ``None`` values are skipped rather than treated as a bare key.
  180. .. versionchanged:: 2.2.3
  181. If a key ends with ``*``, its value will not be quoted.
  182. """
  183. segments = []
  184. if header is not None:
  185. segments.append(header)
  186. for key, value in options.items():
  187. if value is None:
  188. continue
  189. if key[-1] == "*":
  190. segments.append(f"{key}={value}")
  191. else:
  192. segments.append(f"{key}={quote_header_value(value)}")
  193. return "; ".join(segments)
  194. def dump_header(iterable: dict[str, t.Any] | t.Iterable[t.Any]) -> str:
  195. """Produce a header value from a list of items or ``key=value`` pairs, separated by
  196. commas ``,``.
  197. This is the reverse of :func:`parse_list_header`, :func:`parse_dict_header`, and
  198. :func:`parse_set_header`.
  199. If a value contains non-token characters, it will be quoted.
  200. If a value is ``None``, the key is output alone.
  201. In some keys for some headers, a UTF-8 value can be encoded using a special
  202. ``key*=UTF-8''value`` form, where ``value`` is percent encoded. This function will
  203. not produce that format automatically, but if a given key ends with an asterisk
  204. ``*``, the value is assumed to have that form and will not be quoted further.
  205. .. code-block:: python
  206. dump_header(["foo", "bar baz"])
  207. 'foo, "bar baz"'
  208. dump_header({"foo": "bar baz"})
  209. 'foo="bar baz"'
  210. :param iterable: The items to create a header from.
  211. .. versionchanged:: 3.0
  212. The ``allow_token`` parameter is removed.
  213. .. versionchanged:: 2.2.3
  214. If a key ends with ``*``, its value will not be quoted.
  215. """
  216. if isinstance(iterable, dict):
  217. items = []
  218. for key, value in iterable.items():
  219. if value is None:
  220. items.append(key)
  221. elif key[-1] == "*":
  222. items.append(f"{key}={value}")
  223. else:
  224. items.append(f"{key}={quote_header_value(value)}")
  225. else:
  226. items = [quote_header_value(x) for x in iterable]
  227. return ", ".join(items)
  228. def dump_csp_header(header: ds.ContentSecurityPolicy) -> str:
  229. """Dump a Content Security Policy header.
  230. These are structured into policies such as "default-src 'self';
  231. script-src 'self'".
  232. .. versionadded:: 1.0.0
  233. Support for Content Security Policy headers was added.
  234. """
  235. return "; ".join(f"{key} {value}" for key, value in header.items())
  236. def parse_list_header(value: str) -> list[str]:
  237. """Parse a header value that consists of a list of comma separated items according
  238. to `RFC 9110 <https://httpwg.org/specs/rfc9110.html#abnf.extension>`__.
  239. This extends :func:`urllib.request.parse_http_list` to remove surrounding quotes
  240. from values.
  241. .. code-block:: python
  242. parse_list_header('token, "quoted value"')
  243. ['token', 'quoted value']
  244. This is the reverse of :func:`dump_header`.
  245. :param value: The header value to parse.
  246. """
  247. result = []
  248. for item in _parse_list_header(value):
  249. if len(item) >= 2 and item[0] == item[-1] == '"':
  250. item = item[1:-1]
  251. result.append(item)
  252. return result
  253. def parse_dict_header(value: str) -> dict[str, str | None]:
  254. """Parse a list header using :func:`parse_list_header`, then parse each item as a
  255. ``key=value`` pair.
  256. .. code-block:: python
  257. parse_dict_header('a=b, c="d, e", f')
  258. {"a": "b", "c": "d, e", "f": None}
  259. This is the reverse of :func:`dump_header`.
  260. If a key does not have a value, it is ``None``.
  261. This handles charsets for values as described in
  262. `RFC 2231 <https://www.rfc-editor.org/rfc/rfc2231#section-3>`__. Only ASCII, UTF-8,
  263. and ISO-8859-1 charsets are accepted, otherwise the value remains quoted.
  264. :param value: The header value to parse.
  265. .. versionchanged:: 3.0
  266. Passing bytes is not supported.
  267. .. versionchanged:: 3.0
  268. The ``cls`` argument is removed.
  269. .. versionchanged:: 2.3
  270. Added support for ``key*=charset''value`` encoded items.
  271. .. versionchanged:: 0.9
  272. The ``cls`` argument was added.
  273. """
  274. result: dict[str, str | None] = {}
  275. for item in parse_list_header(value):
  276. key, has_value, value = item.partition("=")
  277. key = key.strip()
  278. if not has_value:
  279. result[key] = None
  280. continue
  281. value = value.strip()
  282. encoding: str | None = None
  283. if key[-1] == "*":
  284. # key*=charset''value becomes key=value, where value is percent encoded
  285. # adapted from parse_options_header, without the continuation handling
  286. key = key[:-1]
  287. match = _charset_value_re.match(value)
  288. if match:
  289. # If there is a charset marker in the value, split it off.
  290. encoding, value = match.groups()
  291. encoding = encoding.lower()
  292. # A safe list of encodings. Modern clients should only send ASCII or UTF-8.
  293. # This list will not be extended further. An invalid encoding will leave the
  294. # value quoted.
  295. if encoding in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
  296. # invalid bytes are replaced during unquoting
  297. value = unquote(value, encoding=encoding)
  298. if len(value) >= 2 and value[0] == value[-1] == '"':
  299. value = value[1:-1]
  300. result[key] = value
  301. return result
  302. # https://httpwg.org/specs/rfc9110.html#parameter
  303. _parameter_re = re.compile(
  304. r"""
  305. # don't match multiple empty parts, that causes backtracking
  306. \s*;\s* # find the part delimiter
  307. (?:
  308. ([\w!#$%&'*+\-.^`|~]+) # key, one or more token chars
  309. = # equals, with no space on either side
  310. ( # value, token or quoted string
  311. [\w!#$%&'*+\-.^`|~]+ # one or more token chars
  312. |
  313. "(?:\\\\|\\"|.)*?" # quoted string, consuming slash escapes
  314. )
  315. )? # optionally match key=value, to account for empty parts
  316. """,
  317. re.ASCII | re.VERBOSE,
  318. )
  319. # https://www.rfc-editor.org/rfc/rfc2231#section-4
  320. _charset_value_re = re.compile(
  321. r"""
  322. ([\w!#$%&*+\-.^`|~]*)' # charset part, could be empty
  323. [\w!#$%&*+\-.^`|~]*' # don't care about language part, usually empty
  324. ([\w!#$%&'*+\-.^`|~]+) # one or more token chars with percent encoding
  325. """,
  326. re.ASCII | re.VERBOSE,
  327. )
  328. # https://www.rfc-editor.org/rfc/rfc2231#section-3
  329. _continuation_re = re.compile(r"\*(\d+)$", re.ASCII)
  330. def parse_options_header(value: str | None) -> tuple[str, dict[str, str]]:
  331. """Parse a header that consists of a value with ``key=value`` parameters separated
  332. by semicolons ``;``. For example, the ``Content-Type`` header.
  333. .. code-block:: python
  334. parse_options_header("text/html; charset=UTF-8")
  335. ('text/html', {'charset': 'UTF-8'})
  336. parse_options_header("")
  337. ("", {})
  338. This is the reverse of :func:`dump_options_header`.
  339. This parses valid parameter parts as described in
  340. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#parameter>`__. Invalid parts are
  341. skipped.
  342. This handles continuations and charsets as described in
  343. `RFC 2231 <https://www.rfc-editor.org/rfc/rfc2231#section-3>`__, although not as
  344. strictly as the RFC. Only ASCII, UTF-8, and ISO-8859-1 charsets are accepted,
  345. otherwise the value remains quoted.
  346. Clients may not be consistent in how they handle a quote character within a quoted
  347. value. The `HTML Standard <https://html.spec.whatwg.org/#multipart-form-data>`__
  348. replaces it with ``%22`` in multipart form data.
  349. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#quoted.strings>`__ uses backslash
  350. escapes in HTTP headers. Both are decoded to the ``"`` character.
  351. Clients may not be consistent in how they handle non-ASCII characters. HTML
  352. documents must declare ``<meta charset=UTF-8>``, otherwise browsers may replace with
  353. HTML character references, which can be decoded using :func:`html.unescape`.
  354. :param value: The header value to parse.
  355. :return: ``(value, options)``, where ``options`` is a dict
  356. .. versionchanged:: 2.3
  357. Invalid parts, such as keys with no value, quoted keys, and incorrectly quoted
  358. values, are discarded instead of treating as ``None``.
  359. .. versionchanged:: 2.3
  360. Only ASCII, UTF-8, and ISO-8859-1 are accepted for charset values.
  361. .. versionchanged:: 2.3
  362. Escaped quotes in quoted values, like ``%22`` and ``\\"``, are handled.
  363. .. versionchanged:: 2.2
  364. Option names are always converted to lowercase.
  365. .. versionchanged:: 2.2
  366. The ``multiple`` parameter was removed.
  367. .. versionchanged:: 0.15
  368. :rfc:`2231` parameter continuations are handled.
  369. .. versionadded:: 0.5
  370. """
  371. if value is None:
  372. return "", {}
  373. value, _, rest = value.partition(";")
  374. value = value.strip()
  375. rest = rest.strip()
  376. if not value or not rest:
  377. # empty (invalid) value, or value without options
  378. return value, {}
  379. rest = f";{rest}"
  380. options: dict[str, str] = {}
  381. encoding: str | None = None
  382. continued_encoding: str | None = None
  383. for pk, pv in _parameter_re.findall(rest):
  384. if not pk:
  385. # empty or invalid part
  386. continue
  387. pk = pk.lower()
  388. if pk[-1] == "*":
  389. # key*=charset''value becomes key=value, where value is percent encoded
  390. pk = pk[:-1]
  391. match = _charset_value_re.match(pv)
  392. if match:
  393. # If there is a valid charset marker in the value, split it off.
  394. encoding, pv = match.groups()
  395. # This might be the empty string, handled next.
  396. encoding = encoding.lower()
  397. # No charset marker, or marker with empty charset value.
  398. if not encoding:
  399. encoding = continued_encoding
  400. # A safe list of encodings. Modern clients should only send ASCII or UTF-8.
  401. # This list will not be extended further. An invalid encoding will leave the
  402. # value quoted.
  403. if encoding in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
  404. # Continuation parts don't require their own charset marker. This is
  405. # looser than the RFC, it will persist across different keys and allows
  406. # changing the charset during a continuation. But this implementation is
  407. # much simpler than tracking the full state.
  408. continued_encoding = encoding
  409. # invalid bytes are replaced during unquoting
  410. pv = unquote(pv, encoding=encoding)
  411. # Remove quotes. At this point the value cannot be empty or a single quote.
  412. if pv[0] == pv[-1] == '"':
  413. # HTTP headers use slash, multipart form data uses percent
  414. pv = pv[1:-1].replace("\\\\", "\\").replace('\\"', '"').replace("%22", '"')
  415. match = _continuation_re.search(pk)
  416. if match:
  417. # key*0=a; key*1=b becomes key=ab
  418. pk = pk[: match.start()]
  419. options[pk] = options.get(pk, "") + pv
  420. else:
  421. options[pk] = pv
  422. return value, options
  423. _q_value_re = re.compile(r"-?\d+(\.\d+)?", re.ASCII)
  424. _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept")
  425. @t.overload
  426. def parse_accept_header(value: str | None) -> ds.Accept: ...
  427. @t.overload
  428. def parse_accept_header(value: str | None, cls: type[_TAnyAccept]) -> _TAnyAccept: ...
  429. def parse_accept_header(
  430. value: str | None, cls: type[_TAnyAccept] | None = None
  431. ) -> _TAnyAccept:
  432. """Parse an ``Accept`` header according to
  433. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#field.accept>`__.
  434. Returns an :class:`.Accept` instance, which can sort and inspect items based on
  435. their quality parameter. When parsing ``Accept-Charset``, ``Accept-Encoding``, or
  436. ``Accept-Language``, pass the appropriate :class:`.Accept` subclass.
  437. :param value: The header value to parse.
  438. :param cls: The :class:`.Accept` class to wrap the result in.
  439. :return: An instance of ``cls``.
  440. .. versionchanged:: 2.3
  441. Parse according to RFC 9110. Items with invalid ``q`` values are skipped.
  442. """
  443. if cls is None:
  444. cls = t.cast(t.Type[_TAnyAccept], ds.Accept)
  445. if not value:
  446. return cls(None)
  447. result = []
  448. for item in parse_list_header(value):
  449. item, options = parse_options_header(item)
  450. if "q" in options:
  451. # pop q, remaining options are reconstructed
  452. q_str = options.pop("q").strip()
  453. if _q_value_re.fullmatch(q_str) is None:
  454. # ignore an invalid q
  455. continue
  456. q = float(q_str)
  457. if q < 0 or q > 1:
  458. # ignore an invalid q
  459. continue
  460. else:
  461. q = 1
  462. if options:
  463. # reconstruct the media type with any options
  464. item = dump_options_header(item, options)
  465. result.append((item, q))
  466. return cls(result)
  467. _TAnyCC = t.TypeVar("_TAnyCC", bound="ds.cache_control._CacheControl")
  468. @t.overload
  469. def parse_cache_control_header(
  470. value: str | None,
  471. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  472. ) -> ds.RequestCacheControl: ...
  473. @t.overload
  474. def parse_cache_control_header(
  475. value: str | None,
  476. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  477. cls: type[_TAnyCC] = ...,
  478. ) -> _TAnyCC: ...
  479. def parse_cache_control_header(
  480. value: str | None,
  481. on_update: t.Callable[[ds.cache_control._CacheControl], None] | None = None,
  482. cls: type[_TAnyCC] | None = None,
  483. ) -> _TAnyCC:
  484. """Parse a cache control header. The RFC differs between response and
  485. request cache control, this method does not. It's your responsibility
  486. to not use the wrong control statements.
  487. .. versionadded:: 0.5
  488. The `cls` was added. If not specified an immutable
  489. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  490. :param value: a cache control header to be parsed.
  491. :param on_update: an optional callable that is called every time a value
  492. on the :class:`~werkzeug.datastructures.CacheControl`
  493. object is changed.
  494. :param cls: the class for the returned object. By default
  495. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  496. :return: a `cls` object.
  497. """
  498. if cls is None:
  499. cls = t.cast("type[_TAnyCC]", ds.RequestCacheControl)
  500. if not value:
  501. return cls((), on_update)
  502. return cls(parse_dict_header(value), on_update)
  503. _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy")
  504. @t.overload
  505. def parse_csp_header(
  506. value: str | None,
  507. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  508. ) -> ds.ContentSecurityPolicy: ...
  509. @t.overload
  510. def parse_csp_header(
  511. value: str | None,
  512. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  513. cls: type[_TAnyCSP] = ...,
  514. ) -> _TAnyCSP: ...
  515. def parse_csp_header(
  516. value: str | None,
  517. on_update: t.Callable[[ds.ContentSecurityPolicy], None] | None = None,
  518. cls: type[_TAnyCSP] | None = None,
  519. ) -> _TAnyCSP:
  520. """Parse a Content Security Policy header.
  521. .. versionadded:: 1.0.0
  522. Support for Content Security Policy headers was added.
  523. :param value: a csp header to be parsed.
  524. :param on_update: an optional callable that is called every time a value
  525. on the object is changed.
  526. :param cls: the class for the returned object. By default
  527. :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
  528. :return: a `cls` object.
  529. """
  530. if cls is None:
  531. cls = t.cast("type[_TAnyCSP]", ds.ContentSecurityPolicy)
  532. if value is None:
  533. return cls((), on_update)
  534. items = []
  535. for policy in value.split(";"):
  536. policy = policy.strip()
  537. # Ignore badly formatted policies (no space)
  538. if " " in policy:
  539. directive, value = policy.strip().split(" ", 1)
  540. items.append((directive.strip(), value.strip()))
  541. return cls(items, on_update)
  542. def parse_set_header(
  543. value: str | None,
  544. on_update: t.Callable[[ds.HeaderSet], None] | None = None,
  545. ) -> ds.HeaderSet:
  546. """Parse a set-like header and return a
  547. :class:`~werkzeug.datastructures.HeaderSet` object:
  548. >>> hs = parse_set_header('token, "quoted value"')
  549. The return value is an object that treats the items case-insensitively
  550. and keeps the order of the items:
  551. >>> 'TOKEN' in hs
  552. True
  553. >>> hs.index('quoted value')
  554. 1
  555. >>> hs
  556. HeaderSet(['token', 'quoted value'])
  557. To create a header from the :class:`HeaderSet` again, use the
  558. :func:`dump_header` function.
  559. :param value: a set header to be parsed.
  560. :param on_update: an optional callable that is called every time a
  561. value on the :class:`~werkzeug.datastructures.HeaderSet`
  562. object is changed.
  563. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  564. """
  565. if not value:
  566. return ds.HeaderSet(None, on_update)
  567. return ds.HeaderSet(parse_list_header(value), on_update)
  568. def parse_if_range_header(value: str | None) -> ds.IfRange:
  569. """Parses an if-range header which can be an etag or a date. Returns
  570. a :class:`~werkzeug.datastructures.IfRange` object.
  571. .. versionchanged:: 2.0
  572. If the value represents a datetime, it is timezone-aware.
  573. .. versionadded:: 0.7
  574. """
  575. if not value:
  576. return ds.IfRange()
  577. date = parse_date(value)
  578. if date is not None:
  579. return ds.IfRange(date=date)
  580. # drop weakness information
  581. return ds.IfRange(unquote_etag(value)[0])
  582. def parse_range_header(
  583. value: str | None, make_inclusive: bool = True
  584. ) -> ds.Range | None:
  585. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  586. object. If the header is missing or malformed `None` is returned.
  587. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  588. non-inclusive.
  589. .. versionadded:: 0.7
  590. """
  591. if not value or "=" not in value:
  592. return None
  593. ranges = []
  594. last_end = 0
  595. units, rng = value.split("=", 1)
  596. units = units.strip().lower()
  597. for item in rng.split(","):
  598. item = item.strip()
  599. if "-" not in item:
  600. return None
  601. if item.startswith("-"):
  602. if last_end < 0:
  603. return None
  604. try:
  605. begin = _plain_int(item)
  606. except ValueError:
  607. return None
  608. end = None
  609. last_end = -1
  610. elif "-" in item:
  611. begin_str, end_str = item.split("-", 1)
  612. begin_str = begin_str.strip()
  613. end_str = end_str.strip()
  614. try:
  615. begin = _plain_int(begin_str)
  616. except ValueError:
  617. return None
  618. if begin < last_end or last_end < 0:
  619. return None
  620. if end_str:
  621. try:
  622. end = _plain_int(end_str) + 1
  623. except ValueError:
  624. return None
  625. if begin >= end:
  626. return None
  627. else:
  628. end = None
  629. last_end = end if end is not None else -1
  630. ranges.append((begin, end))
  631. return ds.Range(units, ranges)
  632. def parse_content_range_header(
  633. value: str | None,
  634. on_update: t.Callable[[ds.ContentRange], None] | None = None,
  635. ) -> ds.ContentRange | None:
  636. """Parses a range header into a
  637. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  638. parsing is not possible.
  639. .. versionadded:: 0.7
  640. :param value: a content range header to be parsed.
  641. :param on_update: an optional callable that is called every time a value
  642. on the :class:`~werkzeug.datastructures.ContentRange`
  643. object is changed.
  644. """
  645. if value is None:
  646. return None
  647. try:
  648. units, rangedef = (value or "").strip().split(None, 1)
  649. except ValueError:
  650. return None
  651. if "/" not in rangedef:
  652. return None
  653. rng, length_str = rangedef.split("/", 1)
  654. if length_str == "*":
  655. length = None
  656. else:
  657. try:
  658. length = _plain_int(length_str)
  659. except ValueError:
  660. return None
  661. if rng == "*":
  662. if not is_byte_range_valid(None, None, length):
  663. return None
  664. return ds.ContentRange(units, None, None, length, on_update=on_update)
  665. elif "-" not in rng:
  666. return None
  667. start_str, stop_str = rng.split("-", 1)
  668. try:
  669. start = _plain_int(start_str)
  670. stop = _plain_int(stop_str) + 1
  671. except ValueError:
  672. return None
  673. if is_byte_range_valid(start, stop, length):
  674. return ds.ContentRange(units, start, stop, length, on_update=on_update)
  675. return None
  676. def quote_etag(etag: str, weak: bool = False) -> str:
  677. """Quote an etag.
  678. :param etag: the etag to quote.
  679. :param weak: set to `True` to tag it "weak".
  680. """
  681. if '"' in etag:
  682. raise ValueError("invalid etag")
  683. etag = f'"{etag}"'
  684. if weak:
  685. etag = f"W/{etag}"
  686. return etag
  687. def unquote_etag(
  688. etag: str | None,
  689. ) -> tuple[str, bool] | tuple[None, None]:
  690. """Unquote a single etag:
  691. >>> unquote_etag('W/"bar"')
  692. ('bar', True)
  693. >>> unquote_etag('"bar"')
  694. ('bar', False)
  695. :param etag: the etag identifier to unquote.
  696. :return: a ``(etag, weak)`` tuple.
  697. """
  698. if not etag:
  699. return None, None
  700. etag = etag.strip()
  701. weak = False
  702. if etag.startswith(("W/", "w/")):
  703. weak = True
  704. etag = etag[2:]
  705. if etag[:1] == etag[-1:] == '"':
  706. etag = etag[1:-1]
  707. return etag, weak
  708. def parse_etags(value: str | None) -> ds.ETags:
  709. """Parse an etag header.
  710. :param value: the tag header to parse
  711. :return: an :class:`~werkzeug.datastructures.ETags` object.
  712. """
  713. if not value:
  714. return ds.ETags()
  715. strong = []
  716. weak = []
  717. end = len(value)
  718. pos = 0
  719. while pos < end:
  720. match = _etag_re.match(value, pos)
  721. if match is None:
  722. break
  723. is_weak, quoted, raw = match.groups()
  724. if raw == "*":
  725. return ds.ETags(star_tag=True)
  726. elif quoted:
  727. raw = quoted
  728. if is_weak:
  729. weak.append(raw)
  730. else:
  731. strong.append(raw)
  732. pos = match.end()
  733. return ds.ETags(strong, weak)
  734. def generate_etag(data: bytes) -> str:
  735. """Generate an etag for some data.
  736. .. versionchanged:: 2.0
  737. Use SHA-1. MD5 may not be available in some environments.
  738. """
  739. return sha1(data).hexdigest()
  740. def parse_date(value: str | None) -> datetime | None:
  741. """Parse an :rfc:`2822` date into a timezone-aware
  742. :class:`datetime.datetime` object, or ``None`` if parsing fails.
  743. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
  744. returns ``None`` if parsing fails instead of raising an exception,
  745. and always returns a timezone-aware datetime object. If the string
  746. doesn't have timezone information, it is assumed to be UTC.
  747. :param value: A string with a supported date format.
  748. .. versionchanged:: 2.0
  749. Return a timezone-aware datetime object. Use
  750. ``email.utils.parsedate_to_datetime``.
  751. """
  752. if value is None:
  753. return None
  754. try:
  755. dt = email.utils.parsedate_to_datetime(value)
  756. except (TypeError, ValueError):
  757. return None
  758. if dt.tzinfo is None:
  759. return dt.replace(tzinfo=timezone.utc)
  760. return dt
  761. def http_date(
  762. timestamp: datetime | date | int | float | struct_time | None = None,
  763. ) -> str:
  764. """Format a datetime object or timestamp into an :rfc:`2822` date
  765. string.
  766. This is a wrapper for :func:`email.utils.format_datetime`. It
  767. assumes naive datetime objects are in UTC instead of raising an
  768. exception.
  769. :param timestamp: The datetime or timestamp to format. Defaults to
  770. the current time.
  771. .. versionchanged:: 2.0
  772. Use ``email.utils.format_datetime``. Accept ``date`` objects.
  773. """
  774. if isinstance(timestamp, date):
  775. if not isinstance(timestamp, datetime):
  776. # Assume plain date is midnight UTC.
  777. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc)
  778. else:
  779. # Ensure datetime is timezone-aware.
  780. timestamp = _dt_as_utc(timestamp)
  781. return email.utils.format_datetime(timestamp, usegmt=True)
  782. if isinstance(timestamp, struct_time):
  783. timestamp = mktime(timestamp)
  784. return email.utils.formatdate(timestamp, usegmt=True)
  785. def parse_age(value: str | None = None) -> timedelta | None:
  786. """Parses a base-10 integer count of seconds into a timedelta.
  787. If parsing fails, the return value is `None`.
  788. :param value: a string consisting of an integer represented in base-10
  789. :return: a :class:`datetime.timedelta` object or `None`.
  790. """
  791. if not value:
  792. return None
  793. try:
  794. seconds = int(value)
  795. except ValueError:
  796. return None
  797. if seconds < 0:
  798. return None
  799. try:
  800. return timedelta(seconds=seconds)
  801. except OverflowError:
  802. return None
  803. def dump_age(age: timedelta | int | None = None) -> str | None:
  804. """Formats the duration as a base-10 integer.
  805. :param age: should be an integer number of seconds,
  806. a :class:`datetime.timedelta` object, or,
  807. if the age is unknown, `None` (default).
  808. """
  809. if age is None:
  810. return None
  811. if isinstance(age, timedelta):
  812. age = int(age.total_seconds())
  813. else:
  814. age = int(age)
  815. if age < 0:
  816. raise ValueError("age cannot be negative")
  817. return str(age)
  818. def is_resource_modified(
  819. environ: WSGIEnvironment,
  820. etag: str | None = None,
  821. data: bytes | None = None,
  822. last_modified: datetime | str | None = None,
  823. ignore_if_range: bool = True,
  824. ) -> bool:
  825. """Convenience method for conditional requests.
  826. :param environ: the WSGI environment of the request to be checked.
  827. :param etag: the etag for the response for comparison.
  828. :param data: or alternatively the data of the response to automatically
  829. generate an etag using :func:`generate_etag`.
  830. :param last_modified: an optional date of the last modification.
  831. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  832. account.
  833. :return: `True` if the resource was modified, otherwise `False`.
  834. .. versionchanged:: 2.0
  835. SHA-1 is used to generate an etag value for the data. MD5 may
  836. not be available in some environments.
  837. .. versionchanged:: 1.0.0
  838. The check is run for methods other than ``GET`` and ``HEAD``.
  839. """
  840. return _sansio_http.is_resource_modified(
  841. http_range=environ.get("HTTP_RANGE"),
  842. http_if_range=environ.get("HTTP_IF_RANGE"),
  843. http_if_modified_since=environ.get("HTTP_IF_MODIFIED_SINCE"),
  844. http_if_none_match=environ.get("HTTP_IF_NONE_MATCH"),
  845. http_if_match=environ.get("HTTP_IF_MATCH"),
  846. etag=etag,
  847. data=data,
  848. last_modified=last_modified,
  849. ignore_if_range=ignore_if_range,
  850. )
  851. def remove_entity_headers(
  852. headers: ds.Headers | list[tuple[str, str]],
  853. allowed: t.Iterable[str] = ("expires", "content-location"),
  854. ) -> None:
  855. """Remove all entity headers from a list or :class:`Headers` object. This
  856. operation works in-place. `Expires` and `Content-Location` headers are
  857. by default not removed. The reason for this is :rfc:`2616` section
  858. 10.3.5 which specifies some entity headers that should be sent.
  859. .. versionchanged:: 0.5
  860. added `allowed` parameter.
  861. :param headers: a list or :class:`Headers` object.
  862. :param allowed: a list of headers that should still be allowed even though
  863. they are entity headers.
  864. """
  865. allowed = {x.lower() for x in allowed}
  866. headers[:] = [
  867. (key, value)
  868. for key, value in headers
  869. if not is_entity_header(key) or key.lower() in allowed
  870. ]
  871. def remove_hop_by_hop_headers(headers: ds.Headers | list[tuple[str, str]]) -> None:
  872. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  873. :class:`Headers` object. This operation works in-place.
  874. .. versionadded:: 0.5
  875. :param headers: a list or :class:`Headers` object.
  876. """
  877. headers[:] = [
  878. (key, value) for key, value in headers if not is_hop_by_hop_header(key)
  879. ]
  880. def is_entity_header(header: str) -> bool:
  881. """Check if a header is an entity header.
  882. .. versionadded:: 0.5
  883. :param header: the header to test.
  884. :return: `True` if it's an entity header, `False` otherwise.
  885. """
  886. return header.lower() in _entity_headers
  887. def is_hop_by_hop_header(header: str) -> bool:
  888. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  889. .. versionadded:: 0.5
  890. :param header: the header to test.
  891. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
  892. """
  893. return header.lower() in _hop_by_hop_headers
  894. def parse_cookie(
  895. header: WSGIEnvironment | str | None,
  896. cls: type[ds.MultiDict[str, str]] | None = None,
  897. ) -> ds.MultiDict[str, str]:
  898. """Parse a cookie from a string or WSGI environ.
  899. The same key can be provided multiple times, the values are stored
  900. in-order. The default :class:`MultiDict` will have the first value
  901. first, and all values can be retrieved with
  902. :meth:`MultiDict.getlist`.
  903. :param header: The cookie header as a string, or a WSGI environ dict
  904. with a ``HTTP_COOKIE`` key.
  905. :param cls: A dict-like class to store the parsed cookies in.
  906. Defaults to :class:`MultiDict`.
  907. .. versionchanged:: 3.0
  908. Passing bytes, and the ``charset`` and ``errors`` parameters, were removed.
  909. .. versionchanged:: 1.0
  910. Returns a :class:`MultiDict` instead of a ``TypeConversionDict``.
  911. .. versionchanged:: 0.5
  912. Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls``
  913. parameter was added.
  914. """
  915. if isinstance(header, dict):
  916. cookie = header.get("HTTP_COOKIE")
  917. else:
  918. cookie = header
  919. if cookie:
  920. cookie = cookie.encode("latin1").decode()
  921. return _sansio_http.parse_cookie(cookie=cookie, cls=cls)
  922. _cookie_no_quote_re = re.compile(r"[\w!#$%&'()*+\-./:<=>?@\[\]^`{|}~]*", re.A)
  923. _cookie_slash_re = re.compile(rb"[\x00-\x19\",;\\\x7f-\xff]", re.A)
  924. _cookie_slash_map = {b'"': b'\\"', b"\\": b"\\\\"}
  925. _cookie_slash_map.update(
  926. (v.to_bytes(1, "big"), b"\\%03o" % v)
  927. for v in [*range(0x20), *b",;", *range(0x7F, 256)]
  928. )
  929. def dump_cookie(
  930. key: str,
  931. value: str = "",
  932. max_age: timedelta | int | None = None,
  933. expires: str | datetime | int | float | None = None,
  934. path: str | None = "/",
  935. domain: str | None = None,
  936. secure: bool = False,
  937. httponly: bool = False,
  938. sync_expires: bool = True,
  939. max_size: int = 4093,
  940. samesite: str | None = None,
  941. ) -> str:
  942. """Create a Set-Cookie header without the ``Set-Cookie`` prefix.
  943. The return value is usually restricted to ascii as the vast majority
  944. of values are properly escaped, but that is no guarantee. It's
  945. tunneled through latin1 as required by :pep:`3333`.
  946. The return value is not ASCII safe if the key contains unicode
  947. characters. This is technically against the specification but
  948. happens in the wild. It's strongly recommended to not use
  949. non-ASCII values for the keys.
  950. :param max_age: should be a number of seconds, or `None` (default) if
  951. the cookie should last only as long as the client's
  952. browser session. Additionally `timedelta` objects
  953. are accepted, too.
  954. :param expires: should be a `datetime` object or unix timestamp.
  955. :param path: limits the cookie to a given path, per default it will
  956. span the whole domain.
  957. :param domain: Use this if you want to set a cross-domain cookie. For
  958. example, ``domain="example.com"`` will set a cookie
  959. that is readable by the domain ``www.example.com``,
  960. ``foo.example.com`` etc. Otherwise, a cookie will only
  961. be readable by the domain that set it.
  962. :param secure: The cookie will only be available via HTTPS
  963. :param httponly: disallow JavaScript to access the cookie. This is an
  964. extension to the cookie standard and probably not
  965. supported by all browsers.
  966. :param charset: the encoding for string values.
  967. :param sync_expires: automatically set expires if max_age is defined
  968. but expires not.
  969. :param max_size: Warn if the final header value exceeds this size. The
  970. default, 4093, should be safely `supported by most browsers
  971. <cookie_>`_. Set to 0 to disable this check.
  972. :param samesite: Limits the scope of the cookie such that it will
  973. only be attached to requests if those requests are same-site.
  974. .. _`cookie`: http://browsercookielimits.squawky.net/
  975. .. versionchanged:: 3.0
  976. Passing bytes, and the ``charset`` parameter, were removed.
  977. .. versionchanged:: 2.3.3
  978. The ``path`` parameter is ``/`` by default.
  979. .. versionchanged:: 2.3.1
  980. The value allows more characters without quoting.
  981. .. versionchanged:: 2.3
  982. ``localhost`` and other names without a dot are allowed for the domain. A
  983. leading dot is ignored.
  984. .. versionchanged:: 2.3
  985. The ``path`` parameter is ``None`` by default.
  986. .. versionchanged:: 1.0.0
  987. The string ``'None'`` is accepted for ``samesite``.
  988. """
  989. if path is not None:
  990. # safe = https://url.spec.whatwg.org/#url-path-segment-string
  991. # as well as percent for things that are already quoted
  992. # excluding semicolon since it's part of the header syntax
  993. path = quote(path, safe="%!$&'()*+,/:=@")
  994. if domain:
  995. domain = domain.partition(":")[0].lstrip(".").encode("idna").decode("ascii")
  996. if isinstance(max_age, timedelta):
  997. max_age = int(max_age.total_seconds())
  998. if expires is not None:
  999. if not isinstance(expires, str):
  1000. expires = http_date(expires)
  1001. elif max_age is not None and sync_expires:
  1002. expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)
  1003. if samesite is not None:
  1004. samesite = samesite.title()
  1005. if samesite not in {"Strict", "Lax", "None"}:
  1006. raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
  1007. # Quote value if it contains characters not allowed by RFC 6265. Slash-escape with
  1008. # three octal digits, which matches http.cookies, although the RFC suggests base64.
  1009. if not _cookie_no_quote_re.fullmatch(value):
  1010. # Work with bytes here, since a UTF-8 character could be multiple bytes.
  1011. value = _cookie_slash_re.sub(
  1012. lambda m: _cookie_slash_map[m.group()], value.encode()
  1013. ).decode("ascii")
  1014. value = f'"{value}"'
  1015. # Send a non-ASCII key as mojibake. Everything else should already be ASCII.
  1016. # TODO Remove encoding dance, it seems like clients accept UTF-8 keys
  1017. buf = [f"{key.encode().decode('latin1')}={value}"]
  1018. for k, v in (
  1019. ("Domain", domain),
  1020. ("Expires", expires),
  1021. ("Max-Age", max_age),
  1022. ("Secure", secure),
  1023. ("HttpOnly", httponly),
  1024. ("Path", path),
  1025. ("SameSite", samesite),
  1026. ):
  1027. if v is None or v is False:
  1028. continue
  1029. if v is True:
  1030. buf.append(k)
  1031. continue
  1032. buf.append(f"{k}={v}")
  1033. rv = "; ".join(buf)
  1034. # Warn if the final value of the cookie is larger than the limit. If the cookie is
  1035. # too large, then it may be silently ignored by the browser, which can be quite hard
  1036. # to debug.
  1037. cookie_size = len(rv)
  1038. if max_size and cookie_size > max_size:
  1039. value_size = len(value)
  1040. warnings.warn(
  1041. f"The '{key}' cookie is too large: the value was {value_size} bytes but the"
  1042. f" header required {cookie_size - value_size} extra bytes. The final size"
  1043. f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may"
  1044. " silently ignore cookies larger than this.",
  1045. stacklevel=2,
  1046. )
  1047. return rv
  1048. def is_byte_range_valid(
  1049. start: int | None, stop: int | None, length: int | None
  1050. ) -> bool:
  1051. """Checks if a given byte content range is valid for the given length.
  1052. .. versionadded:: 0.7
  1053. """
  1054. if (start is None) != (stop is None):
  1055. return False
  1056. elif start is None:
  1057. return length is None or length >= 0
  1058. elif length is None:
  1059. return 0 <= start < stop # type: ignore
  1060. elif start >= stop: # type: ignore
  1061. return False
  1062. return 0 <= start < length
  1063. # circular dependencies
  1064. from . import datastructures as ds
  1065. from .sansio import http as _sansio_http