http.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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. @typing.overload
  332. def parse_options_header(
  333. value: t.Optional[str], multiple: "te.Literal[False]" = False
  334. ) -> t.Tuple[str, t.Dict[str, str]]:
  335. ...
  336. @typing.overload
  337. def parse_options_header(
  338. value: t.Optional[str], multiple: "te.Literal[True]"
  339. ) -> t.Tuple[t.Any, ...]:
  340. ...
  341. def parse_options_header(
  342. value: t.Optional[str], multiple: bool = False
  343. ) -> t.Union[t.Tuple[str, t.Dict[str, str]], t.Tuple[t.Any, ...]]:
  344. """Parse a ``Content-Type`` like header into a tuple with the content
  345. type and the options:
  346. >>> parse_options_header('text/html; charset=utf8')
  347. ('text/html', {'charset': 'utf8'})
  348. This should not be used to parse ``Cache-Control`` like headers that use
  349. a slightly different format. For these headers use the
  350. :func:`parse_dict_header` function.
  351. .. versionchanged:: 0.15
  352. :rfc:`2231` parameter continuations are handled.
  353. .. versionadded:: 0.5
  354. :param value: the header to parse.
  355. :param multiple: Whether try to parse and return multiple MIME types
  356. :return: (mimetype, options) or (mimetype, options, mimetype, options, …)
  357. if multiple=True
  358. """
  359. if not value:
  360. return "", {}
  361. result: t.List[t.Any] = []
  362. value = "," + value.replace("\n", ",")
  363. while value:
  364. match = _option_header_start_mime_type.match(value)
  365. if not match:
  366. break
  367. result.append(match.group(1)) # mimetype
  368. options: t.Dict[str, str] = {}
  369. # Parse options
  370. rest = match.group(2)
  371. encoding: t.Optional[str]
  372. continued_encoding: t.Optional[str] = None
  373. while rest:
  374. optmatch = _option_header_piece_re.match(rest)
  375. if not optmatch:
  376. break
  377. option, count, encoding, language, option_value = optmatch.groups()
  378. # Continuations don't have to supply the encoding after the
  379. # first line. If we're in a continuation, track the current
  380. # encoding to use for subsequent lines. Reset it when the
  381. # continuation ends.
  382. if not count:
  383. continued_encoding = None
  384. else:
  385. if not encoding:
  386. encoding = continued_encoding
  387. continued_encoding = encoding
  388. option = unquote_header_value(option)
  389. if option_value is not None:
  390. option_value = unquote_header_value(option_value, option == "filename")
  391. if encoding is not None:
  392. option_value = _unquote(option_value).decode(encoding)
  393. if count:
  394. # Continuations append to the existing value. For
  395. # simplicity, this ignores the possibility of
  396. # out-of-order indices, which shouldn't happen anyway.
  397. if option_value is not None:
  398. options[option] = options.get(option, "") + option_value
  399. else:
  400. options[option] = option_value # type: ignore[assignment]
  401. rest = rest[optmatch.end() :]
  402. result.append(options)
  403. if multiple is False:
  404. return tuple(result)
  405. value = rest
  406. return tuple(result) if result else ("", {})
  407. _TAnyAccept = t.TypeVar("_TAnyAccept", bound="ds.Accept")
  408. @typing.overload
  409. def parse_accept_header(value: t.Optional[str]) -> "ds.Accept":
  410. ...
  411. @typing.overload
  412. def parse_accept_header(
  413. value: t.Optional[str], cls: t.Type[_TAnyAccept]
  414. ) -> _TAnyAccept:
  415. ...
  416. def parse_accept_header(
  417. value: t.Optional[str], cls: t.Optional[t.Type[_TAnyAccept]] = None
  418. ) -> _TAnyAccept:
  419. """Parses an HTTP Accept-* header. This does not implement a complete
  420. valid algorithm but one that supports at least value and quality
  421. extraction.
  422. Returns a new :class:`Accept` object (basically a list of ``(value, quality)``
  423. tuples sorted by the quality with some additional accessor methods).
  424. The second parameter can be a subclass of :class:`Accept` that is created
  425. with the parsed values and returned.
  426. :param value: the accept header string to be parsed.
  427. :param cls: the wrapper class for the return value (can be
  428. :class:`Accept` or a subclass thereof)
  429. :return: an instance of `cls`.
  430. """
  431. if cls is None:
  432. cls = t.cast(t.Type[_TAnyAccept], ds.Accept)
  433. if not value:
  434. return cls(None)
  435. result = []
  436. for match in _accept_re.finditer(value):
  437. quality_match = match.group(2)
  438. if not quality_match:
  439. quality: float = 1
  440. else:
  441. quality = max(min(float(quality_match), 1), 0)
  442. result.append((match.group(1), quality))
  443. return cls(result)
  444. _TAnyCC = t.TypeVar("_TAnyCC", bound="ds._CacheControl")
  445. _t_cc_update = t.Optional[t.Callable[[_TAnyCC], None]]
  446. @typing.overload
  447. def parse_cache_control_header(
  448. value: t.Optional[str], on_update: _t_cc_update, cls: None = None
  449. ) -> "ds.RequestCacheControl":
  450. ...
  451. @typing.overload
  452. def parse_cache_control_header(
  453. value: t.Optional[str], on_update: _t_cc_update, cls: t.Type[_TAnyCC]
  454. ) -> _TAnyCC:
  455. ...
  456. def parse_cache_control_header(
  457. value: t.Optional[str],
  458. on_update: _t_cc_update = None,
  459. cls: t.Optional[t.Type[_TAnyCC]] = None,
  460. ) -> _TAnyCC:
  461. """Parse a cache control header. The RFC differs between response and
  462. request cache control, this method does not. It's your responsibility
  463. to not use the wrong control statements.
  464. .. versionadded:: 0.5
  465. The `cls` was added. If not specified an immutable
  466. :class:`~werkzeug.datastructures.RequestCacheControl` is returned.
  467. :param value: a cache control header to be parsed.
  468. :param on_update: an optional callable that is called every time a value
  469. on the :class:`~werkzeug.datastructures.CacheControl`
  470. object is changed.
  471. :param cls: the class for the returned object. By default
  472. :class:`~werkzeug.datastructures.RequestCacheControl` is used.
  473. :return: a `cls` object.
  474. """
  475. if cls is None:
  476. cls = t.cast(t.Type[_TAnyCC], ds.RequestCacheControl)
  477. if not value:
  478. return cls((), on_update)
  479. return cls(parse_dict_header(value), on_update)
  480. _TAnyCSP = t.TypeVar("_TAnyCSP", bound="ds.ContentSecurityPolicy")
  481. _t_csp_update = t.Optional[t.Callable[[_TAnyCSP], None]]
  482. @typing.overload
  483. def parse_csp_header(
  484. value: t.Optional[str], on_update: _t_csp_update, cls: None = None
  485. ) -> "ds.ContentSecurityPolicy":
  486. ...
  487. @typing.overload
  488. def parse_csp_header(
  489. value: t.Optional[str], on_update: _t_csp_update, cls: t.Type[_TAnyCSP]
  490. ) -> _TAnyCSP:
  491. ...
  492. def parse_csp_header(
  493. value: t.Optional[str],
  494. on_update: _t_csp_update = None,
  495. cls: t.Optional[t.Type[_TAnyCSP]] = None,
  496. ) -> _TAnyCSP:
  497. """Parse a Content Security Policy header.
  498. .. versionadded:: 1.0.0
  499. Support for Content Security Policy headers was added.
  500. :param value: a csp header to be parsed.
  501. :param on_update: an optional callable that is called every time a value
  502. on the object is changed.
  503. :param cls: the class for the returned object. By default
  504. :class:`~werkzeug.datastructures.ContentSecurityPolicy` is used.
  505. :return: a `cls` object.
  506. """
  507. if cls is None:
  508. cls = t.cast(t.Type[_TAnyCSP], ds.ContentSecurityPolicy)
  509. if value is None:
  510. return cls((), on_update)
  511. items = []
  512. for policy in value.split(";"):
  513. policy = policy.strip()
  514. # Ignore badly formatted policies (no space)
  515. if " " in policy:
  516. directive, value = policy.strip().split(" ", 1)
  517. items.append((directive.strip(), value.strip()))
  518. return cls(items, on_update)
  519. def parse_set_header(
  520. value: t.Optional[str],
  521. on_update: t.Optional[t.Callable[["ds.HeaderSet"], None]] = None,
  522. ) -> "ds.HeaderSet":
  523. """Parse a set-like header and return a
  524. :class:`~werkzeug.datastructures.HeaderSet` object:
  525. >>> hs = parse_set_header('token, "quoted value"')
  526. The return value is an object that treats the items case-insensitively
  527. and keeps the order of the items:
  528. >>> 'TOKEN' in hs
  529. True
  530. >>> hs.index('quoted value')
  531. 1
  532. >>> hs
  533. HeaderSet(['token', 'quoted value'])
  534. To create a header from the :class:`HeaderSet` again, use the
  535. :func:`dump_header` function.
  536. :param value: a set header to be parsed.
  537. :param on_update: an optional callable that is called every time a
  538. value on the :class:`~werkzeug.datastructures.HeaderSet`
  539. object is changed.
  540. :return: a :class:`~werkzeug.datastructures.HeaderSet`
  541. """
  542. if not value:
  543. return ds.HeaderSet(None, on_update)
  544. return ds.HeaderSet(parse_list_header(value), on_update)
  545. def parse_authorization_header(
  546. value: t.Optional[str],
  547. ) -> t.Optional["ds.Authorization"]:
  548. """Parse an HTTP basic/digest authorization header transmitted by the web
  549. browser. The return value is either `None` if the header was invalid or
  550. not given, otherwise an :class:`~werkzeug.datastructures.Authorization`
  551. object.
  552. :param value: the authorization header to parse.
  553. :return: a :class:`~werkzeug.datastructures.Authorization` object or `None`.
  554. """
  555. if not value:
  556. return None
  557. value = _wsgi_decoding_dance(value)
  558. try:
  559. auth_type, auth_info = value.split(None, 1)
  560. auth_type = auth_type.lower()
  561. except ValueError:
  562. return None
  563. if auth_type == "basic":
  564. try:
  565. username, password = base64.b64decode(auth_info).split(b":", 1)
  566. except Exception:
  567. return None
  568. try:
  569. return ds.Authorization(
  570. "basic",
  571. {
  572. "username": _to_str(username, "utf-8"),
  573. "password": _to_str(password, "utf-8"),
  574. },
  575. )
  576. except UnicodeDecodeError:
  577. return None
  578. elif auth_type == "digest":
  579. auth_map = parse_dict_header(auth_info)
  580. for key in "username", "realm", "nonce", "uri", "response":
  581. if key not in auth_map:
  582. return None
  583. if "qop" in auth_map:
  584. if not auth_map.get("nc") or not auth_map.get("cnonce"):
  585. return None
  586. return ds.Authorization("digest", auth_map)
  587. return None
  588. def parse_www_authenticate_header(
  589. value: t.Optional[str],
  590. on_update: t.Optional[t.Callable[["ds.WWWAuthenticate"], None]] = None,
  591. ) -> "ds.WWWAuthenticate":
  592. """Parse an HTTP WWW-Authenticate header into a
  593. :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  594. :param value: a WWW-Authenticate header to parse.
  595. :param on_update: an optional callable that is called every time a value
  596. on the :class:`~werkzeug.datastructures.WWWAuthenticate`
  597. object is changed.
  598. :return: a :class:`~werkzeug.datastructures.WWWAuthenticate` object.
  599. """
  600. if not value:
  601. return ds.WWWAuthenticate(on_update=on_update)
  602. try:
  603. auth_type, auth_info = value.split(None, 1)
  604. auth_type = auth_type.lower()
  605. except (ValueError, AttributeError):
  606. return ds.WWWAuthenticate(value.strip().lower(), on_update=on_update)
  607. return ds.WWWAuthenticate(auth_type, parse_dict_header(auth_info), on_update)
  608. def parse_if_range_header(value: t.Optional[str]) -> "ds.IfRange":
  609. """Parses an if-range header which can be an etag or a date. Returns
  610. a :class:`~werkzeug.datastructures.IfRange` object.
  611. .. versionchanged:: 2.0
  612. If the value represents a datetime, it is timezone-aware.
  613. .. versionadded:: 0.7
  614. """
  615. if not value:
  616. return ds.IfRange()
  617. date = parse_date(value)
  618. if date is not None:
  619. return ds.IfRange(date=date)
  620. # drop weakness information
  621. return ds.IfRange(unquote_etag(value)[0])
  622. def parse_range_header(
  623. value: t.Optional[str], make_inclusive: bool = True
  624. ) -> t.Optional["ds.Range"]:
  625. """Parses a range header into a :class:`~werkzeug.datastructures.Range`
  626. object. If the header is missing or malformed `None` is returned.
  627. `ranges` is a list of ``(start, stop)`` tuples where the ranges are
  628. non-inclusive.
  629. .. versionadded:: 0.7
  630. """
  631. if not value or "=" not in value:
  632. return None
  633. ranges = []
  634. last_end = 0
  635. units, rng = value.split("=", 1)
  636. units = units.strip().lower()
  637. for item in rng.split(","):
  638. item = item.strip()
  639. if "-" not in item:
  640. return None
  641. if item.startswith("-"):
  642. if last_end < 0:
  643. return None
  644. try:
  645. begin = int(item)
  646. except ValueError:
  647. return None
  648. end = None
  649. last_end = -1
  650. elif "-" in item:
  651. begin_str, end_str = item.split("-", 1)
  652. begin_str = begin_str.strip()
  653. end_str = end_str.strip()
  654. if not begin_str.isdigit():
  655. return None
  656. begin = int(begin_str)
  657. if begin < last_end or last_end < 0:
  658. return None
  659. if end_str:
  660. if not end_str.isdigit():
  661. return None
  662. end = int(end_str) + 1
  663. if begin >= end:
  664. return None
  665. else:
  666. end = None
  667. last_end = end if end is not None else -1
  668. ranges.append((begin, end))
  669. return ds.Range(units, ranges)
  670. def parse_content_range_header(
  671. value: t.Optional[str],
  672. on_update: t.Optional[t.Callable[["ds.ContentRange"], None]] = None,
  673. ) -> t.Optional["ds.ContentRange"]:
  674. """Parses a range header into a
  675. :class:`~werkzeug.datastructures.ContentRange` object or `None` if
  676. parsing is not possible.
  677. .. versionadded:: 0.7
  678. :param value: a content range header to be parsed.
  679. :param on_update: an optional callable that is called every time a value
  680. on the :class:`~werkzeug.datastructures.ContentRange`
  681. object is changed.
  682. """
  683. if value is None:
  684. return None
  685. try:
  686. units, rangedef = (value or "").strip().split(None, 1)
  687. except ValueError:
  688. return None
  689. if "/" not in rangedef:
  690. return None
  691. rng, length_str = rangedef.split("/", 1)
  692. if length_str == "*":
  693. length = None
  694. elif length_str.isdigit():
  695. length = int(length_str)
  696. else:
  697. return None
  698. if rng == "*":
  699. return ds.ContentRange(units, None, None, length, on_update=on_update)
  700. elif "-" not in rng:
  701. return None
  702. start_str, stop_str = rng.split("-", 1)
  703. try:
  704. start = int(start_str)
  705. stop = int(stop_str) + 1
  706. except ValueError:
  707. return None
  708. if is_byte_range_valid(start, stop, length):
  709. return ds.ContentRange(units, start, stop, length, on_update=on_update)
  710. return None
  711. def quote_etag(etag: str, weak: bool = False) -> str:
  712. """Quote an etag.
  713. :param etag: the etag to quote.
  714. :param weak: set to `True` to tag it "weak".
  715. """
  716. if '"' in etag:
  717. raise ValueError("invalid etag")
  718. etag = f'"{etag}"'
  719. if weak:
  720. etag = f"W/{etag}"
  721. return etag
  722. def unquote_etag(
  723. etag: t.Optional[str],
  724. ) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]:
  725. """Unquote a single etag:
  726. >>> unquote_etag('W/"bar"')
  727. ('bar', True)
  728. >>> unquote_etag('"bar"')
  729. ('bar', False)
  730. :param etag: the etag identifier to unquote.
  731. :return: a ``(etag, weak)`` tuple.
  732. """
  733. if not etag:
  734. return None, None
  735. etag = etag.strip()
  736. weak = False
  737. if etag.startswith(("W/", "w/")):
  738. weak = True
  739. etag = etag[2:]
  740. if etag[:1] == etag[-1:] == '"':
  741. etag = etag[1:-1]
  742. return etag, weak
  743. def parse_etags(value: t.Optional[str]) -> "ds.ETags":
  744. """Parse an etag header.
  745. :param value: the tag header to parse
  746. :return: an :class:`~werkzeug.datastructures.ETags` object.
  747. """
  748. if not value:
  749. return ds.ETags()
  750. strong = []
  751. weak = []
  752. end = len(value)
  753. pos = 0
  754. while pos < end:
  755. match = _etag_re.match(value, pos)
  756. if match is None:
  757. break
  758. is_weak, quoted, raw = match.groups()
  759. if raw == "*":
  760. return ds.ETags(star_tag=True)
  761. elif quoted:
  762. raw = quoted
  763. if is_weak:
  764. weak.append(raw)
  765. else:
  766. strong.append(raw)
  767. pos = match.end()
  768. return ds.ETags(strong, weak)
  769. def generate_etag(data: bytes) -> str:
  770. """Generate an etag for some data.
  771. .. versionchanged:: 2.0
  772. Use SHA-1. MD5 may not be available in some environments.
  773. """
  774. return sha1(data).hexdigest()
  775. def parse_date(value: t.Optional[str]) -> t.Optional[datetime]:
  776. """Parse an :rfc:`2822` date into a timezone-aware
  777. :class:`datetime.datetime` object, or ``None`` if parsing fails.
  778. This is a wrapper for :func:`email.utils.parsedate_to_datetime`. It
  779. returns ``None`` if parsing fails instead of raising an exception,
  780. and always returns a timezone-aware datetime object. If the string
  781. doesn't have timezone information, it is assumed to be UTC.
  782. :param value: A string with a supported date format.
  783. .. versionchanged:: 2.0
  784. Return a timezone-aware datetime object. Use
  785. ``email.utils.parsedate_to_datetime``.
  786. """
  787. if value is None:
  788. return None
  789. try:
  790. dt = email.utils.parsedate_to_datetime(value)
  791. except (TypeError, ValueError):
  792. return None
  793. if dt.tzinfo is None:
  794. return dt.replace(tzinfo=timezone.utc)
  795. return dt
  796. def cookie_date(
  797. expires: t.Optional[t.Union[datetime, date, int, float, struct_time]] = None
  798. ) -> str:
  799. """Format a datetime object or timestamp into an :rfc:`2822` date
  800. string for ``Set-Cookie expires``.
  801. .. deprecated:: 2.0
  802. Will be removed in Werkzeug 2.1. Use :func:`http_date` instead.
  803. """
  804. warnings.warn(
  805. "'cookie_date' is deprecated and will be removed in Werkzeug"
  806. " 2.1. Use 'http_date' instead.",
  807. DeprecationWarning,
  808. stacklevel=2,
  809. )
  810. return http_date(expires)
  811. def http_date(
  812. timestamp: t.Optional[t.Union[datetime, date, int, float, struct_time]] = None
  813. ) -> str:
  814. """Format a datetime object or timestamp into an :rfc:`2822` date
  815. string.
  816. This is a wrapper for :func:`email.utils.format_datetime`. It
  817. assumes naive datetime objects are in UTC instead of raising an
  818. exception.
  819. :param timestamp: The datetime or timestamp to format. Defaults to
  820. the current time.
  821. .. versionchanged:: 2.0
  822. Use ``email.utils.format_datetime``. Accept ``date`` objects.
  823. """
  824. if isinstance(timestamp, date):
  825. if not isinstance(timestamp, datetime):
  826. # Assume plain date is midnight UTC.
  827. timestamp = datetime.combine(timestamp, time(), tzinfo=timezone.utc)
  828. else:
  829. # Ensure datetime is timezone-aware.
  830. timestamp = _dt_as_utc(timestamp)
  831. return email.utils.format_datetime(timestamp, usegmt=True)
  832. if isinstance(timestamp, struct_time):
  833. timestamp = mktime(timestamp)
  834. return email.utils.formatdate(timestamp, usegmt=True)
  835. def parse_age(value: t.Optional[str] = None) -> t.Optional[timedelta]:
  836. """Parses a base-10 integer count of seconds into a timedelta.
  837. If parsing fails, the return value is `None`.
  838. :param value: a string consisting of an integer represented in base-10
  839. :return: a :class:`datetime.timedelta` object or `None`.
  840. """
  841. if not value:
  842. return None
  843. try:
  844. seconds = int(value)
  845. except ValueError:
  846. return None
  847. if seconds < 0:
  848. return None
  849. try:
  850. return timedelta(seconds=seconds)
  851. except OverflowError:
  852. return None
  853. def dump_age(age: t.Optional[t.Union[timedelta, int]] = None) -> t.Optional[str]:
  854. """Formats the duration as a base-10 integer.
  855. :param age: should be an integer number of seconds,
  856. a :class:`datetime.timedelta` object, or,
  857. if the age is unknown, `None` (default).
  858. """
  859. if age is None:
  860. return None
  861. if isinstance(age, timedelta):
  862. age = int(age.total_seconds())
  863. else:
  864. age = int(age)
  865. if age < 0:
  866. raise ValueError("age cannot be negative")
  867. return str(age)
  868. def is_resource_modified(
  869. environ: "WSGIEnvironment",
  870. etag: t.Optional[str] = None,
  871. data: t.Optional[bytes] = None,
  872. last_modified: t.Optional[t.Union[datetime, str]] = None,
  873. ignore_if_range: bool = True,
  874. ) -> bool:
  875. """Convenience method for conditional requests.
  876. :param environ: the WSGI environment of the request to be checked.
  877. :param etag: the etag for the response for comparison.
  878. :param data: or alternatively the data of the response to automatically
  879. generate an etag using :func:`generate_etag`.
  880. :param last_modified: an optional date of the last modification.
  881. :param ignore_if_range: If `False`, `If-Range` header will be taken into
  882. account.
  883. :return: `True` if the resource was modified, otherwise `False`.
  884. .. versionchanged:: 2.0
  885. SHA-1 is used to generate an etag value for the data. MD5 may
  886. not be available in some environments.
  887. .. versionchanged:: 1.0.0
  888. The check is run for methods other than ``GET`` and ``HEAD``.
  889. """
  890. if etag is None and data is not None:
  891. etag = generate_etag(data)
  892. elif data is not None:
  893. raise TypeError("both data and etag given")
  894. unmodified = False
  895. if isinstance(last_modified, str):
  896. last_modified = parse_date(last_modified)
  897. # HTTP doesn't use microsecond, remove it to avoid false positive
  898. # comparisons. Mark naive datetimes as UTC.
  899. if last_modified is not None:
  900. last_modified = _dt_as_utc(last_modified.replace(microsecond=0))
  901. if_range = None
  902. if not ignore_if_range and "HTTP_RANGE" in environ:
  903. # https://tools.ietf.org/html/rfc7233#section-3.2
  904. # A server MUST ignore an If-Range header field received in a request
  905. # that does not contain a Range header field.
  906. if_range = parse_if_range_header(environ.get("HTTP_IF_RANGE"))
  907. if if_range is not None and if_range.date is not None:
  908. modified_since: t.Optional[datetime] = if_range.date
  909. else:
  910. modified_since = parse_date(environ.get("HTTP_IF_MODIFIED_SINCE"))
  911. if modified_since and last_modified and last_modified <= modified_since:
  912. unmodified = True
  913. if etag:
  914. etag, _ = unquote_etag(etag)
  915. etag = t.cast(str, etag)
  916. if if_range is not None and if_range.etag is not None:
  917. unmodified = parse_etags(if_range.etag).contains(etag)
  918. else:
  919. if_none_match = parse_etags(environ.get("HTTP_IF_NONE_MATCH"))
  920. if if_none_match:
  921. # https://tools.ietf.org/html/rfc7232#section-3.2
  922. # "A recipient MUST use the weak comparison function when comparing
  923. # entity-tags for If-None-Match"
  924. unmodified = if_none_match.contains_weak(etag)
  925. # https://tools.ietf.org/html/rfc7232#section-3.1
  926. # "Origin server MUST use the strong comparison function when
  927. # comparing entity-tags for If-Match"
  928. if_match = parse_etags(environ.get("HTTP_IF_MATCH"))
  929. if if_match:
  930. unmodified = not if_match.is_strong(etag)
  931. return not unmodified
  932. def remove_entity_headers(
  933. headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]],
  934. allowed: t.Iterable[str] = ("expires", "content-location"),
  935. ) -> None:
  936. """Remove all entity headers from a list or :class:`Headers` object. This
  937. operation works in-place. `Expires` and `Content-Location` headers are
  938. by default not removed. The reason for this is :rfc:`2616` section
  939. 10.3.5 which specifies some entity headers that should be sent.
  940. .. versionchanged:: 0.5
  941. added `allowed` parameter.
  942. :param headers: a list or :class:`Headers` object.
  943. :param allowed: a list of headers that should still be allowed even though
  944. they are entity headers.
  945. """
  946. allowed = {x.lower() for x in allowed}
  947. headers[:] = [
  948. (key, value)
  949. for key, value in headers
  950. if not is_entity_header(key) or key.lower() in allowed
  951. ]
  952. def remove_hop_by_hop_headers(
  953. headers: t.Union["ds.Headers", t.List[t.Tuple[str, str]]]
  954. ) -> None:
  955. """Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
  956. :class:`Headers` object. This operation works in-place.
  957. .. versionadded:: 0.5
  958. :param headers: a list or :class:`Headers` object.
  959. """
  960. headers[:] = [
  961. (key, value) for key, value in headers if not is_hop_by_hop_header(key)
  962. ]
  963. def is_entity_header(header: str) -> bool:
  964. """Check if a header is an entity header.
  965. .. versionadded:: 0.5
  966. :param header: the header to test.
  967. :return: `True` if it's an entity header, `False` otherwise.
  968. """
  969. return header.lower() in _entity_headers
  970. def is_hop_by_hop_header(header: str) -> bool:
  971. """Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
  972. .. versionadded:: 0.5
  973. :param header: the header to test.
  974. :return: `True` if it's an HTTP/1.1 "Hop-by-Hop" header, `False` otherwise.
  975. """
  976. return header.lower() in _hop_by_hop_headers
  977. def parse_cookie(
  978. header: t.Union["WSGIEnvironment", str, bytes, None],
  979. charset: str = "utf-8",
  980. errors: str = "replace",
  981. cls: t.Optional[t.Type["ds.MultiDict"]] = None,
  982. ) -> "ds.MultiDict[str, str]":
  983. """Parse a cookie from a string or WSGI environ.
  984. The same key can be provided multiple times, the values are stored
  985. in-order. The default :class:`MultiDict` will have the first value
  986. first, and all values can be retrieved with
  987. :meth:`MultiDict.getlist`.
  988. :param header: The cookie header as a string, or a WSGI environ dict
  989. with a ``HTTP_COOKIE`` key.
  990. :param charset: The charset for the cookie values.
  991. :param errors: The error behavior for the charset decoding.
  992. :param cls: A dict-like class to store the parsed cookies in.
  993. Defaults to :class:`MultiDict`.
  994. .. versionchanged:: 1.0.0
  995. Returns a :class:`MultiDict` instead of a
  996. ``TypeConversionDict``.
  997. .. versionchanged:: 0.5
  998. Returns a :class:`TypeConversionDict` instead of a regular dict.
  999. The ``cls`` parameter was added.
  1000. """
  1001. if isinstance(header, dict):
  1002. header = header.get("HTTP_COOKIE", "")
  1003. elif header is None:
  1004. header = ""
  1005. # PEP 3333 sends headers through the environ as latin1 decoded
  1006. # strings. Encode strings back to bytes for parsing.
  1007. if isinstance(header, str):
  1008. header = header.encode("latin1", "replace")
  1009. if cls is None:
  1010. cls = ds.MultiDict
  1011. def _parse_pairs() -> t.Iterator[t.Tuple[str, str]]:
  1012. for key, val in _cookie_parse_impl(header): # type: ignore
  1013. key_str = _to_str(key, charset, errors, allow_none_charset=True)
  1014. if not key_str:
  1015. continue
  1016. val_str = _to_str(val, charset, errors, allow_none_charset=True)
  1017. yield key_str, val_str
  1018. return cls(_parse_pairs())
  1019. def dump_cookie(
  1020. key: str,
  1021. value: t.Union[bytes, str] = "",
  1022. max_age: t.Optional[t.Union[timedelta, int]] = None,
  1023. expires: t.Optional[t.Union[str, datetime, int, float]] = None,
  1024. path: t.Optional[str] = "/",
  1025. domain: t.Optional[str] = None,
  1026. secure: bool = False,
  1027. httponly: bool = False,
  1028. charset: str = "utf-8",
  1029. sync_expires: bool = True,
  1030. max_size: int = 4093,
  1031. samesite: t.Optional[str] = None,
  1032. ) -> str:
  1033. """Create a Set-Cookie header without the ``Set-Cookie`` prefix.
  1034. The return value is usually restricted to ascii as the vast majority
  1035. of values are properly escaped, but that is no guarantee. It's
  1036. tunneled through latin1 as required by :pep:`3333`.
  1037. The return value is not ASCII safe if the key contains unicode
  1038. characters. This is technically against the specification but
  1039. happens in the wild. It's strongly recommended to not use
  1040. non-ASCII values for the keys.
  1041. :param max_age: should be a number of seconds, or `None` (default) if
  1042. the cookie should last only as long as the client's
  1043. browser session. Additionally `timedelta` objects
  1044. are accepted, too.
  1045. :param expires: should be a `datetime` object or unix timestamp.
  1046. :param path: limits the cookie to a given path, per default it will
  1047. span the whole domain.
  1048. :param domain: Use this if you want to set a cross-domain cookie. For
  1049. example, ``domain=".example.com"`` will set a cookie
  1050. that is readable by the domain ``www.example.com``,
  1051. ``foo.example.com`` etc. Otherwise, a cookie will only
  1052. be readable by the domain that set it.
  1053. :param secure: The cookie will only be available via HTTPS
  1054. :param httponly: disallow JavaScript to access the cookie. This is an
  1055. extension to the cookie standard and probably not
  1056. supported by all browsers.
  1057. :param charset: the encoding for string values.
  1058. :param sync_expires: automatically set expires if max_age is defined
  1059. but expires not.
  1060. :param max_size: Warn if the final header value exceeds this size. The
  1061. default, 4093, should be safely `supported by most browsers
  1062. <cookie_>`_. Set to 0 to disable this check.
  1063. :param samesite: Limits the scope of the cookie such that it will
  1064. only be attached to requests if those requests are same-site.
  1065. .. _`cookie`: http://browsercookielimits.squawky.net/
  1066. .. versionchanged:: 1.0.0
  1067. The string ``'None'`` is accepted for ``samesite``.
  1068. """
  1069. key = _to_bytes(key, charset)
  1070. value = _to_bytes(value, charset)
  1071. if path is not None:
  1072. from .urls import iri_to_uri
  1073. path = iri_to_uri(path, charset)
  1074. domain = _make_cookie_domain(domain)
  1075. if isinstance(max_age, timedelta):
  1076. max_age = int(max_age.total_seconds())
  1077. if expires is not None:
  1078. if not isinstance(expires, str):
  1079. expires = http_date(expires)
  1080. elif max_age is not None and sync_expires:
  1081. expires = http_date(datetime.now(tz=timezone.utc).timestamp() + max_age)
  1082. if samesite is not None:
  1083. samesite = samesite.title()
  1084. if samesite not in {"Strict", "Lax", "None"}:
  1085. raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.")
  1086. buf = [key + b"=" + _cookie_quote(value)]
  1087. # XXX: In theory all of these parameters that are not marked with `None`
  1088. # should be quoted. Because stdlib did not quote it before I did not
  1089. # want to introduce quoting there now.
  1090. for k, v, q in (
  1091. (b"Domain", domain, True),
  1092. (b"Expires", expires, False),
  1093. (b"Max-Age", max_age, False),
  1094. (b"Secure", secure, None),
  1095. (b"HttpOnly", httponly, None),
  1096. (b"Path", path, False),
  1097. (b"SameSite", samesite, False),
  1098. ):
  1099. if q is None:
  1100. if v:
  1101. buf.append(k)
  1102. continue
  1103. if v is None:
  1104. continue
  1105. tmp = bytearray(k)
  1106. if not isinstance(v, (bytes, bytearray)):
  1107. v = _to_bytes(str(v), charset)
  1108. if q:
  1109. v = _cookie_quote(v)
  1110. tmp += b"=" + v
  1111. buf.append(bytes(tmp))
  1112. # The return value will be an incorrectly encoded latin1 header for
  1113. # consistency with the headers object.
  1114. rv = b"; ".join(buf)
  1115. rv = rv.decode("latin1")
  1116. # Warn if the final value of the cookie is larger than the limit. If the
  1117. # cookie is too large, then it may be silently ignored by the browser,
  1118. # which can be quite hard to debug.
  1119. cookie_size = len(rv)
  1120. if max_size and cookie_size > max_size:
  1121. value_size = len(value)
  1122. warnings.warn(
  1123. f"The {key.decode(charset)!r} cookie is too large: the value was"
  1124. f" {value_size} bytes but the"
  1125. f" header required {cookie_size - value_size} extra bytes. The final size"
  1126. f" was {cookie_size} bytes but the limit is {max_size} bytes. Browsers may"
  1127. f" silently ignore cookies larger than this.",
  1128. stacklevel=2,
  1129. )
  1130. return rv
  1131. def is_byte_range_valid(
  1132. start: t.Optional[int], stop: t.Optional[int], length: t.Optional[int]
  1133. ) -> bool:
  1134. """Checks if a given byte content range is valid for the given length.
  1135. .. versionadded:: 0.7
  1136. """
  1137. if (start is None) != (stop is None):
  1138. return False
  1139. elif start is None:
  1140. return length is None or length >= 0
  1141. elif length is None:
  1142. return 0 <= start < stop # type: ignore
  1143. elif start >= stop: # type: ignore
  1144. return False
  1145. return 0 <= start < length
  1146. # circular dependencies
  1147. from . import datastructures as ds