http.py 35 KB

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