http.py 44 KB

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