http.py 33 KB

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