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.

1158 lines
39 KiB

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