You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.py 41KB

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