http.py 42 KB

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