http.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. import base64
  2. import email.utils
  3. import re
  4. import typing
  5. import typing as t
  6. import warnings
  7. from datetime import date
  8. from datetime import datetime
  9. from datetime import time
  10. from datetime import timedelta
  11. from datetime import timezone
  12. from enum import Enum
  13. from hashlib import sha1
  14. from time import mktime
  15. from time import struct_time
  16. from urllib.parse import unquote_to_bytes as _unquote
  17. from urllib.request import parse_http_list as _parse_list_header
  18. from ._internal import _cookie_parse_impl
  19. from ._internal import _cookie_quote
  20. from ._internal import _make_cookie_domain
  21. from ._internal import _to_bytes
  22. from ._internal import _to_str
  23. from ._internal import _wsgi_decoding_dance
  24. from werkzeug._internal import _dt_as_utc
  25. if t.TYPE_CHECKING:
  26. import typing_extensions as te
  27. from _typeshed.wsgi import WSGIEnvironment
  28. # for explanation of "media-range", etc. see Sections 5.3.{1,2} of RFC 7231
  29. _accept_re = re.compile(
  30. r"""
  31. ( # media-range capturing-parenthesis
  32. [^\s;,]+ # type/subtype
  33. (?:[ \t]*;[ \t]* # ";"
  34. (?: # parameter non-capturing-parenthesis
  35. [^\s;,q][^\s;,]* # token that doesn't start with "q"
  36. | # or
  37. q[^\s;,=][^\s;,]* # token that is more than just "q"
  38. )
  39. )* # zero or more parameters
  40. ) # end of media-range
  41. (?:[ \t]*;[ \t]*q= # weight is a "q" parameter
  42. (\d*(?:\.\d+)?) # qvalue capturing-parentheses
  43. [^,]* # "extension" accept params: who cares?
  44. )? # accept params are optional
  45. """,
  46. re.VERBOSE,
  47. )
  48. _token_chars = frozenset(
  49. "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"
  50. )
  51. _etag_re = re.compile(r'([Ww]/)?(?:"(.*?)"|(.*?))(?:\s*,\s*|$)')
  52. _option_header_piece_re = re.compile(
  53. r"""
  54. ;\s*,?\s* # newlines were replaced with commas
  55. (?P<key>
  56. "[^"\\]*(?:\\.[^"\\]*)*" # quoted string
  57. |
  58. [^\s;,=*]+ # token
  59. )
  60. (?:\*(?P<count>\d+))? # *1, optional continuation index
  61. \s*
  62. (?: # optionally followed by =value
  63. (?: # equals sign, possibly with encoding
  64. \*\s*=\s* # * indicates extended notation
  65. (?: # optional encoding
  66. (?P<encoding>[^\s]+?)
  67. '(?P<language>[^\s]*?)'
  68. )?
  69. |
  70. =\s* # basic notation
  71. )
  72. (?P<value>
  73. "[^"\\]*(?:\\.[^"\\]*)*" # quoted string
  74. |
  75. [^;,]+ # token
  76. )?
  77. )?
  78. \s*
  79. """,
  80. flags=re.VERBOSE,
  81. )
  82. _option_header_start_mime_type = re.compile(r",\s*([^;,\s]+)([;,]\s*.+)?")
  83. _entity_headers = frozenset(
  84. [
  85. "allow",
  86. "content-encoding",
  87. "content-language",
  88. "content-length",
  89. "content-location",
  90. "content-md5",
  91. "content-range",
  92. "content-type",
  93. "expires",
  94. "last-modified",
  95. ]
  96. )
  97. _hop_by_hop_headers = frozenset(
  98. [
  99. "connection",
  100. "keep-alive",
  101. "proxy-authenticate",
  102. "proxy-authorization",
  103. "te",
  104. "trailer",
  105. "transfer-encoding",
  106. "upgrade",
  107. ]
  108. )
  109. HTTP_STATUS_CODES = {
  110. 100: "Continue",
  111. 101: "Switching Protocols",
  112. 102: "Processing",
  113. 103: "Early Hints", # see RFC 8297
  114. 200: "OK",
  115. 201: "Created",
  116. 202: "Accepted",
  117. 203: "Non Authoritative Information",
  118. 204: "No Content",
  119. 205: "Reset Content",
  120. 206: "Partial Content",
  121. 207: "Multi Status",
  122. 208: "Already Reported", # see RFC 5842
  123. 226: "IM Used", # see RFC 3229
  124. 300: "Multiple Choices",
  125. 301: "Moved Permanently",
  126. 302: "Found",
  127. 303: "See Other",
  128. 304: "Not Modified",
  129. 305: "Use Proxy",
  130. 306: "Switch Proxy", # unused
  131. 307: "Temporary Redirect",
  132. 308: "Permanent Redirect",
  133. 400: "Bad Request",
  134. 401: "Unauthorized",
  135. 402: "Payment Required", # unused
  136. 403: "Forbidden",
  137. 404: "Not Found",
  138. 405: "Method Not Allowed",
  139. 406: "Not Acceptable",
  140. 407: "Proxy Authentication Required",
  141. 408: "Request Timeout",
  142. 409: "Conflict",
  143. 410: "Gone",
  144. 411: "Length Required",
  145. 412: "Precondition Failed",
  146. 413: "Request Entity Too Large",
  147. 414: "Request URI Too Long",
  148. 415: "Unsupported Media Type",
  149. 416: "Requested Range Not Satisfiable",
  150. 417: "Expectation Failed",
  151. 418: "I'm a teapot", # see RFC 2324
  152. 421: "Misdirected Request", # see RFC 7540
  153. 422: "Unprocessable Entity",
  154. 423: "Locked",
  155. 424: "Failed Dependency",
  156. 425: "Too Early", # see RFC 8470
  157. 426: "Upgrade Required",
  158. 428: "Precondition Required", # see RFC 6585
  159. 429: "Too Many Requests",
  160. 431: "Request Header Fields Too Large",
  161. 449: "Retry With", # proprietary MS extension
  162. 451: "Unavailable For Legal Reasons",
  163. 500: "Internal Server Error",
  164. 501: "Not Implemented",
  165. 502: "Bad Gateway",
  166. 503: "Service Unavailable",
  167. 504: "Gateway Timeout",
  168. 505: "HTTP Version Not Supported",
  169. 506: "Variant Also Negotiates", # see RFC 2295
  170. 507: "Insufficient Storage",
  171. 508: "Loop Detected", # see RFC 5842
  172. 510: "Not Extended",
  173. 511: "Network Authentication Failed",
  174. }
  175. class COEP(Enum):
  176. """Cross Origin Embedder Policies"""
  177. UNSAFE_NONE = "unsafe-none"
  178. REQUIRE_CORP = "require-corp"
  179. class COOP(Enum):
  180. """Cross Origin Opener Policies"""
  181. UNSAFE_NONE = "unsafe-none"
  182. SAME_ORIGIN_ALLOW_POPUPS = "same-origin-allow-popups"
  183. SAME_ORIGIN = "same-origin"
  184. def quote_header_value(
  185. value: t.Union[str, int], extra_chars: str = "", allow_token: bool = True
  186. ) -> str:
  187. """Quote a header value if necessary.
  188. .. versionadded:: 0.5
  189. :param value: the value to quote.
  190. :param extra_chars: a list of extra characters to skip quoting.
  191. :param allow_token: if this is enabled token values are returned
  192. unchanged.
  193. """
  194. if isinstance(value, bytes):
  195. value = value.decode("latin1")
  196. value = str(value)
  197. if allow_token:
  198. token_chars = _token_chars | set(extra_chars)
  199. if set(value).issubset(token_chars):
  200. return value
  201. value = value.replace("\\", "\\\\").replace('"', '\\"')
  202. return f'"{value}"'
  203. def unquote_header_value(value: str, is_filename: bool = False) -> str:
  204. r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
  205. This does not use the real unquoting but what browsers are actually
  206. using for quoting.
  207. .. versionadded:: 0.5
  208. :param value: the header value to unquote.
  209. :param is_filename: The value represents a filename or path.
  210. """
  211. if value and value[0] == value[-1] == '"':
  212. # this is not the real unquoting, but fixing this so that the
  213. # RFC is met will result in bugs with internet explorer and
  214. # probably some other browsers as well. IE for example is
  215. # uploading files with "C:\foo\bar.txt" as filename
  216. value = value[1:-1]
  217. # if this is a filename and the starting characters look like
  218. # a UNC path, then just return the value without quotes. Using the
  219. # replace sequence below on a UNC path has the effect of turning
  220. # the leading double slash into a single slash and then
  221. # _fix_ie_filename() doesn't work correctly. See #458.
  222. if not is_filename or value[:2] != "\\\\":
  223. return value.replace("\\\\", "\\").replace('\\"', '"')
  224. return value
  225. def dump_options_header(
  226. header: t.Optional[str], options: t.Mapping[str, t.Optional[t.Union[str, int]]]
  227. ) -> str:
  228. """The reverse function to :func:`parse_options_header`.
  229. :param header: the header to dump
  230. :param options: a dict of options to append.
  231. """
  232. segments = []
  233. if header is not None:
  234. segments.append(header)
  235. for key, value in options.items():
  236. if value is None:
  237. segments.append(key)
  238. else:
  239. segments.append(f"{key}={quote_header_value(value)}")
  240. return "; ".join(segments)
  241. def dump_header(
  242. iterable: t.Union[t.Dict[str, t.Union[str, int]], t.Iterable[str]],
  243. allow_token: bool = True,
  244. ) -> str:
  245. """Dump an HTTP header again. This is the reversal of
  246. :func:`parse_list_header`, :func:`parse_set_header` and
  247. :func:`parse_dict_header`. This also quotes strings that include an
  248. equals sign unless you pass it as dict of key, value pairs.
  249. >>> dump_header({'foo': 'bar baz'})
  250. 'foo="bar baz"'
  251. >>> dump_header(('foo', 'bar baz'))
  252. 'foo, "bar baz"'
  253. :param iterable: the iterable or dict of values to quote.
  254. :param allow_token: if set to `False` tokens as values are disallowed.
  255. See :func:`quote_header_value` for more details.
  256. """
  257. if isinstance(iterable, dict):
  258. items = []
  259. for key, value in iterable.items():
  260. if value is None:
  261. items.append(key)
  262. else:
  263. items.append(
  264. f"{key}={quote_header_value(value, allow_token=allow_token)}"
  265. )
  266. else:
  267. items = [quote_header_value(x, allow_token=allow_token) for x in iterable]
  268. return ", ".join(items)
  269. def dump_csp_header(header: "ds.ContentSecurityPolicy") -> str:
  270. """Dump a Content Security Policy header.
  271. These are structured into policies such as "default-src 'self';
  272. script-src 'self'".
  273. .. versionadded:: 1.0.0
  274. Support for Content Security Policy headers was added.
  275. """
  276. return "; ".join(f"{key} {value}" for key, value in header.items())
  277. def parse_list_header(value: str) -> t.List[str]:
  278. """Parse lists as described by RFC 2068 Section 2.
  279. In particular, parse comma-separated lists where the elements of
  280. the list may include quoted-strings. A quoted-string could
  281. contain a comma. A non-quoted string could have quotes in the
  282. middle. Quotes are removed automatically after parsing.
  283. It basically works like :func:`parse_set_header` just that items
  284. may appear multiple times and case sensitivity is preserved.
  285. The return value is a standard :class:`list`:
  286. >>> parse_list_header('token, "quoted value"')
  287. ['token', 'quoted value']
  288. To create a header from the :class:`list` again, use the
  289. :func:`dump_header` function.
  290. :param value: a string with a list header.
  291. :return: :class:`list`
  292. """
  293. result = []
  294. for item in _parse_list_header(value):
  295. if item[:1] == item[-1:] == '"':
  296. item = unquote_header_value(item[1:-1])
  297. result.append(item)
  298. return result
  299. def parse_dict_header(value: str, cls: t.Type[dict] = dict) -> t.Dict[str, str]:
  300. """Parse lists of key, value pairs as described by RFC 2068 Section 2 and
  301. convert them into a python dict (or any other mapping object created from
  302. the type with a dict like interface provided by the `cls` argument):
  303. >>> d = parse_dict_header('foo="is a fish", bar="as well"')
  304. >>> type(d) is dict
  305. True
  306. >>> sorted(d.items())
  307. [('bar', 'as well'), ('foo', 'is a fish')]
  308. If there is no value for a key it will be `None`:
  309. >>> parse_dict_header('key_without_value')
  310. {'key_without_value': None}
  311. To create a header from the :class:`dict` again, use the
  312. :func:`dump_header` function.
  313. .. versionchanged:: 0.9
  314. Added support for `cls` argument.
  315. :param value: a string with a dict header.
  316. :param cls: callable to use for storage of parsed results.
  317. :return: an instance of `cls`
  318. """
  319. result = cls()
  320. if isinstance(value, bytes):
  321. value = value.decode("latin1")
  322. for item in _parse_list_header(value):
  323. if "=" not in item:
  324. result[item] = None
  325. continue
  326. name, value = item.split("=", 1)
  327. if value[:1] == value[-1:] == '"':
  328. value = unquote_header_value(value[1:-1])
  329. result[name] = value
  330. return result
  331. def parse_options_header(
  332. value: t.Optional[str], multiple: "te.Literal[None]" = None
  333. ) -> t.Tuple[str, t.Dict[str, str]]:
  334. """Parse a ``Content-Type``-like header into a tuple with the
  335. value and any options:
  336. >>> parse_options_header('text/html; charset=utf8')
  337. ('text/html', {'charset': 'utf8'})
  338. This should is not for ``Cache-Control``-like headers, which use a
  339. different format. For those, use :func:`parse_dict_header`.
  340. :param value: The header value to parse.
  341. .. versionchanged:: 2.1
  342. The ``multiple`` parameter is deprecated and will be removed in
  343. Werkzeug 2.2.
  344. .. versionchanged:: 0.15
  345. :rfc:`2231` parameter continuations are handled.
  346. .. versionadded:: 0.5
  347. """
  348. if multiple is not None:
  349. import warnings
  350. warnings.warn(
  351. "The 'multiple' parameter of 'parse_options_header' is"
  352. " deprecated and will be removed in Werkzeug 2.2.",
  353. DeprecationWarning,
  354. stacklevel=2,
  355. )
  356. if not value:
  357. return "", {}
  358. result: t.List[t.Any] = []
  359. value = "," + value.replace("\n", ",")
  360. while value:
  361. match = _option_header_start_mime_type.match(value)
  362. if not match:
  363. break
  364. result.append(match.group(1)) # mimetype
  365. options: t.Dict[str, str] = {}
  366. # Parse options
  367. rest = match.group(2)
  368. encoding: t.Optional[str]
  369. continued_encoding: t.Optional[str] = None
  370. while rest:
  371. optmatch = _option_header_piece_re.match(rest)
  372. if not optmatch:
  373. break
  374. option, count, encoding, language, option_value = optmatch.groups()
  375. # Continuations don't have to supply the encoding after the
  376. # first line. If we're in a continuation, track the current
  377. # encoding to use for subsequent lines. Reset it when the
  378. # continuation ends.
  379. if not count:
  380. continued_encoding = None
  381. else:
  382. if not encoding:
  383. encoding = continued_encoding
  384. continued_encoding = encoding
  385. option = unquote_header_value(option)
  386. if option_value is not None:
  387. option_value = unquote_header_value(option_value, option == "filename")
  388. if encoding is not None:
  389. option_value = _unquote(option_value).decode(encoding)
  390. if count:
  391. # Continuations append to the existing value. For
  392. # simplicity, this ignores the possibility of
  393. # out-of-order indices, which shouldn't happen anyway.
  394. if option_value is not None:
  395. options[option] = options.get(option, "") + option_value
  396. else:
  397. options[option] = option_value # type: ignore[assignment]
  398. rest = rest[optmatch.end() :]
  399. result.append(options)
  400. if not multiple:
  401. return tuple(result) # type: ignore[return-value]
  402. value = rest
  403. return tuple(result) if result else ("", {}) # type: ignore[return-value]
  404. _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept")
  405. @typing.overload
  406. def parse_accept_header(value: t.Optional[str]) -> "ds.Accept":
  407. ...
  408. @typing.overload
  409. def parse_accept_header(
  410. value: t.Optional[str], cls: t.Type[_TAnyAccept]
  411. ) -> _TAnyAccept:
  412. ...
  413. def parse_accept_header(
  414. value: t.Optional[str], cls: t.Optional[t.Type[_TAnyAccept]] = None
  415. ) -> _TAnyAccept:
  416. """Parses an HTTP Accept-* header. This does not implement a complete
  417. valid algorithm but one that supports at least value and quality
  418. extraction.
  419. Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
  420. tuples sorted by the quality with some additional accessor methods).
  421. The second parameter can be a subclass of :class:`Accept` that is created
  422. with the parsed values and returned.
  423. :param value: the accept header string to be parsed.
  424. :param cls: the wrapper class for the return value (can be
  425. :class:`Accept` or a subclass thereof)
  426. :return: an instance of `cls`.
  427. """
  428. if cls is None:
  429. cls = t.cast(t.Type[_TAnyAccept], ds.Accept)
  430. if not value:
  431. return cls(None)
  432. result = []
  433. for match in _accept_re.finditer(value):
  434. quality_match = match.group(2)
  435. if not quality_match:
  436. quality: float = 1
  437. else:
  438. quality = max(min(float(quality_match), 1), 0)
  439. result.append((match.group(1), quality))
  440. return cls(result)
  441. _TAnyCC = t.TypeVar("_TAnyCC", bound="ds._CacheControl")
  442. _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]]
  443. @typing.overload
  444. def parse_cache_control_header(
  445. value: t.Optional[str], on_update: _t_cc_update, cls: None = None
  446. ) -> "ds.RequestCacheControl":
  447. ...
  448. @typing.overload
  449. def parse_cache_control_header(
  450. value: t.Optional[str], on_update: _t_cc_update, cls: t.Type[_TAnyCC]
  451. ) -> _TAnyCC:
  452. ...
  453. def parse_cache_control_header(
  454. value: t.Optional[str],
  455. on_update: _t_cc_update = None,
  456. cls: t.Optional[t.Type[_TAnyCC]] = None,
  457. ) -> _TAnyCC:
  458. """Parse a cache control header. The RFC differs between response and
  459. request cache control, this method does not. It's your responsibility
  460. to not use the wrong control statements.
  461. .. versionadded:: 0.5
  462. The `cls` was added. If not specified an immutable
  463. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  464. :param value: a cache control header to be parsed.
  465. :param on_update: an optional callable that is called every time a value
  466. on the :class:`~werkzeug.datastructures.CacheControl`
  467. object is changed.
  468. :param cls: the class for the returned object. By default
  469. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  470. :return: a `cls` object.
  471. """
  472. if cls is None:
  473. cls = t.cast(t.Type[_TAnyCC], ds.RequestCacheControl)
  474. if not value:
  475. return cls((), on_update)
  476. return cls(parse_dict_header(value), on_update)
  477. _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy")
  478. _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]]
  479. @typing.overload
  480. def parse_csp_header(
  481. value: t.Optional[str], on_update: _t_csp_update, cls: None = None
  482. ) -> "ds.ContentSecurityPolicy":
  483. ...
  484. @typing.overload
  485. def parse_csp_header(
  486. value: t.Optional[str], on_update: _t_csp_update, cls: t.Type[_TAnyCSP]
  487. ) -> _TAnyCSP:
  488. ...
  489. def parse_csp_header(
  490. value: t.Optional[str],
  491. on_update: _t_csp_update = None,
  492. cls: t.Optional[t.Type[_TAnyCSP]] = None,
  493. ) -> _TAnyCSP:
  494. """Parse a Content Security Policy header.
  495. .. versionadded:: 1.0.0
  496. Support for Content Security Policy headers was added.
  497. :param value: a csp header to be parsed.
  498. :param on_update: an optional callable that is called every time a value
  499. on the object is changed.
  500. :param cls: the class for the returned object. By default
  501. :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
  502. :return: a `cls` object.
  503. """
  504. if cls is None:
  505. cls = t.cast(t.Type[_TAnyCSP], ds.ContentSecurityPolicy)
  506. if value is None:
  507. return cls((), on_update)
  508. items = []
  509. for policy in value.split(";"):
  510. policy = policy.strip()
  511. # Ignore badly formatted policies (no space)
  512. if " " in policy:
  513. directive, value = policy.strip().split(" ", 1)
  514. items.append((directive.strip(), value.strip()))
  515. return cls(items, on_update)
  516. def parse_set_header(
  517. value: t.Optional[str],
  518. on_update: t.Optional[t.Callable[["ds.HeaderSet"], None]] = None,
  519. ) -> "ds.HeaderSet":
  520. """Parse a set-like header and return a
  521. :class:`~werkzeug.datastructures.HeaderSet` object:
  522. >>> hs = parse_set_header('token, "quoted value"')
  523. The return value is an object that treats the items case-insensitively
  524. and keeps the order of the items:
  525. >>> 'TOKEN' in hs
  526. True
  527. >>> hs.index('quoted value')
  528. 1
  529. >>> hs
  530. HeaderSet(['token', 'quoted value'])
  531. To create a header from the :class:`HeaderSet` again, use the
  532. :func:`dump_header` function.
  533. :param value: a set header to be parsed.
  534. :param on_update: an optional callable that is called every time a
  535. value on the :class:`~werkzeug.datastructures.HeaderSet`
  536. object is changed.
  537. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  538. """
  539. if not value:
  540. return ds.HeaderSet(None, on_update)
  541. return ds.HeaderSet(parse_list_header(value), on_update)
  542. def parse_authorization_header(
  543. value: t.Optional[str],
  544. ) -> t.Optional["ds.Authorization"]:
  545. """Parse an HTTP basic/digest authorization header transmitted by the web
  546. browser. The return value is either `None` if the header was invalid or
  547. not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
  548. object.
  549. :param value: the authorization header to parse.
  550. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
  551. """
  552. if not value:
  553. return None
  554. value = _wsgi_decoding_dance(value)
  555. try:
  556. auth_type, auth_info = value.split(None, 1)
  557. auth_type = auth_type.lower()
  558. except ValueError:
  559. return None
  560. if auth_type == "basic":
  561. try:
  562. username, password = base64.b64decode(auth_info).split(b":", 1)
  563. except Exception:
  564. return None
  565. try:
  566. return ds.Authorization(
  567. "basic",
  568. {
  569. "username": _to_str(username, "utf-8"),
  570. "password": _to_str(password, "utf-8"),
  571. },
  572. )
  573. except UnicodeDecodeError:
  574. return None
  575. elif auth_type == "digest":
  576. auth_map = parse_dict_header(auth_info)
  577. for key in "username", "realm", "nonce", "uri", "response":
  578. if key not in auth_map:
  579. return None
  580. if "qop" in auth_map:
  581. if not auth_map.get("nc") or not auth_map.get("cnonce"):
  582. return None
  583. return ds.Authorization("digest", auth_map)
  584. return None
  585. def parse_www_authenticate_header(
  586. value: t.Optional[str],
  587. on_update: t.Optional[t.Callable[["ds.WWWAuthenticate"], None]] = None,
  588. ) -> "ds.WWWAuthenticate":
  589. """Parse an HTTP WWW-Authenticate header into a
  590. :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  591. :param value: a WWW-Authenticate header to parse.
  592. :param on_update: an optional callable that is called every time a value
  593. on the :class:`~werkzeug.datastructures.WWWAuthenticate`
  594. object is changed.
  595. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  596. """
  597. if not value:
  598. return ds.WWWAuthenticate(on_update=on_update)
  599. try:
  600. auth_type, auth_info = value.split(None, 1)
  601. auth_type = auth_type.lower()
  602. except (ValueError, AttributeError):
  603. return ds.WWWAuthenticate(value.strip().lower(), on_update=on_update)
  604. return ds.WWWAuthenticate(auth_type, parse_dict_header(auth_info), on_update)
  605. def parse_if_range_header(value: t.Optional[str]) -> "ds.IfRange":
  606. """Parses an if-range header which can be an etag or a date. Returns
  607. a :class:`~werkzeug.datastructures.IfRange` object.
  608. .. versionchanged:: 2.0
  609. If the value represents a datetime, it is timezone-aware.
  610. .. versionadded:: 0.7
  611. """
  612. if not value:
  613. return ds.IfRange()
  614. date = parse_date(value)
  615. if date is not None:
  616. return ds.IfRange(date=date)
  617. # drop weakness information
  618. return ds.IfRange(unquote_etag(value)[0])
  619. def parse_range_header(
  620. value: t.Optional[str], make_inclusive: bool = True
  621. ) -> t.Optional["ds.Range"]:
  622. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  623. object. If the header is missing or malformed `None` is returned.
  624. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  625. non-inclusive.
  626. .. versionadded:: 0.7
  627. """
  628. if not value or "=" not in value:
  629. return None
  630. ranges = []
  631. last_end = 0
  632. units, rng = value.split("=", 1)
  633. units = units.strip().lower()
  634. for item in rng.split(","):
  635. item = item.strip()
  636. if "-" not in item:
  637. return None
  638. if item.startswith("-"):
  639. if last_end < 0:
  640. return None
  641. try:
  642. begin = int(item)
  643. except ValueError:
  644. return None
  645. end = None
  646. last_end = -1
  647. elif "-" in item:
  648. begin_str, end_str = item.split("-", 1)
  649. begin_str = begin_str.strip()
  650. end_str = end_str.strip()
  651. if not begin_str.isdigit():
  652. return None
  653. begin = int(begin_str)
  654. if begin < last_end or last_end < 0:
  655. return None
  656. if end_str:
  657. if not end_str.isdigit():
  658. return None
  659. end = int(end_str) + 1
  660. if begin >= end:
  661. return None
  662. else:
  663. end = None
  664. last_end = end if end is not None else -1
  665. ranges.append((begin, end))
  666. return ds.Range(units, ranges)
  667. def parse_content_range_header(
  668. value: t.Optional[str],
  669. on_update: t.Optional[t.Callable[["ds.ContentRange"], None]] = None,
  670. ) -> t.Optional["ds.ContentRange"]:
  671. """Parses a range header into a
  672. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  673. parsing is not possible.
  674. .. versionadded:: 0.7
  675. :param value: a content range header to be parsed.
  676. :param on_update: an optional callable that is called every time a value
  677. on the :class:`~werkzeug.datastructures.ContentRange`
  678. object is changed.
  679. """
  680. if value is None:
  681. return None
  682. try:
  683. units, rangedef = (value or "").strip().split(None, 1)
  684. except ValueError:
  685. return None
  686. if "/" not in rangedef:
  687. return None
  688. rng, length_str = rangedef.split("/", 1)
  689. if length_str == "*":
  690. length = None
  691. elif length_str.isdigit():
  692. length = int(length_str)
  693. else:
  694. return None
  695. if rng == "*":
  696. return ds.ContentRange(units, None, None, length, on_update=on_update)
  697. elif "-" not in rng:
  698. return None
  699. start_str, stop_str = rng.split("-", 1)
  700. try:
  701. start = int(start_str)
  702. stop = int(stop_str) + 1
  703. except ValueError:
  704. return None
  705. if is_byte_range_valid(start, stop, length):
  706. return ds.ContentRange(units, start, stop, length, on_update=on_update)
  707. return None
  708. def quote_etag(etag: str, weak: bool = False) -> str:
  709. """Quote an etag.
  710. :param etag: the etag to quote.
  711. :param weak: set to `True` to tag it "weak".
  712. """
  713. if '"' in etag:
  714. raise ValueError("invalid etag")
  715. etag = f'"{etag}"'
  716. if weak:
  717. etag = f"W/{etag}"
  718. return etag
  719. def unquote_etag(
  720. etag: t.Optional[str],
  721. ) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]:
  722. """Unquote a single etag:
  723. >>> unquote_etag('W/"bar"')
  724. ('bar', True)
  725. >>> unquote_etag('"bar"')
  726. ('bar', False)
  727. :param etag: the etag identifier to unquote.
  728. :return: a ``(etag, weak)`` tuple.
  729. """
  730. if not etag:
  731. return None, None
  732. etag = etag.strip()
  733. weak = False
  734. if etag.startswith(("W/", "w/")):
  735. weak = True
  736. etag = etag[2:]
  737. if etag[:1] == etag[-1:] == '"':
  738. etag = etag[1:-1]
  739. return etag, weak
  740. def parse_etags(value: t.Optional[str]) -> "ds.ETags":
  741. """Parse an etag header.
  742. :param value: the tag header to parse
  743. :return: an :class:`~werkzeug.datastructures.ETags` object.
  744. """
  745. if not value:
  746. return ds.ETags()
  747. strong = []
  748. weak = []
  749. end = len(value)
  750. pos = 0
  751. while pos < end:
  752. match = _etag_re.match(value, pos)
  753. if match is None:
  754. break
  755. is_weak, quoted, raw = match.groups()
  756. if raw == "*":
  757. return ds.ETags(star_tag=True)
  758. elif quoted:
  759. raw = quoted
  760. if is_weak:
  761. weak.append(raw)
  762. else:
  763. strong.append(raw)
  764. pos = match.end()
  765. return ds.ETags(strong, weak)
  766. def generate_etag(data: bytes) -> str:
  767. """Generate an etag for some data.
  768. .. versionchanged:: 2.0
  769. Use SHA-1. MD5 may not be available in some environments.
  770. """
  771. return sha1(data).hexdigest()
  772. def parse_date(value: t.Optional[str]) -> t.Optional[datetime]:
  773. """Parse an :rfc:`2822` date into a timezone-aware
  774. :class:`datetime.datetime` object, or ``None`` if parsing fails.
  775. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
  776. returns ``None`` if parsing fails instead of raising an exception,
  777. and always returns a timezone-aware datetime object. If the string
  778. doesn't have timezone information, it is assumed to be UTC.
  779. :param value: A string with a supported date format.
  780. .. versionchanged:: 2.0
  781. Return a timezone-aware datetime object. Use
  782. ``email.utils.parsedate_to_datetime``.
  783. """
  784. if value is None:
  785. return None
  786. try:
  787. dt = email.utils.parsedate_to_datetime(value)
  788. except (TypeError, ValueError):
  789. return None
  790. if dt.tzinfo is None:
  791. return dt.replace(tzinfo=timezone.utc)
  792. return dt
  793. def http_date(
  794. timestamp: t.Optional[t.Union[datetime, date, int, float, struct_time]] = None
  795. ) -> str:
  796. """Format a datetime object or timestamp into an :rfc:`2822` date
  797. string.
  798. This is a wrapper for :func:`email.utils.format_datetime`. It
  799. assumes naive datetime objects are in UTC instead of raising an
  800. exception.
  801. :param timestamp: The datetime or timestamp to format. Defaults to
  802. the current time.
  803. .. versionchanged:: 2.0
  804. Use ``email.utils.format_datetime``. Accept ``date`` objects.
  805. """
  806. if isinstance(timestamp, date):
  807. if not isinstance(timestamp, datetime):
  808. # Assume plain date is midnight UTC.
  809. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc)
  810. else:
  811. # Ensure datetime is timezone-aware.
  812. timestamp = _dt_as_utc(timestamp)
  813. return email.utils.format_datetime(timestamp, usegmt=True)
  814. if isinstance(timestamp, struct_time):
  815. timestamp = mktime(timestamp)
  816. return email.utils.formatdate(timestamp, usegmt=True)
  817. def parse_age(value: t.Optional[str] = None) -> t.Optional[timedelta]:
  818. """Parses a base-10 integer count of seconds into a timedelta.
  819. If parsing fails, the return value is `None`.
  820. :param value: a string consisting of an integer represented in base-10
  821. :return: a :class:`datetime.timedelta` object or `None`.
  822. """
  823. if not value:
  824. return None
  825. try:
  826. seconds = int(value)
  827. except ValueError:
  828. return None
  829. if seconds < 0:
  830. return None
  831. try:
  832. return timedelta(seconds=seconds)
  833. except OverflowError:
  834. return None
  835. def dump_age(age: t.Optional[t.Union[timedelta, int]] = None) -> t.Optional[str]:
  836. """Formats the duration as a base-10 integer.
  837. :param age: should be an integer number of seconds,
  838. a :class:`datetime.timedelta` object, or,
  839. if the age is unknown, `None` (default).
  840. """
  841. if age is None:
  842. return None
  843. if isinstance(age, timedelta):
  844. age = int(age.total_seconds())
  845. else:
  846. age = int(age)
  847. if age < 0:
  848. raise ValueError("age cannot be negative")
  849. return str(age)
  850. def is_resource_modified(
  851. environ: "WSGIEnvironment",
  852. etag: t.Optional[str] = None,
  853. data: t.Optional[bytes] = None,
  854. last_modified: t.Optional[t.Union[datetime, str]] = None,
  855. ignore_if_range: bool = True,
  856. ) -> bool:
  857. """Convenience method for conditional requests.
  858. :param environ: the WSGI environment of the request to be checked.
  859. :param etag: the etag for the response for comparison.
  860. :param data: or alternatively the data of the response to automatically
  861. generate an etag using :func:`generate_etag`.
  862. :param last_modified: an optional date of the last modification.
  863. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  864. account.
  865. :return: `True` if the resource was modified, otherwise `False`.
  866. .. versionchanged:: 2.0
  867. SHA-1 is used to generate an etag value for the data. MD5 may
  868. not be available in some environments.
  869. .. versionchanged:: 1.0.0
  870. The check is run for methods other than ``GET`` and ``HEAD``.
  871. """
  872. if etag is None and data is not None:
  873. etag = generate_etag(data)
  874. elif data is not None:
  875. raise TypeError("both data and etag given")
  876. unmodified = False
  877. if isinstance(last_modified, str):
  878. last_modified = parse_date(last_modified)
  879. # HTTP doesn't use microsecond, remove it to avoid false positive
  880. # comparisons. Mark naive datetimes as UTC.
  881. if last_modified is not None:
  882. last_modified = _dt_as_utc(last_modified.replace(microsecond=0))
  883. if_range = None
  884. if not ignore_if_range and "HTTP_RANGE" in environ:
  885. # https://tools.ietf.org/html/rfc7233#section-3.2
  886. # A server MUST ignore an If-Range header field received in a request
  887. # that does not contain a Range header field.
  888. if_range = parse_if_range_header(environ.get("HTTP_IF_RANGE"))
  889. if if_range is not None and if_range.date is not None:
  890. modified_since: t.Optional[datetime] = if_range.date
  891. else:
  892. modified_since = parse_date(environ.get("HTTP_IF_MODIFIED_SINCE"))
  893. if modified_since and last_modified and last_modified <= modified_since:
  894. unmodified = True
  895. if etag:
  896. etag, _ = unquote_etag(etag)
  897. etag = t.cast(str, etag)
  898. if if_range is not None and if_range.etag is not None:
  899. unmodified = parse_etags(if_range.etag).contains(etag)
  900. else:
  901. if_none_match = parse_etags(environ.get("HTTP_IF_NONE_MATCH"))
  902. if if_none_match:
  903. # https://tools.ietf.org/html/rfc7232#section-3.2
  904. # "A recipient MUST use the weak comparison function when comparing
  905. # entity-tags for If-None-Match"
  906. unmodified = if_none_match.contains_weak(etag)
  907. # https://tools.ietf.org/html/rfc7232#section-3.1
  908. # "Origin server MUST use the strong comparison function when
  909. # comparing entity-tags for If-Match"
  910. if_match = parse_etags(environ.get("HTTP_IF_MATCH"))
  911. if if_match:
  912. unmodified = not if_match.is_strong(etag)
  913. return not unmodified
  914. def remove_entity_headers(
  915. headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]],
  916. allowed: t.Iterable[str] = ("expires", "content-location"),
  917. ) -> None:
  918. """Remove all entity headers from a list or :class:`Headers` object. This
  919. operation works in-place. `Expires` and `Content-Location` headers are
  920. by default not removed. The reason for this is :rfc:`2616` section
  921. 10.3.5 which specifies some entity headers that should be sent.
  922. .. versionchanged:: 0.5
  923. added `allowed` parameter.
  924. :param headers: a list or :class:`Headers` object.
  925. :param allowed: a list of headers that should still be allowed even though
  926. they are entity headers.
  927. """
  928. allowed = {x.lower() for x in allowed}
  929. headers[:] = [
  930. (key, value)
  931. for key, value in headers
  932. if not is_entity_header(key) or key.lower() in allowed
  933. ]
  934. def remove_hop_by_hop_headers(
  935. headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]]
  936. ) -> None:
  937. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  938. :class:`Headers` object. This operation works in-place.
  939. .. versionadded:: 0.5
  940. :param headers: a list or :class:`Headers` object.
  941. """
  942. headers[:] = [
  943. (key, value) for key, value in headers if not is_hop_by_hop_header(key)
  944. ]
  945. def is_entity_header(header: str) -> bool:
  946. """Check if a header is an entity header.
  947. .. versionadded:: 0.5
  948. :param header: the header to test.
  949. :return: `True` if it's an entity header, `False` otherwise.
  950. """
  951. return header.lower() in _entity_headers
  952. def is_hop_by_hop_header(header: str) -> bool:
  953. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  954. .. versionadded:: 0.5
  955. :param header: the header to test.
  956. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
  957. """
  958. return header.lower() in _hop_by_hop_headers
  959. def parse_cookie(
  960. header: t.Union["WSGIEnvironment", str, bytes, None],
  961. charset: str = "utf-8",
  962. errors: str = "replace",
  963. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  964. ) -> "ds.MultiDict[str, str]":
  965. """Parse a cookie from a string or WSGI environ.
  966. The same key can be provided multiple times, the values are stored
  967. in-order. The default :class:`MultiDict` will have the first value
  968. first, and all values can be retrieved with
  969. :meth:`MultiDict.getlist`.
  970. :param header: The cookie header as a string, or a WSGI environ dict
  971. with a ``HTTP_COOKIE`` key.
  972. :param charset: The charset for the cookie values.
  973. :param errors: The error behavior for the charset decoding.
  974. :param cls: A dict-like class to store the parsed cookies in.
  975. Defaults to :class:`MultiDict`.
  976. .. versionchanged:: 1.0.0
  977. Returns a :class:`MultiDict` instead of a
  978. ``TypeConversionDict``.
  979. .. versionchanged:: 0.5
  980. Returns a :class:`TypeConversionDict` instead of a regular dict.
  981. The ``cls`` parameter was added.
  982. """
  983. if isinstance(header, dict):
  984. header = header.get("HTTP_COOKIE", "")
  985. elif header is None:
  986. header = ""
  987. # PEP 3333 sends headers through the environ as latin1 decoded
  988. # strings. Encode strings back to bytes for parsing.
  989. if isinstance(header, str):
  990. header = header.encode("latin1", "replace")
  991. if cls is None:
  992. cls = ds.MultiDict
  993. def _parse_pairs() -> t.Iterator[t.Tuple[str, str]]:
  994. for key, val in _cookie_parse_impl(header): # type: ignore
  995. key_str = _to_str(key, charset, errors, allow_none_charset=True)
  996. if not key_str:
  997. continue
  998. val_str = _to_str(val, charset, errors, allow_none_charset=True)
  999. yield key_str, val_str
  1000. return cls(_parse_pairs())
  1001. def dump_cookie(
  1002. key: str,
  1003. value: t.Union[bytes, str] = "",
  1004. max_age: t.Optional[t.Union[timedelta, int]] = None,
  1005. expires: t.Optional[t.Union[str, datetime, int, float]] = None,
  1006. path: t.Optional[str] = "/",
  1007. domain: t.Optional[str] = None,
  1008. secure: bool = False,
  1009. httponly: bool = False,
  1010. charset: str = "utf-8",
  1011. sync_expires: bool = True,
  1012. max_size: int = 4093,
  1013. samesite: t.Optional[str] = None,
  1014. ) -> str:
  1015. """Create a Set-Cookie header without the ``Set-Cookie`` prefix.
  1016. The return value is usually restricted to ascii as the vast majority
  1017. of values are properly escaped, but that is no guarantee. It's
  1018. tunneled through latin1 as required by :pep:`3333`.
  1019. The return value is not ASCII safe if the key contains unicode
  1020. characters. This is technically against the specification but
  1021. happens in the wild. It's strongly recommended to not use
  1022. non-ASCII values for the keys.
  1023. :param max_age: should be a number of seconds, or `None` (default) if
  1024. the cookie should last only as long as the client's
  1025. browser session. Additionally `timedelta` objects
  1026. are accepted, too.
  1027. :param expires: should be a `datetime` object or unix timestamp.
  1028. :param path: limits the cookie to a given path, per default it will
  1029. span the whole domain.
  1030. :param domain: Use this if you want to set a cross-domain cookie. For
  1031. example, ``domain=".example.com"`` will set a cookie
  1032. that is readable by the domain ``www.example.com``,
  1033. ``foo.example.com`` etc. Otherwise, a cookie will only
  1034. be readable by the domain that set it.
  1035. :param secure: The cookie will only be available via HTTPS
  1036. :param httponly: disallow JavaScript to access the cookie. This is an
  1037. extension to the cookie standard and probably not
  1038. supported by all browsers.
  1039. :param charset: the encoding for string values.
  1040. :param sync_expires: automatically set expires if max_age is defined
  1041. but expires not.
  1042. :param max_size: Warn if the final header value exceeds this size. The
  1043. default, 4093, should be safely `supported by most browsers
  1044. <cookie_>`_. Set to 0 to disable this check.
  1045. :param samesite: Limits the scope of the cookie such that it will
  1046. only be attached to requests if those requests are same-site.
  1047. .. _`cookie`: http://browsercookielimits.squawky.net/
  1048. .. versionchanged:: 1.0.0
  1049. The string ``'None'`` is accepted for ``samesite``.
  1050. """
  1051. key = _to_bytes(key, charset)
  1052. value = _to_bytes(value, charset)
  1053. if path is not None:
  1054. from .urls import iri_to_uri
  1055. path = iri_to_uri(path, charset)
  1056. domain = _make_cookie_domain(domain)
  1057. if isinstance(max_age, timedelta):
  1058. max_age = int(max_age.total_seconds())
  1059. if expires is not None:
  1060. if not isinstance(expires, str):
  1061. expires = http_date(expires)
  1062. elif max_age is not None and sync_expires:
  1063. expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)
  1064. if samesite is not None:
  1065. samesite = samesite.title()
  1066. if samesite not in {"Strict", "Lax", "None"}:
  1067. raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
  1068. buf = [key + b"=" + _cookie_quote(value)]
  1069. # XXX: In theory all of these parameters that are not marked with `None`
  1070. # should be quoted. Because stdlib did not quote it before I did not
  1071. # want to introduce quoting there now.
  1072. for k, v, q in (
  1073. (b"Domain", domain, True),
  1074. (b"Expires", expires, False),
  1075. (b"Max-Age", max_age, False),
  1076. (b"Secure", secure, None),
  1077. (b"HttpOnly", httponly, None),
  1078. (b"Path", path, False),
  1079. (b"SameSite", samesite, False),
  1080. ):
  1081. if q is None:
  1082. if v:
  1083. buf.append(k)
  1084. continue
  1085. if v is None:
  1086. continue
  1087. tmp = bytearray(k)
  1088. if not isinstance(v, (bytes, bytearray)):
  1089. v = _to_bytes(str(v), charset)
  1090. if q:
  1091. v = _cookie_quote(v)
  1092. tmp += b"=" + v
  1093. buf.append(bytes(tmp))
  1094. # The return value will be an incorrectly encoded latin1 header for
  1095. # consistency with the headers object.
  1096. rv = b"; ".join(buf)
  1097. rv = rv.decode("latin1")
  1098. # Warn if the final value of the cookie is larger than the limit. If the
  1099. # cookie is too large, then it may be silently ignored by the browser,
  1100. # which can be quite hard to debug.
  1101. cookie_size = len(rv)
  1102. if max_size and cookie_size > max_size:
  1103. value_size = len(value)
  1104. warnings.warn(
  1105. f"The {key.decode(charset)!r} cookie is too large: the value was"
  1106. f" {value_size} bytes but the"
  1107. f" header required {cookie_size - value_size} extra bytes. The final size"
  1108. f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may"
  1109. f" silently ignore cookies larger than this.",
  1110. stacklevel=2,
  1111. )
  1112. return rv
  1113. def is_byte_range_valid(
  1114. start: t.Optional[int], stop: t.Optional[int], length: t.Optional[int]
  1115. ) -> bool:
  1116. """Checks if a given byte content range is valid for the given length.
  1117. .. versionadded:: 0.7
  1118. """
  1119. if (start is None) != (stop is None):
  1120. return False
  1121. elif start is None:
  1122. return length is None or length >= 0
  1123. elif length is None:
  1124. return 0 <= start < stop # type: ignore
  1125. elif start >= stop: # type: ignore
  1126. return False
  1127. return 0 <= start < length
  1128. # circular dependencies
  1129. from . import datastructures as ds