http.py 47 KB

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