http.py 41 KB

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