http.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  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(value)
  143. if not value:
  144. return '""'
  145. if allow_token:
  146. token_chars = _token_chars
  147. if token_chars.issuperset(value):
  148. return value
  149. value = value.replace("\\", "\\\\").replace('"', '\\"')
  150. return f'"{value}"'
  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. ...
  428. @t.overload
  429. def parse_accept_header(value: str | None, cls: type[_TAnyAccept]) -> _TAnyAccept:
  430. ...
  431. def parse_accept_header(
  432. value: str | None, cls: type[_TAnyAccept] | None = None
  433. ) -> _TAnyAccept:
  434. """Parse an ``Accept`` header according to
  435. `RFC 9110 <https://httpwg.org/specs/rfc9110.html#field.accept>`__.
  436. Returns an :class:`.Accept` instance, which can sort and inspect items based on
  437. their quality parameter. When parsing ``Accept-Charset``, ``Accept-Encoding``, or
  438. ``Accept-Language``, pass the appropriate :class:`.Accept` subclass.
  439. :param value: The header value to parse.
  440. :param cls: The :class:`.Accept` class to wrap the result in.
  441. :return: An instance of ``cls``.
  442. .. versionchanged:: 2.3
  443. Parse according to RFC 9110. Items with invalid ``q`` values are skipped.
  444. """
  445. if cls is None:
  446. cls = t.cast(t.Type[_TAnyAccept], ds.Accept)
  447. if not value:
  448. return cls(None)
  449. result = []
  450. for item in parse_list_header(value):
  451. item, options = parse_options_header(item)
  452. if "q" in options:
  453. # pop q, remaining options are reconstructed
  454. q_str = options.pop("q").strip()
  455. if _q_value_re.fullmatch(q_str) is None:
  456. # ignore an invalid q
  457. continue
  458. q = float(q_str)
  459. if q < 0 or q > 1:
  460. # ignore an invalid q
  461. continue
  462. else:
  463. q = 1
  464. if options:
  465. # reconstruct the media type with any options
  466. item = dump_options_header(item, options)
  467. result.append((item, q))
  468. return cls(result)
  469. _TAnyCC = t.TypeVar("_TAnyCC", bound="ds.cache_control._CacheControl")
  470. _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]]
  471. @t.overload
  472. def parse_cache_control_header(
  473. value: str | None, on_update: _t_cc_update, cls: None = None
  474. ) -> ds.RequestCacheControl:
  475. ...
  476. @t.overload
  477. def parse_cache_control_header(
  478. value: str | None, on_update: _t_cc_update, cls: type[_TAnyCC]
  479. ) -> _TAnyCC:
  480. ...
  481. def parse_cache_control_header(
  482. value: str | None,
  483. on_update: _t_cc_update = None,
  484. cls: type[_TAnyCC] | None = None,
  485. ) -> _TAnyCC:
  486. """Parse a cache control header. The RFC differs between response and
  487. request cache control, this method does not. It's your responsibility
  488. to not use the wrong control statements.
  489. .. versionadded:: 0.5
  490. The `cls` was added. If not specified an immutable
  491. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  492. :param value: a cache control header to be parsed.
  493. :param on_update: an optional callable that is called every time a value
  494. on the :class:`~werkzeug.datastructures.CacheControl`
  495. object is changed.
  496. :param cls: the class for the returned object. By default
  497. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  498. :return: a `cls` object.
  499. """
  500. if cls is None:
  501. cls = t.cast(t.Type[_TAnyCC], ds.RequestCacheControl)
  502. if not value:
  503. return cls((), on_update)
  504. return cls(parse_dict_header(value), on_update)
  505. _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy")
  506. _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]]
  507. @t.overload
  508. def parse_csp_header(
  509. value: str | None, on_update: _t_csp_update, cls: None = None
  510. ) -> ds.ContentSecurityPolicy:
  511. ...
  512. @t.overload
  513. def parse_csp_header(
  514. value: str | None, on_update: _t_csp_update, cls: type[_TAnyCSP]
  515. ) -> _TAnyCSP:
  516. ...
  517. def parse_csp_header(
  518. value: str | None,
  519. on_update: _t_csp_update = None,
  520. cls: type[_TAnyCSP] | None = None,
  521. ) -> _TAnyCSP:
  522. """Parse a Content Security Policy header.
  523. .. versionadded:: 1.0.0
  524. Support for Content Security Policy headers was added.
  525. :param value: a csp header to be parsed.
  526. :param on_update: an optional callable that is called every time a value
  527. on the object is changed.
  528. :param cls: the class for the returned object. By default
  529. :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
  530. :return: a `cls` object.
  531. """
  532. if cls is None:
  533. cls = t.cast(t.Type[_TAnyCSP], ds.ContentSecurityPolicy)
  534. if value is None:
  535. return cls((), on_update)
  536. items = []
  537. for policy in value.split(";"):
  538. policy = policy.strip()
  539. # Ignore badly formatted policies (no space)
  540. if " " in policy:
  541. directive, value = policy.strip().split(" ", 1)
  542. items.append((directive.strip(), value.strip()))
  543. return cls(items, on_update)
  544. def parse_set_header(
  545. value: str | None,
  546. on_update: t.Callable[[ds.HeaderSet], None] | None = None,
  547. ) -> ds.HeaderSet:
  548. """Parse a set-like header and return a
  549. :class:`~werkzeug.datastructures.HeaderSet` object:
  550. >>> hs = parse_set_header('token, "quoted value"')
  551. The return value is an object that treats the items case-insensitively
  552. and keeps the order of the items:
  553. >>> 'TOKEN' in hs
  554. True
  555. >>> hs.index('quoted value')
  556. 1
  557. >>> hs
  558. HeaderSet(['token', 'quoted value'])
  559. To create a header from the :class:`HeaderSet` again, use the
  560. :func:`dump_header` function.
  561. :param value: a set header to be parsed.
  562. :param on_update: an optional callable that is called every time a
  563. value on the :class:`~werkzeug.datastructures.HeaderSet`
  564. object is changed.
  565. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  566. """
  567. if not value:
  568. return ds.HeaderSet(None, on_update)
  569. return ds.HeaderSet(parse_list_header(value), on_update)
  570. def parse_if_range_header(value: str | None) -> ds.IfRange:
  571. """Parses an if-range header which can be an etag or a date. Returns
  572. a :class:`~werkzeug.datastructures.IfRange` object.
  573. .. versionchanged:: 2.0
  574. If the value represents a datetime, it is timezone-aware.
  575. .. versionadded:: 0.7
  576. """
  577. if not value:
  578. return ds.IfRange()
  579. date = parse_date(value)
  580. if date is not None:
  581. return ds.IfRange(date=date)
  582. # drop weakness information
  583. return ds.IfRange(unquote_etag(value)[0])
  584. def parse_range_header(
  585. value: str | None, make_inclusive: bool = True
  586. ) -> ds.Range | None:
  587. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  588. object. If the header is missing or malformed `None` is returned.
  589. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  590. non-inclusive.
  591. .. versionadded:: 0.7
  592. """
  593. if not value or "=" not in value:
  594. return None
  595. ranges = []
  596. last_end = 0
  597. units, rng = value.split("=", 1)
  598. units = units.strip().lower()
  599. for item in rng.split(","):
  600. item = item.strip()
  601. if "-" not in item:
  602. return None
  603. if item.startswith("-"):
  604. if last_end < 0:
  605. return None
  606. try:
  607. begin = _plain_int(item)
  608. except ValueError:
  609. return None
  610. end = None
  611. last_end = -1
  612. elif "-" in item:
  613. begin_str, end_str = item.split("-", 1)
  614. begin_str = begin_str.strip()
  615. end_str = end_str.strip()
  616. try:
  617. begin = _plain_int(begin_str)
  618. except ValueError:
  619. return None
  620. if begin < last_end or last_end < 0:
  621. return None
  622. if end_str:
  623. try:
  624. end = _plain_int(end_str) + 1
  625. except ValueError:
  626. return None
  627. if begin >= end:
  628. return None
  629. else:
  630. end = None
  631. last_end = end if end is not None else -1
  632. ranges.append((begin, end))
  633. return ds.Range(units, ranges)
  634. def parse_content_range_header(
  635. value: str | None,
  636. on_update: t.Callable[[ds.ContentRange], None] | None = None,
  637. ) -> ds.ContentRange | None:
  638. """Parses a range header into a
  639. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  640. parsing is not possible.
  641. .. versionadded:: 0.7
  642. :param value: a content range header to be parsed.
  643. :param on_update: an optional callable that is called every time a value
  644. on the :class:`~werkzeug.datastructures.ContentRange`
  645. object is changed.
  646. """
  647. if value is None:
  648. return None
  649. try:
  650. units, rangedef = (value or "").strip().split(None, 1)
  651. except ValueError:
  652. return None
  653. if "/" not in rangedef:
  654. return None
  655. rng, length_str = rangedef.split("/", 1)
  656. if length_str == "*":
  657. length = None
  658. else:
  659. try:
  660. length = _plain_int(length_str)
  661. except ValueError:
  662. return None
  663. if rng == "*":
  664. if not is_byte_range_valid(None, None, length):
  665. return None
  666. return ds.ContentRange(units, None, None, length, on_update=on_update)
  667. elif "-" not in rng:
  668. return None
  669. start_str, stop_str = rng.split("-", 1)
  670. try:
  671. start = _plain_int(start_str)
  672. stop = _plain_int(stop_str) + 1
  673. except ValueError:
  674. return None
  675. if is_byte_range_valid(start, stop, length):
  676. return ds.ContentRange(units, start, stop, length, on_update=on_update)
  677. return None
  678. def quote_etag(etag: str, weak: bool = False) -> str:
  679. """Quote an etag.
  680. :param etag: the etag to quote.
  681. :param weak: set to `True` to tag it "weak".
  682. """
  683. if '"' in etag:
  684. raise ValueError("invalid etag")
  685. etag = f'"{etag}"'
  686. if weak:
  687. etag = f"W/{etag}"
  688. return etag
  689. def unquote_etag(
  690. etag: str | None,
  691. ) -> tuple[str, bool] | tuple[None, None]:
  692. """Unquote a single etag:
  693. >>> unquote_etag('W/"bar"')
  694. ('bar', True)
  695. >>> unquote_etag('"bar"')
  696. ('bar', False)
  697. :param etag: the etag identifier to unquote.
  698. :return: a ``(etag, weak)`` tuple.
  699. """
  700. if not etag:
  701. return None, None
  702. etag = etag.strip()
  703. weak = False
  704. if etag.startswith(("W/", "w/")):
  705. weak = True
  706. etag = etag[2:]
  707. if etag[:1] == etag[-1:] == '"':
  708. etag = etag[1:-1]
  709. return etag, weak
  710. def parse_etags(value: str | None) -> ds.ETags:
  711. """Parse an etag header.
  712. :param value: the tag header to parse
  713. :return: an :class:`~werkzeug.datastructures.ETags` object.
  714. """
  715. if not value:
  716. return ds.ETags()
  717. strong = []
  718. weak = []
  719. end = len(value)
  720. pos = 0
  721. while pos < end:
  722. match = _etag_re.match(value, pos)
  723. if match is None:
  724. break
  725. is_weak, quoted, raw = match.groups()
  726. if raw == "*":
  727. return ds.ETags(star_tag=True)
  728. elif quoted:
  729. raw = quoted
  730. if is_weak:
  731. weak.append(raw)
  732. else:
  733. strong.append(raw)
  734. pos = match.end()
  735. return ds.ETags(strong, weak)
  736. def generate_etag(data: bytes) -> str:
  737. """Generate an etag for some data.
  738. .. versionchanged:: 2.0
  739. Use SHA-1. MD5 may not be available in some environments.
  740. """
  741. return sha1(data).hexdigest()
  742. def parse_date(value: str | None) -> datetime | None:
  743. """Parse an :rfc:`2822` date into a timezone-aware
  744. :class:`datetime.datetime` object, or ``None`` if parsing fails.
  745. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
  746. returns ``None`` if parsing fails instead of raising an exception,
  747. and always returns a timezone-aware datetime object. If the string
  748. doesn't have timezone information, it is assumed to be UTC.
  749. :param value: A string with a supported date format.
  750. .. versionchanged:: 2.0
  751. Return a timezone-aware datetime object. Use
  752. ``email.utils.parsedate_to_datetime``.
  753. """
  754. if value is None:
  755. return None
  756. try:
  757. dt = email.utils.parsedate_to_datetime(value)
  758. except (TypeError, ValueError):
  759. return None
  760. if dt.tzinfo is None:
  761. return dt.replace(tzinfo=timezone.utc)
  762. return dt
  763. def http_date(
  764. timestamp: datetime | date | int | float | struct_time | None = None,
  765. ) -> str:
  766. """Format a datetime object or timestamp into an :rfc:`2822` date
  767. string.
  768. This is a wrapper for :func:`email.utils.format_datetime`. It
  769. assumes naive datetime objects are in UTC instead of raising an
  770. exception.
  771. :param timestamp: The datetime or timestamp to format. Defaults to
  772. the current time.
  773. .. versionchanged:: 2.0
  774. Use ``email.utils.format_datetime``. Accept ``date`` objects.
  775. """
  776. if isinstance(timestamp, date):
  777. if not isinstance(timestamp, datetime):
  778. # Assume plain date is midnight UTC.
  779. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc)
  780. else:
  781. # Ensure datetime is timezone-aware.
  782. timestamp = _dt_as_utc(timestamp)
  783. return email.utils.format_datetime(timestamp, usegmt=True)
  784. if isinstance(timestamp, struct_time):
  785. timestamp = mktime(timestamp)
  786. return email.utils.formatdate(timestamp, usegmt=True)
  787. def parse_age(value: str | None = None) -> timedelta | None:
  788. """Parses a base-10 integer count of seconds into a timedelta.
  789. If parsing fails, the return value is `None`.
  790. :param value: a string consisting of an integer represented in base-10
  791. :return: a :class:`datetime.timedelta` object or `None`.
  792. """
  793. if not value:
  794. return None
  795. try:
  796. seconds = int(value)
  797. except ValueError:
  798. return None
  799. if seconds < 0:
  800. return None
  801. try:
  802. return timedelta(seconds=seconds)
  803. except OverflowError:
  804. return None
  805. def dump_age(age: timedelta | int | None = None) -> str | None:
  806. """Formats the duration as a base-10 integer.
  807. :param age: should be an integer number of seconds,
  808. a :class:`datetime.timedelta` object, or,
  809. if the age is unknown, `None` (default).
  810. """
  811. if age is None:
  812. return None
  813. if isinstance(age, timedelta):
  814. age = int(age.total_seconds())
  815. else:
  816. age = int(age)
  817. if age < 0:
  818. raise ValueError("age cannot be negative")
  819. return str(age)
  820. def is_resource_modified(
  821. environ: WSGIEnvironment,
  822. etag: str | None = None,
  823. data: bytes | None = None,
  824. last_modified: datetime | str | None = None,
  825. ignore_if_range: bool = True,
  826. ) -> bool:
  827. """Convenience method for conditional requests.
  828. :param environ: the WSGI environment of the request to be checked.
  829. :param etag: the etag for the response for comparison.
  830. :param data: or alternatively the data of the response to automatically
  831. generate an etag using :func:`generate_etag`.
  832. :param last_modified: an optional date of the last modification.
  833. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  834. account.
  835. :return: `True` if the resource was modified, otherwise `False`.
  836. .. versionchanged:: 2.0
  837. SHA-1 is used to generate an etag value for the data. MD5 may
  838. not be available in some environments.
  839. .. versionchanged:: 1.0.0
  840. The check is run for methods other than ``GET`` and ``HEAD``.
  841. """
  842. return _sansio_http.is_resource_modified(
  843. http_range=environ.get("HTTP_RANGE"),
  844. http_if_range=environ.get("HTTP_IF_RANGE"),
  845. http_if_modified_since=environ.get("HTTP_IF_MODIFIED_SINCE"),
  846. http_if_none_match=environ.get("HTTP_IF_NONE_MATCH"),
  847. http_if_match=environ.get("HTTP_IF_MATCH"),
  848. etag=etag,
  849. data=data,
  850. last_modified=last_modified,
  851. ignore_if_range=ignore_if_range,
  852. )
  853. def remove_entity_headers(
  854. headers: ds.Headers | list[tuple[str, str]],
  855. allowed: t.Iterable[str] = ("expires", "content-location"),
  856. ) -> None:
  857. """Remove all entity headers from a list or :class:`Headers` object. This
  858. operation works in-place. `Expires` and `Content-Location` headers are
  859. by default not removed. The reason for this is :rfc:`2616` section
  860. 10.3.5 which specifies some entity headers that should be sent.
  861. .. versionchanged:: 0.5
  862. added `allowed` parameter.
  863. :param headers: a list or :class:`Headers` object.
  864. :param allowed: a list of headers that should still be allowed even though
  865. they are entity headers.
  866. """
  867. allowed = {x.lower() for x in allowed}
  868. headers[:] = [
  869. (key, value)
  870. for key, value in headers
  871. if not is_entity_header(key) or key.lower() in allowed
  872. ]
  873. def remove_hop_by_hop_headers(headers: ds.Headers | list[tuple[str, str]]) -> None:
  874. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  875. :class:`Headers` object. This operation works in-place.
  876. .. versionadded:: 0.5
  877. :param headers: a list or :class:`Headers` object.
  878. """
  879. headers[:] = [
  880. (key, value) for key, value in headers if not is_hop_by_hop_header(key)
  881. ]
  882. def is_entity_header(header: str) -> bool:
  883. """Check if a header is an entity header.
  884. .. versionadded:: 0.5
  885. :param header: the header to test.
  886. :return: `True` if it's an entity header, `False` otherwise.
  887. """
  888. return header.lower() in _entity_headers
  889. def is_hop_by_hop_header(header: str) -> bool:
  890. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  891. .. versionadded:: 0.5
  892. :param header: the header to test.
  893. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
  894. """
  895. return header.lower() in _hop_by_hop_headers
  896. def parse_cookie(
  897. header: WSGIEnvironment | str | None,
  898. cls: type[ds.MultiDict] | None = None,
  899. ) -> ds.MultiDict[str, str]:
  900. """Parse a cookie from a string or WSGI environ.
  901. The same key can be provided multiple times, the values are stored
  902. in-order. The default :class:`MultiDict` will have the first value
  903. first, and all values can be retrieved with
  904. :meth:`MultiDict.getlist`.
  905. :param header: The cookie header as a string, or a WSGI environ dict
  906. with a ``HTTP_COOKIE`` key.
  907. :param cls: A dict-like class to store the parsed cookies in.
  908. Defaults to :class:`MultiDict`.
  909. .. versionchanged:: 3.0
  910. Passing bytes, and the ``charset`` and ``errors`` parameters, were removed.
  911. .. versionchanged:: 1.0
  912. Returns a :class:`MultiDict` instead of a ``TypeConversionDict``.
  913. .. versionchanged:: 0.5
  914. Returns a :class:`TypeConversionDict` instead of a regular dict. The ``cls``
  915. parameter was added.
  916. """
  917. if isinstance(header, dict):
  918. cookie = header.get("HTTP_COOKIE")
  919. else:
  920. cookie = header
  921. if cookie:
  922. cookie = cookie.encode("latin1").decode()
  923. return _sansio_http.parse_cookie(cookie=cookie, cls=cls)
  924. _cookie_no_quote_re = re.compile(r"[\w!#$%&'()*+\-./:<=>?@\[\]^`{|}~]*", re.A)
  925. _cookie_slash_re = re.compile(rb"[\x00-\x19\",;\\\x7f-\xff]", re.A)
  926. _cookie_slash_map = {b'"': b'\\"', b"\\": b"\\\\"}
  927. _cookie_slash_map.update(
  928. (v.to_bytes(1, "big"), b"\\%03o" % v)
  929. for v in [*range(0x20), *b",;", *range(0x7F, 256)]
  930. )
  931. def dump_cookie(
  932. key: str,
  933. value: str = "",
  934. max_age: timedelta | int | None = None,
  935. expires: str | datetime | int | float | None = None,
  936. path: str | None = "/",
  937. domain: str | None = None,
  938. secure: bool = False,
  939. httponly: bool = False,
  940. sync_expires: bool = True,
  941. max_size: int = 4093,
  942. samesite: str | None = None,
  943. ) -> str:
  944. """Create a Set-Cookie header without the ``Set-Cookie`` prefix.
  945. The return value is usually restricted to ascii as the vast majority
  946. of values are properly escaped, but that is no guarantee. It's
  947. tunneled through latin1 as required by :pep:`3333`.
  948. The return value is not ASCII safe if the key contains unicode
  949. characters. This is technically against the specification but
  950. happens in the wild. It's strongly recommended to not use
  951. non-ASCII values for the keys.
  952. :param max_age: should be a number of seconds, or `None` (default) if
  953. the cookie should last only as long as the client's
  954. browser session. Additionally `timedelta` objects
  955. are accepted, too.
  956. :param expires: should be a `datetime` object or unix timestamp.
  957. :param path: limits the cookie to a given path, per default it will
  958. span the whole domain.
  959. :param domain: Use this if you want to set a cross-domain cookie. For
  960. example, ``domain="example.com"`` will set a cookie
  961. that is readable by the domain ``www.example.com``,
  962. ``foo.example.com`` etc. Otherwise, a cookie will only
  963. be readable by the domain that set it.
  964. :param secure: The cookie will only be available via HTTPS
  965. :param httponly: disallow JavaScript to access the cookie. This is an
  966. extension to the cookie standard and probably not
  967. supported by all browsers.
  968. :param charset: the encoding for string values.
  969. :param sync_expires: automatically set expires if max_age is defined
  970. but expires not.
  971. :param max_size: Warn if the final header value exceeds this size. The
  972. default, 4093, should be safely `supported by most browsers
  973. <cookie_>`_. Set to 0 to disable this check.
  974. :param samesite: Limits the scope of the cookie such that it will
  975. only be attached to requests if those requests are same-site.
  976. .. _`cookie`: http://browsercookielimits.squawky.net/
  977. .. versionchanged:: 3.0
  978. Passing bytes, and the ``charset`` parameter, were removed.
  979. .. versionchanged:: 2.3.3
  980. The ``path`` parameter is ``/`` by default.
  981. .. versionchanged:: 2.3.1
  982. The value allows more characters without quoting.
  983. .. versionchanged:: 2.3
  984. ``localhost`` and other names without a dot are allowed for the domain. A
  985. leading dot is ignored.
  986. .. versionchanged:: 2.3
  987. The ``path`` parameter is ``None`` by default.
  988. .. versionchanged:: 1.0.0
  989. The string ``'None'`` is accepted for ``samesite``.
  990. """
  991. if path is not None:
  992. # safe = https://url.spec.whatwg.org/#url-path-segment-string
  993. # as well as percent for things that are already quoted
  994. # excluding semicolon since it's part of the header syntax
  995. path = quote(path, safe="%!$&'()*+,/:=@")
  996. if domain:
  997. domain = domain.partition(":")[0].lstrip(".").encode("idna").decode("ascii")
  998. if isinstance(max_age, timedelta):
  999. max_age = int(max_age.total_seconds())
  1000. if expires is not None:
  1001. if not isinstance(expires, str):
  1002. expires = http_date(expires)
  1003. elif max_age is not None and sync_expires:
  1004. expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)
  1005. if samesite is not None:
  1006. samesite = samesite.title()
  1007. if samesite not in {"Strict", "Lax", "None"}:
  1008. raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
  1009. # Quote value if it contains characters not allowed by RFC 6265. Slash-escape with
  1010. # three octal digits, which matches http.cookies, although the RFC suggests base64.
  1011. if not _cookie_no_quote_re.fullmatch(value):
  1012. # Work with bytes here, since a UTF-8 character could be multiple bytes.
  1013. value = _cookie_slash_re.sub(
  1014. lambda m: _cookie_slash_map[m.group()], value.encode()
  1015. ).decode("ascii")
  1016. value = f'"{value}"'
  1017. # Send a non-ASCII key as mojibake. Everything else should already be ASCII.
  1018. # TODO Remove encoding dance, it seems like clients accept UTF-8 keys
  1019. buf = [f"{key.encode().decode('latin1')}={value}"]
  1020. for k, v in (
  1021. ("Domain", domain),
  1022. ("Expires", expires),
  1023. ("Max-Age", max_age),
  1024. ("Secure", secure),
  1025. ("HttpOnly", httponly),
  1026. ("Path", path),
  1027. ("SameSite", samesite),
  1028. ):
  1029. if v is None or v is False:
  1030. continue
  1031. if v is True:
  1032. buf.append(k)
  1033. continue
  1034. buf.append(f"{k}={v}")
  1035. rv = "; ".join(buf)
  1036. # Warn if the final value of the cookie is larger than the limit. If the cookie is
  1037. # too large, then it may be silently ignored by the browser, which can be quite hard
  1038. # to debug.
  1039. cookie_size = len(rv)
  1040. if max_size and cookie_size > max_size:
  1041. value_size = len(value)
  1042. warnings.warn(
  1043. f"The '{key}' cookie is too large: the value was {value_size} bytes but the"
  1044. f" header required {cookie_size - value_size} extra bytes. The final size"
  1045. f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may"
  1046. " silently ignore cookies larger than this.",
  1047. stacklevel=2,
  1048. )
  1049. return rv
  1050. def is_byte_range_valid(
  1051. start: int | None, stop: int | None, length: int | None
  1052. ) -> bool:
  1053. """Checks if a given byte content range is valid for the given length.
  1054. .. versionadded:: 0.7
  1055. """
  1056. if (start is None) != (stop is None):
  1057. return False
  1058. elif start is None:
  1059. return length is None or length >= 0
  1060. elif length is None:
  1061. return 0 <= start < stop # type: ignore
  1062. elif start >= stop: # type: ignore
  1063. return False
  1064. return 0 <= start < length
  1065. # circular dependencies
  1066. from . import datastructures as ds
  1067. from .sansio import http as _sansio_http