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.

1364 lines
48 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.wsgi
  4. ~~~~~~~~~~~~~
  5. This module implements WSGI related helpers.
  6. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import io
  10. try:
  11. import httplib
  12. except ImportError:
  13. from http import client as httplib
  14. import mimetypes
  15. import os
  16. import posixpath
  17. import re
  18. import socket
  19. from datetime import datetime
  20. from functools import partial, update_wrapper
  21. from itertools import chain
  22. from time import mktime, time
  23. from zlib import adler32
  24. from werkzeug._compat import BytesIO, PY2, implements_iterator, iteritems, \
  25. make_literal_wrapper, string_types, text_type, to_bytes, to_unicode, \
  26. try_coerce_native, wsgi_get_bytes
  27. from werkzeug._internal import _empty_stream, _encode_idna
  28. from werkzeug.filesystem import get_filesystem_encoding
  29. from werkzeug.http import http_date, is_resource_modified, \
  30. is_hop_by_hop_header
  31. from werkzeug.urls import uri_to_iri, url_join, url_parse, url_quote
  32. from werkzeug.datastructures import EnvironHeaders
  33. def responder(f):
  34. """Marks a function as responder. Decorate a function with it and it
  35. will automatically call the return value as WSGI application.
  36. Example::
  37. @responder
  38. def application(environ, start_response):
  39. return Response('Hello World!')
  40. """
  41. return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
  42. def get_current_url(environ, root_only=False, strip_querystring=False,
  43. host_only=False, trusted_hosts=None):
  44. """A handy helper function that recreates the full URL as IRI for the
  45. current request or parts of it. Here's an example:
  46. >>> from werkzeug.test import create_environ
  47. >>> env = create_environ("/?param=foo", "http://localhost/script")
  48. >>> get_current_url(env)
  49. 'http://localhost/script/?param=foo'
  50. >>> get_current_url(env, root_only=True)
  51. 'http://localhost/script/'
  52. >>> get_current_url(env, host_only=True)
  53. 'http://localhost/'
  54. >>> get_current_url(env, strip_querystring=True)
  55. 'http://localhost/script/'
  56. This optionally it verifies that the host is in a list of trusted hosts.
  57. If the host is not in there it will raise a
  58. :exc:`~werkzeug.exceptions.SecurityError`.
  59. Note that the string returned might contain unicode characters as the
  60. representation is an IRI not an URI. If you need an ASCII only
  61. representation you can use the :func:`~werkzeug.urls.iri_to_uri`
  62. function:
  63. >>> from werkzeug.urls import iri_to_uri
  64. >>> iri_to_uri(get_current_url(env))
  65. 'http://localhost/script/?param=foo'
  66. :param environ: the WSGI environment to get the current URL from.
  67. :param root_only: set `True` if you only want the root URL.
  68. :param strip_querystring: set to `True` if you don't want the querystring.
  69. :param host_only: set to `True` if the host URL should be returned.
  70. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
  71. for more information.
  72. """
  73. tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)]
  74. cat = tmp.append
  75. if host_only:
  76. return uri_to_iri(''.join(tmp) + '/')
  77. cat(url_quote(wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))).rstrip('/'))
  78. cat('/')
  79. if not root_only:
  80. cat(url_quote(wsgi_get_bytes(environ.get('PATH_INFO', '')).lstrip(b'/')))
  81. if not strip_querystring:
  82. qs = get_query_string(environ)
  83. if qs:
  84. cat('?' + qs)
  85. return uri_to_iri(''.join(tmp))
  86. def host_is_trusted(hostname, trusted_list):
  87. """Checks if a host is trusted against a list. This also takes care
  88. of port normalization.
  89. .. versionadded:: 0.9
  90. :param hostname: the hostname to check
  91. :param trusted_list: a list of hostnames to check against. If a
  92. hostname starts with a dot it will match against
  93. all subdomains as well.
  94. """
  95. if not hostname:
  96. return False
  97. if isinstance(trusted_list, string_types):
  98. trusted_list = [trusted_list]
  99. def _normalize(hostname):
  100. if ':' in hostname:
  101. hostname = hostname.rsplit(':', 1)[0]
  102. return _encode_idna(hostname)
  103. try:
  104. hostname = _normalize(hostname)
  105. except UnicodeError:
  106. return False
  107. for ref in trusted_list:
  108. if ref.startswith('.'):
  109. ref = ref[1:]
  110. suffix_match = True
  111. else:
  112. suffix_match = False
  113. try:
  114. ref = _normalize(ref)
  115. except UnicodeError:
  116. return False
  117. if ref == hostname:
  118. return True
  119. if suffix_match and hostname.endswith(b'.' + ref):
  120. return True
  121. return False
  122. def get_host(environ, trusted_hosts=None):
  123. """Return the real host for the given WSGI environment. This first checks
  124. the `X-Forwarded-Host` header, then the normal `Host` header, and finally
  125. the `SERVER_NAME` environment variable (using the first one it finds).
  126. Optionally it verifies that the host is in a list of trusted hosts.
  127. If the host is not in there it will raise a
  128. :exc:`~werkzeug.exceptions.SecurityError`.
  129. :param environ: the WSGI environment to get the host of.
  130. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
  131. for more information.
  132. """
  133. if 'HTTP_X_FORWARDED_HOST' in environ:
  134. rv = environ['HTTP_X_FORWARDED_HOST'].split(',', 1)[0].strip()
  135. elif 'HTTP_HOST' in environ:
  136. rv = environ['HTTP_HOST']
  137. else:
  138. rv = environ['SERVER_NAME']
  139. if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \
  140. in (('https', '443'), ('http', '80')):
  141. rv += ':' + environ['SERVER_PORT']
  142. if trusted_hosts is not None:
  143. if not host_is_trusted(rv, trusted_hosts):
  144. from werkzeug.exceptions import SecurityError
  145. raise SecurityError('Host "%s" is not trusted' % rv)
  146. return rv
  147. def get_content_length(environ):
  148. """Returns the content length from the WSGI environment as
  149. integer. If it's not available or chunked transfer encoding is used,
  150. ``None`` is returned.
  151. .. versionadded:: 0.9
  152. :param environ: the WSGI environ to fetch the content length from.
  153. """
  154. if environ.get('HTTP_TRANSFER_ENCODING', '') == 'chunked':
  155. return None
  156. content_length = environ.get('CONTENT_LENGTH')
  157. if content_length is not None:
  158. try:
  159. return max(0, int(content_length))
  160. except (ValueError, TypeError):
  161. pass
  162. def get_input_stream(environ, safe_fallback=True):
  163. """Returns the input stream from the WSGI environment and wraps it
  164. in the most sensible way possible. The stream returned is not the
  165. raw WSGI stream in most cases but one that is safe to read from
  166. without taking into account the content length.
  167. If content length is not set, the stream will be empty for safety reasons.
  168. If the WSGI server supports chunked or infinite streams, it should set
  169. the ``wsgi.input_terminated`` value in the WSGI environ to indicate that.
  170. .. versionadded:: 0.9
  171. :param environ: the WSGI environ to fetch the stream from.
  172. :param safe_fallback: use an empty stream as a safe fallback when the
  173. content length is not set. Disabling this allows infinite streams,
  174. which can be a denial-of-service risk.
  175. """
  176. stream = environ['wsgi.input']
  177. content_length = get_content_length(environ)
  178. # A wsgi extension that tells us if the input is terminated. In
  179. # that case we return the stream unchanged as we know we can safely
  180. # read it until the end.
  181. if environ.get('wsgi.input_terminated'):
  182. return stream
  183. # If the request doesn't specify a content length, returning the stream is
  184. # potentially dangerous because it could be infinite, malicious or not. If
  185. # safe_fallback is true, return an empty stream instead for safety.
  186. if content_length is None:
  187. return safe_fallback and _empty_stream or stream
  188. # Otherwise limit the stream to the content length
  189. return LimitedStream(stream, content_length)
  190. def get_query_string(environ):
  191. """Returns the `QUERY_STRING` from the WSGI environment. This also takes
  192. care about the WSGI decoding dance on Python 3 environments as a
  193. native string. The string returned will be restricted to ASCII
  194. characters.
  195. .. versionadded:: 0.9
  196. :param environ: the WSGI environment object to get the query string from.
  197. """
  198. qs = wsgi_get_bytes(environ.get('QUERY_STRING', ''))
  199. # QUERY_STRING really should be ascii safe but some browsers
  200. # will send us some unicode stuff (I am looking at you IE).
  201. # In that case we want to urllib quote it badly.
  202. return try_coerce_native(url_quote(qs, safe=':&%=+$!*\'(),'))
  203. def get_path_info(environ, charset='utf-8', errors='replace'):
  204. """Returns the `PATH_INFO` from the WSGI environment and properly
  205. decodes it. This also takes care about the WSGI decoding dance
  206. on Python 3 environments. if the `charset` is set to `None` a
  207. bytestring is returned.
  208. .. versionadded:: 0.9
  209. :param environ: the WSGI environment object to get the path from.
  210. :param charset: the charset for the path info, or `None` if no
  211. decoding should be performed.
  212. :param errors: the decoding error handling.
  213. """
  214. path = wsgi_get_bytes(environ.get('PATH_INFO', ''))
  215. return to_unicode(path, charset, errors, allow_none_charset=True)
  216. def get_script_name(environ, charset='utf-8', errors='replace'):
  217. """Returns the `SCRIPT_NAME` from the WSGI environment and properly
  218. decodes it. This also takes care about the WSGI decoding dance
  219. on Python 3 environments. if the `charset` is set to `None` a
  220. bytestring is returned.
  221. .. versionadded:: 0.9
  222. :param environ: the WSGI environment object to get the path from.
  223. :param charset: the charset for the path, or `None` if no
  224. decoding should be performed.
  225. :param errors: the decoding error handling.
  226. """
  227. path = wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))
  228. return to_unicode(path, charset, errors, allow_none_charset=True)
  229. def pop_path_info(environ, charset='utf-8', errors='replace'):
  230. """Removes and returns the next segment of `PATH_INFO`, pushing it onto
  231. `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
  232. If the `charset` is set to `None` a bytestring is returned.
  233. If there are empty segments (``'/foo//bar``) these are ignored but
  234. properly pushed to the `SCRIPT_NAME`:
  235. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  236. >>> pop_path_info(env)
  237. 'a'
  238. >>> env['SCRIPT_NAME']
  239. '/foo/a'
  240. >>> pop_path_info(env)
  241. 'b'
  242. >>> env['SCRIPT_NAME']
  243. '/foo/a/b'
  244. .. versionadded:: 0.5
  245. .. versionchanged:: 0.9
  246. The path is now decoded and a charset and encoding
  247. parameter can be provided.
  248. :param environ: the WSGI environment that is modified.
  249. """
  250. path = environ.get('PATH_INFO')
  251. if not path:
  252. return None
  253. script_name = environ.get('SCRIPT_NAME', '')
  254. # shift multiple leading slashes over
  255. old_path = path
  256. path = path.lstrip('/')
  257. if path != old_path:
  258. script_name += '/' * (len(old_path) - len(path))
  259. if '/' not in path:
  260. environ['PATH_INFO'] = ''
  261. environ['SCRIPT_NAME'] = script_name + path
  262. rv = wsgi_get_bytes(path)
  263. else:
  264. segment, path = path.split('/', 1)
  265. environ['PATH_INFO'] = '/' + path
  266. environ['SCRIPT_NAME'] = script_name + segment
  267. rv = wsgi_get_bytes(segment)
  268. return to_unicode(rv, charset, errors, allow_none_charset=True)
  269. def peek_path_info(environ, charset='utf-8', errors='replace'):
  270. """Returns the next segment on the `PATH_INFO` or `None` if there
  271. is none. Works like :func:`pop_path_info` without modifying the
  272. environment:
  273. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  274. >>> peek_path_info(env)
  275. 'a'
  276. >>> peek_path_info(env)
  277. 'a'
  278. If the `charset` is set to `None` a bytestring is returned.
  279. .. versionadded:: 0.5
  280. .. versionchanged:: 0.9
  281. The path is now decoded and a charset and encoding
  282. parameter can be provided.
  283. :param environ: the WSGI environment that is checked.
  284. """
  285. segments = environ.get('PATH_INFO', '').lstrip('/').split('/', 1)
  286. if segments:
  287. return to_unicode(wsgi_get_bytes(segments[0]),
  288. charset, errors, allow_none_charset=True)
  289. def extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8',
  290. errors='replace', collapse_http_schemes=True):
  291. """Extracts the path info from the given URL (or WSGI environment) and
  292. path. The path info returned is a unicode string, not a bytestring
  293. suitable for a WSGI environment. The URLs might also be IRIs.
  294. If the path info could not be determined, `None` is returned.
  295. Some examples:
  296. >>> extract_path_info('http://example.com/app', '/app/hello')
  297. u'/hello'
  298. >>> extract_path_info('http://example.com/app',
  299. ... 'https://example.com/app/hello')
  300. u'/hello'
  301. >>> extract_path_info('http://example.com/app',
  302. ... 'https://example.com/app/hello',
  303. ... collapse_http_schemes=False) is None
  304. True
  305. Instead of providing a base URL you can also pass a WSGI environment.
  306. .. versionadded:: 0.6
  307. :param environ_or_baseurl: a WSGI environment dict, a base URL or
  308. base IRI. This is the root of the
  309. application.
  310. :param path_or_url: an absolute path from the server root, a
  311. relative path (in which case it's the path info)
  312. or a full URL. Also accepts IRIs and unicode
  313. parameters.
  314. :param charset: the charset for byte data in URLs
  315. :param errors: the error handling on decode
  316. :param collapse_http_schemes: if set to `False` the algorithm does
  317. not assume that http and https on the
  318. same server point to the same
  319. resource.
  320. """
  321. def _normalize_netloc(scheme, netloc):
  322. parts = netloc.split(u'@', 1)[-1].split(u':', 1)
  323. if len(parts) == 2:
  324. netloc, port = parts
  325. if (scheme == u'http' and port == u'80') or \
  326. (scheme == u'https' and port == u'443'):
  327. port = None
  328. else:
  329. netloc = parts[0]
  330. port = None
  331. if port is not None:
  332. netloc += u':' + port
  333. return netloc
  334. # make sure whatever we are working on is a IRI and parse it
  335. path = uri_to_iri(path_or_url, charset, errors)
  336. if isinstance(environ_or_baseurl, dict):
  337. environ_or_baseurl = get_current_url(environ_or_baseurl,
  338. root_only=True)
  339. base_iri = uri_to_iri(environ_or_baseurl, charset, errors)
  340. base_scheme, base_netloc, base_path = url_parse(base_iri)[:3]
  341. cur_scheme, cur_netloc, cur_path, = \
  342. url_parse(url_join(base_iri, path))[:3]
  343. # normalize the network location
  344. base_netloc = _normalize_netloc(base_scheme, base_netloc)
  345. cur_netloc = _normalize_netloc(cur_scheme, cur_netloc)
  346. # is that IRI even on a known HTTP scheme?
  347. if collapse_http_schemes:
  348. for scheme in base_scheme, cur_scheme:
  349. if scheme not in (u'http', u'https'):
  350. return None
  351. else:
  352. if not (base_scheme in (u'http', u'https') and
  353. base_scheme == cur_scheme):
  354. return None
  355. # are the netlocs compatible?
  356. if base_netloc != cur_netloc:
  357. return None
  358. # are we below the application path?
  359. base_path = base_path.rstrip(u'/')
  360. if not cur_path.startswith(base_path):
  361. return None
  362. return u'/' + cur_path[len(base_path):].lstrip(u'/')
  363. class ProxyMiddleware(object):
  364. """This middleware routes some requests to the provided WSGI app and
  365. proxies some requests to an external server. This is not something that
  366. can generally be done on the WSGI layer and some HTTP requests will not
  367. tunnel through correctly (for instance websocket requests cannot be
  368. proxied through WSGI). As a result this is only really useful for some
  369. basic requests that can be forwarded.
  370. Example configuration::
  371. app = ProxyMiddleware(app, {
  372. '/static/': {
  373. 'target': 'http://127.0.0.1:5001/',
  374. }
  375. })
  376. For each host options can be specified. The following options are
  377. supported:
  378. ``target``:
  379. the target URL to dispatch to
  380. ``remove_prefix``:
  381. if set to `True` the prefix is chopped off the URL before
  382. dispatching it to the server.
  383. ``host``:
  384. When set to ``'<auto>'`` which is the default the host header is
  385. automatically rewritten to the URL of the target. If set to `None`
  386. then the host header is unmodified from the client request. Any
  387. other value overwrites the host header with that value.
  388. ``headers``:
  389. An optional dictionary of headers that should be sent with the
  390. request to the target host.
  391. ``ssl_context``:
  392. In case this is an HTTPS target host then an SSL context can be
  393. provided here (:class:`ssl.SSLContext`). This can be used for instance
  394. to disable SSL verification.
  395. In this case everything below ``'/static/'`` is proxied to the server on
  396. port 5001. The host header is automatically rewritten and so are request
  397. URLs (eg: the leading `/static/` prefix here gets chopped off).
  398. .. versionadded:: 0.14
  399. """
  400. def __init__(self, app, targets, chunk_size=2 << 13, timeout=10):
  401. def _set_defaults(opts):
  402. opts.setdefault('remove_prefix', False)
  403. opts.setdefault('host', '<auto>')
  404. opts.setdefault('headers', {})
  405. opts.setdefault('ssl_context', None)
  406. return opts
  407. self.app = app
  408. self.targets = dict(('/%s/' % k.strip('/'), _set_defaults(v))
  409. for k, v in iteritems(targets))
  410. self.chunk_size = chunk_size
  411. self.timeout = timeout
  412. def proxy_to(self, opts, path, prefix):
  413. target = url_parse(opts['target'])
  414. def application(environ, start_response):
  415. headers = list(EnvironHeaders(environ).items())
  416. headers[:] = [(k, v) for k, v in headers
  417. if not is_hop_by_hop_header(k) and
  418. k.lower() not in ('content-length', 'host')]
  419. headers.append(('Connection', 'close'))
  420. if opts['host'] == '<auto>':
  421. headers.append(('Host', target.ascii_host))
  422. elif opts['host'] is None:
  423. headers.append(('Host', environ['HTTP_HOST']))
  424. else:
  425. headers.append(('Host', opts['host']))
  426. headers.extend(opts['headers'].items())
  427. remote_path = path
  428. if opts['remove_prefix']:
  429. remote_path = '%s/%s' % (
  430. target.path.rstrip('/'),
  431. remote_path[len(prefix):].lstrip('/')
  432. )
  433. content_length = environ.get('CONTENT_LENGTH')
  434. chunked = False
  435. if content_length not in ('', None):
  436. headers.append(('Content-Length', content_length))
  437. elif content_length is not None:
  438. headers.append(('Transfer-Encoding', 'chunked'))
  439. chunked = True
  440. try:
  441. if target.scheme == 'http':
  442. con = httplib.HTTPConnection(
  443. target.ascii_host, target.port or 80,
  444. timeout=self.timeout)
  445. elif target.scheme == 'https':
  446. con = httplib.HTTPSConnection(
  447. target.ascii_host, target.port or 443,
  448. timeout=self.timeout,
  449. context=opts['ssl_context'])
  450. con.connect()
  451. con.putrequest(environ['REQUEST_METHOD'], url_quote(remote_path),
  452. skip_host=True)
  453. for k, v in headers:
  454. if k.lower() == 'connection':
  455. v = 'close'
  456. con.putheader(k, v)
  457. con.endheaders()
  458. stream = get_input_stream(environ)
  459. while 1:
  460. data = stream.read(self.chunk_size)
  461. if not data:
  462. break
  463. if chunked:
  464. con.send(b'%x\r\n%s\r\n' % (len(data), data))
  465. else:
  466. con.send(data)
  467. resp = con.getresponse()
  468. except socket.error:
  469. from werkzeug.exceptions import BadGateway
  470. return BadGateway()(environ, start_response)
  471. start_response('%d %s' % (resp.status, resp.reason),
  472. [(k.title(), v) for k, v in resp.getheaders()
  473. if not is_hop_by_hop_header(k)])
  474. def read():
  475. while 1:
  476. try:
  477. data = resp.read(self.chunk_size)
  478. except socket.error:
  479. break
  480. if not data:
  481. break
  482. yield data
  483. return read()
  484. return application
  485. def __call__(self, environ, start_response):
  486. path = environ['PATH_INFO']
  487. app = self.app
  488. for prefix, opts in iteritems(self.targets):
  489. if path.startswith(prefix):
  490. app = self.proxy_to(opts, path, prefix)
  491. break
  492. return app(environ, start_response)
  493. class SharedDataMiddleware(object):
  494. """A WSGI middleware that provides static content for development
  495. environments or simple server setups. Usage is quite simple::
  496. import os
  497. from werkzeug.wsgi import SharedDataMiddleware
  498. app = SharedDataMiddleware(app, {
  499. '/shared': os.path.join(os.path.dirname(__file__), 'shared')
  500. })
  501. The contents of the folder ``./shared`` will now be available on
  502. ``http://example.com/shared/``. This is pretty useful during development
  503. because a standalone media server is not required. One can also mount
  504. files on the root folder and still continue to use the application because
  505. the shared data middleware forwards all unhandled requests to the
  506. application, even if the requests are below one of the shared folders.
  507. If `pkg_resources` is available you can also tell the middleware to serve
  508. files from package data::
  509. app = SharedDataMiddleware(app, {
  510. '/shared': ('myapplication', 'shared_files')
  511. })
  512. This will then serve the ``shared_files`` folder in the `myapplication`
  513. Python package.
  514. The optional `disallow` parameter can be a list of :func:`~fnmatch.fnmatch`
  515. rules for files that are not accessible from the web. If `cache` is set to
  516. `False` no caching headers are sent.
  517. Currently the middleware does not support non ASCII filenames. If the
  518. encoding on the file system happens to be the encoding of the URI it may
  519. work but this could also be by accident. We strongly suggest using ASCII
  520. only file names for static files.
  521. The middleware will guess the mimetype using the Python `mimetype`
  522. module. If it's unable to figure out the charset it will fall back
  523. to `fallback_mimetype`.
  524. .. versionchanged:: 0.5
  525. The cache timeout is configurable now.
  526. .. versionadded:: 0.6
  527. The `fallback_mimetype` parameter was added.
  528. :param app: the application to wrap. If you don't want to wrap an
  529. application you can pass it :exc:`NotFound`.
  530. :param exports: a list or dict of exported files and folders.
  531. :param disallow: a list of :func:`~fnmatch.fnmatch` rules.
  532. :param fallback_mimetype: the fallback mimetype for unknown files.
  533. :param cache: enable or disable caching headers.
  534. :param cache_timeout: the cache timeout in seconds for the headers.
  535. """
  536. def __init__(self, app, exports, disallow=None, cache=True,
  537. cache_timeout=60 * 60 * 12, fallback_mimetype='text/plain'):
  538. self.app = app
  539. self.exports = []
  540. self.cache = cache
  541. self.cache_timeout = cache_timeout
  542. if hasattr(exports, 'items'):
  543. exports = iteritems(exports)
  544. for key, value in exports:
  545. if isinstance(value, tuple):
  546. loader = self.get_package_loader(*value)
  547. elif isinstance(value, string_types):
  548. if os.path.isfile(value):
  549. loader = self.get_file_loader(value)
  550. else:
  551. loader = self.get_directory_loader(value)
  552. else:
  553. raise TypeError('unknown def %r' % value)
  554. self.exports.append((key, loader))
  555. if disallow is not None:
  556. from fnmatch import fnmatch
  557. self.is_allowed = lambda x: not fnmatch(x, disallow)
  558. self.fallback_mimetype = fallback_mimetype
  559. def is_allowed(self, filename):
  560. """Subclasses can override this method to disallow the access to
  561. certain files. However by providing `disallow` in the constructor
  562. this method is overwritten.
  563. """
  564. return True
  565. def _opener(self, filename):
  566. return lambda: (
  567. open(filename, 'rb'),
  568. datetime.utcfromtimestamp(os.path.getmtime(filename)),
  569. int(os.path.getsize(filename))
  570. )
  571. def get_file_loader(self, filename):
  572. return lambda x: (os.path.basename(filename), self._opener(filename))
  573. def get_package_loader(self, package, package_path):
  574. from pkg_resources import DefaultProvider, ResourceManager, \
  575. get_provider
  576. loadtime = datetime.utcnow()
  577. provider = get_provider(package)
  578. manager = ResourceManager()
  579. filesystem_bound = isinstance(provider, DefaultProvider)
  580. def loader(path):
  581. if path is None:
  582. return None, None
  583. path = posixpath.join(package_path, path)
  584. if not provider.has_resource(path):
  585. return None, None
  586. basename = posixpath.basename(path)
  587. if filesystem_bound:
  588. return basename, self._opener(
  589. provider.get_resource_filename(manager, path))
  590. s = provider.get_resource_string(manager, path)
  591. return basename, lambda: (
  592. BytesIO(s),
  593. loadtime,
  594. len(s)
  595. )
  596. return loader
  597. def get_directory_loader(self, directory):
  598. def loader(path):
  599. if path is not None:
  600. path = os.path.join(directory, path)
  601. else:
  602. path = directory
  603. if os.path.isfile(path):
  604. return os.path.basename(path), self._opener(path)
  605. return None, None
  606. return loader
  607. def generate_etag(self, mtime, file_size, real_filename):
  608. if not isinstance(real_filename, bytes):
  609. real_filename = real_filename.encode(get_filesystem_encoding())
  610. return 'wzsdm-%d-%s-%s' % (
  611. mktime(mtime.timetuple()),
  612. file_size,
  613. adler32(real_filename) & 0xffffffff
  614. )
  615. def __call__(self, environ, start_response):
  616. cleaned_path = get_path_info(environ)
  617. if PY2:
  618. cleaned_path = cleaned_path.encode(get_filesystem_encoding())
  619. # sanitize the path for non unix systems
  620. cleaned_path = cleaned_path.strip('/')
  621. for sep in os.sep, os.altsep:
  622. if sep and sep != '/':
  623. cleaned_path = cleaned_path.replace(sep, '/')
  624. path = '/' + '/'.join(x for x in cleaned_path.split('/')
  625. if x and x != '..')
  626. file_loader = None
  627. for search_path, loader in self.exports:
  628. if search_path == path:
  629. real_filename, file_loader = loader(None)
  630. if file_loader is not None:
  631. break
  632. if not search_path.endswith('/'):
  633. search_path += '/'
  634. if path.startswith(search_path):
  635. real_filename, file_loader = loader(path[len(search_path):])
  636. if file_loader is not None:
  637. break
  638. if file_loader is None or not self.is_allowed(real_filename):
  639. return self.app(environ, start_response)
  640. guessed_type = mimetypes.guess_type(real_filename)
  641. mime_type = guessed_type[0] or self.fallback_mimetype
  642. f, mtime, file_size = file_loader()
  643. headers = [('Date', http_date())]
  644. if self.cache:
  645. timeout = self.cache_timeout
  646. etag = self.generate_etag(mtime, file_size, real_filename)
  647. headers += [
  648. ('Etag', '"%s"' % etag),
  649. ('Cache-Control', 'max-age=%d, public' % timeout)
  650. ]
  651. if not is_resource_modified(environ, etag, last_modified=mtime):
  652. f.close()
  653. start_response('304 Not Modified', headers)
  654. return []
  655. headers.append(('Expires', http_date(time() + timeout)))
  656. else:
  657. headers.append(('Cache-Control', 'public'))
  658. headers.extend((
  659. ('Content-Type', mime_type),
  660. ('Content-Length', str(file_size)),
  661. ('Last-Modified', http_date(mtime))
  662. ))
  663. start_response('200 OK', headers)
  664. return wrap_file(environ, f)
  665. class DispatcherMiddleware(object):
  666. """Allows one to mount middlewares or applications in a WSGI application.
  667. This is useful if you want to combine multiple WSGI applications::
  668. app = DispatcherMiddleware(app, {
  669. '/app2': app2,
  670. '/app3': app3
  671. })
  672. """
  673. def __init__(self, app, mounts=None):
  674. self.app = app
  675. self.mounts = mounts or {}
  676. def __call__(self, environ, start_response):
  677. script = environ.get('PATH_INFO', '')
  678. path_info = ''
  679. while '/' in script:
  680. if script in self.mounts:
  681. app = self.mounts[script]
  682. break
  683. script, last_item = script.rsplit('/', 1)
  684. path_info = '/%s%s' % (last_item, path_info)
  685. else:
  686. app = self.mounts.get(script, self.app)
  687. original_script_name = environ.get('SCRIPT_NAME', '')
  688. environ['SCRIPT_NAME'] = original_script_name + script
  689. environ['PATH_INFO'] = path_info
  690. return app(environ, start_response)
  691. @implements_iterator
  692. class ClosingIterator(object):
  693. """The WSGI specification requires that all middlewares and gateways
  694. respect the `close` callback of an iterator. Because it is useful to add
  695. another close action to a returned iterator and adding a custom iterator
  696. is a boring task this class can be used for that::
  697. return ClosingIterator(app(environ, start_response), [cleanup_session,
  698. cleanup_locals])
  699. If there is just one close function it can be passed instead of the list.
  700. A closing iterator is not needed if the application uses response objects
  701. and finishes the processing if the response is started::
  702. try:
  703. return response(environ, start_response)
  704. finally:
  705. cleanup_session()
  706. cleanup_locals()
  707. """
  708. def __init__(self, iterable, callbacks=None):
  709. iterator = iter(iterable)
  710. self._next = partial(next, iterator)
  711. if callbacks is None:
  712. callbacks = []
  713. elif callable(callbacks):
  714. callbacks = [callbacks]
  715. else:
  716. callbacks = list(callbacks)
  717. iterable_close = getattr(iterator, 'close', None)
  718. if iterable_close:
  719. callbacks.insert(0, iterable_close)
  720. self._callbacks = callbacks
  721. def __iter__(self):
  722. return self
  723. def __next__(self):
  724. return self._next()
  725. def close(self):
  726. for callback in self._callbacks:
  727. callback()
  728. def wrap_file(environ, file, buffer_size=8192):
  729. """Wraps a file. This uses the WSGI server's file wrapper if available
  730. or otherwise the generic :class:`FileWrapper`.
  731. .. versionadded:: 0.5
  732. If the file wrapper from the WSGI server is used it's important to not
  733. iterate over it from inside the application but to pass it through
  734. unchanged. If you want to pass out a file wrapper inside a response
  735. object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.
  736. More information about file wrappers are available in :pep:`333`.
  737. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  738. :param buffer_size: number of bytes for one iteration.
  739. """
  740. return environ.get('wsgi.file_wrapper', FileWrapper)(file, buffer_size)
  741. @implements_iterator
  742. class FileWrapper(object):
  743. """This class can be used to convert a :class:`file`-like object into
  744. an iterable. It yields `buffer_size` blocks until the file is fully
  745. read.
  746. You should not use this class directly but rather use the
  747. :func:`wrap_file` function that uses the WSGI server's file wrapper
  748. support if it's available.
  749. .. versionadded:: 0.5
  750. If you're using this object together with a :class:`BaseResponse` you have
  751. to use the `direct_passthrough` mode.
  752. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  753. :param buffer_size: number of bytes for one iteration.
  754. """
  755. def __init__(self, file, buffer_size=8192):
  756. self.file = file
  757. self.buffer_size = buffer_size
  758. def close(self):
  759. if hasattr(self.file, 'close'):
  760. self.file.close()
  761. def seekable(self):
  762. if hasattr(self.file, 'seekable'):
  763. return self.file.seekable()
  764. if hasattr(self.file, 'seek'):
  765. return True
  766. return False
  767. def seek(self, *args):
  768. if hasattr(self.file, 'seek'):
  769. self.file.seek(*args)
  770. def tell(self):
  771. if hasattr(self.file, 'tell'):
  772. return self.file.tell()
  773. return None
  774. def __iter__(self):
  775. return self
  776. def __next__(self):
  777. data = self.file.read(self.buffer_size)
  778. if data:
  779. return data
  780. raise StopIteration()
  781. @implements_iterator
  782. class _RangeWrapper(object):
  783. # private for now, but should we make it public in the future ?
  784. """This class can be used to convert an iterable object into
  785. an iterable that will only yield a piece of the underlying content.
  786. It yields blocks until the underlying stream range is fully read.
  787. The yielded blocks will have a size that can't exceed the original
  788. iterator defined block size, but that can be smaller.
  789. If you're using this object together with a :class:`BaseResponse` you have
  790. to use the `direct_passthrough` mode.
  791. :param iterable: an iterable object with a :meth:`__next__` method.
  792. :param start_byte: byte from which read will start.
  793. :param byte_range: how many bytes to read.
  794. """
  795. def __init__(self, iterable, start_byte=0, byte_range=None):
  796. self.iterable = iter(iterable)
  797. self.byte_range = byte_range
  798. self.start_byte = start_byte
  799. self.end_byte = None
  800. if byte_range is not None:
  801. self.end_byte = self.start_byte + self.byte_range
  802. self.read_length = 0
  803. self.seekable = hasattr(iterable, 'seekable') and iterable.seekable()
  804. self.end_reached = False
  805. def __iter__(self):
  806. return self
  807. def _next_chunk(self):
  808. try:
  809. chunk = next(self.iterable)
  810. self.read_length += len(chunk)
  811. return chunk
  812. except StopIteration:
  813. self.end_reached = True
  814. raise
  815. def _first_iteration(self):
  816. chunk = None
  817. if self.seekable:
  818. self.iterable.seek(self.start_byte)
  819. self.read_length = self.iterable.tell()
  820. contextual_read_length = self.read_length
  821. else:
  822. while self.read_length <= self.start_byte:
  823. chunk = self._next_chunk()
  824. if chunk is not None:
  825. chunk = chunk[self.start_byte - self.read_length:]
  826. contextual_read_length = self.start_byte
  827. return chunk, contextual_read_length
  828. def _next(self):
  829. if self.end_reached:
  830. raise StopIteration()
  831. chunk = None
  832. contextual_read_length = self.read_length
  833. if self.read_length == 0:
  834. chunk, contextual_read_length = self._first_iteration()
  835. if chunk is None:
  836. chunk = self._next_chunk()
  837. if self.end_byte is not None and self.read_length >= self.end_byte:
  838. self.end_reached = True
  839. return chunk[:self.end_byte - contextual_read_length]
  840. return chunk
  841. def __next__(self):
  842. chunk = self._next()
  843. if chunk:
  844. return chunk
  845. self.end_reached = True
  846. raise StopIteration()
  847. def close(self):
  848. if hasattr(self.iterable, 'close'):
  849. self.iterable.close()
  850. def _make_chunk_iter(stream, limit, buffer_size):
  851. """Helper for the line and chunk iter functions."""
  852. if isinstance(stream, (bytes, bytearray, text_type)):
  853. raise TypeError('Passed a string or byte object instead of '
  854. 'true iterator or stream.')
  855. if not hasattr(stream, 'read'):
  856. for item in stream:
  857. if item:
  858. yield item
  859. return
  860. if not isinstance(stream, LimitedStream) and limit is not None:
  861. stream = LimitedStream(stream, limit)
  862. _read = stream.read
  863. while 1:
  864. item = _read(buffer_size)
  865. if not item:
  866. break
  867. yield item
  868. def make_line_iter(stream, limit=None, buffer_size=10 * 1024,
  869. cap_at_buffer=False):
  870. """Safely iterates line-based over an input stream. If the input stream
  871. is not a :class:`LimitedStream` the `limit` parameter is mandatory.
  872. This uses the stream's :meth:`~file.read` method internally as opposite
  873. to the :meth:`~file.readline` method that is unsafe and can only be used
  874. in violation of the WSGI specification. The same problem applies to the
  875. `__iter__` function of the input stream which calls :meth:`~file.readline`
  876. without arguments.
  877. If you need line-by-line processing it's strongly recommended to iterate
  878. over the input stream using this helper function.
  879. .. versionchanged:: 0.8
  880. This function now ensures that the limit was reached.
  881. .. versionadded:: 0.9
  882. added support for iterators as input stream.
  883. .. versionadded:: 0.11.10
  884. added support for the `cap_at_buffer` parameter.
  885. :param stream: the stream or iterate to iterate over.
  886. :param limit: the limit in bytes for the stream. (Usually
  887. content length. Not necessary if the `stream`
  888. is a :class:`LimitedStream`.
  889. :param buffer_size: The optional buffer size.
  890. :param cap_at_buffer: if this is set chunks are split if they are longer
  891. than the buffer size. Internally this is implemented
  892. that the buffer size might be exhausted by a factor
  893. of two however.
  894. """
  895. _iter = _make_chunk_iter(stream, limit, buffer_size)
  896. first_item = next(_iter, '')
  897. if not first_item:
  898. return
  899. s = make_literal_wrapper(first_item)
  900. empty = s('')
  901. cr = s('\r')
  902. lf = s('\n')
  903. crlf = s('\r\n')
  904. _iter = chain((first_item,), _iter)
  905. def _iter_basic_lines():
  906. _join = empty.join
  907. buffer = []
  908. while 1:
  909. new_data = next(_iter, '')
  910. if not new_data:
  911. break
  912. new_buf = []
  913. buf_size = 0
  914. for item in chain(buffer, new_data.splitlines(True)):
  915. new_buf.append(item)
  916. buf_size += len(item)
  917. if item and item[-1:] in crlf:
  918. yield _join(new_buf)
  919. new_buf = []
  920. elif cap_at_buffer and buf_size >= buffer_size:
  921. rv = _join(new_buf)
  922. while len(rv) >= buffer_size:
  923. yield rv[:buffer_size]
  924. rv = rv[buffer_size:]
  925. new_buf = [rv]
  926. buffer = new_buf
  927. if buffer:
  928. yield _join(buffer)
  929. # This hackery is necessary to merge 'foo\r' and '\n' into one item
  930. # of 'foo\r\n' if we were unlucky and we hit a chunk boundary.
  931. previous = empty
  932. for item in _iter_basic_lines():
  933. if item == lf and previous[-1:] == cr:
  934. previous += item
  935. item = empty
  936. if previous:
  937. yield previous
  938. previous = item
  939. if previous:
  940. yield previous
  941. def make_chunk_iter(stream, separator, limit=None, buffer_size=10 * 1024,
  942. cap_at_buffer=False):
  943. """Works like :func:`make_line_iter` but accepts a separator
  944. which divides chunks. If you want newline based processing
  945. you should use :func:`make_line_iter` instead as it
  946. supports arbitrary newline markers.
  947. .. versionadded:: 0.8
  948. .. versionadded:: 0.9
  949. added support for iterators as input stream.
  950. .. versionadded:: 0.11.10
  951. added support for the `cap_at_buffer` parameter.
  952. :param stream: the stream or iterate to iterate over.
  953. :param separator: the separator that divides chunks.
  954. :param limit: the limit in bytes for the stream. (Usually
  955. content length. Not necessary if the `stream`
  956. is otherwise already limited).
  957. :param buffer_size: The optional buffer size.
  958. :param cap_at_buffer: if this is set chunks are split if they are longer
  959. than the buffer size. Internally this is implemented
  960. that the buffer size might be exhausted by a factor
  961. of two however.
  962. """
  963. _iter = _make_chunk_iter(stream, limit, buffer_size)
  964. first_item = next(_iter, '')
  965. if not first_item:
  966. return
  967. _iter = chain((first_item,), _iter)
  968. if isinstance(first_item, text_type):
  969. separator = to_unicode(separator)
  970. _split = re.compile(r'(%s)' % re.escape(separator)).split
  971. _join = u''.join
  972. else:
  973. separator = to_bytes(separator)
  974. _split = re.compile(b'(' + re.escape(separator) + b')').split
  975. _join = b''.join
  976. buffer = []
  977. while 1:
  978. new_data = next(_iter, '')
  979. if not new_data:
  980. break
  981. chunks = _split(new_data)
  982. new_buf = []
  983. buf_size = 0
  984. for item in chain(buffer, chunks):
  985. if item == separator:
  986. yield _join(new_buf)
  987. new_buf = []
  988. buf_size = 0
  989. else:
  990. buf_size += len(item)
  991. new_buf.append(item)
  992. if cap_at_buffer and buf_size >= buffer_size:
  993. rv = _join(new_buf)
  994. while len(rv) >= buffer_size:
  995. yield rv[:buffer_size]
  996. rv = rv[buffer_size:]
  997. new_buf = [rv]
  998. buf_size = len(rv)
  999. buffer = new_buf
  1000. if buffer:
  1001. yield _join(buffer)
  1002. @implements_iterator
  1003. class LimitedStream(io.IOBase):
  1004. """Wraps a stream so that it doesn't read more than n bytes. If the
  1005. stream is exhausted and the caller tries to get more bytes from it
  1006. :func:`on_exhausted` is called which by default returns an empty
  1007. string. The return value of that function is forwarded
  1008. to the reader function. So if it returns an empty string
  1009. :meth:`read` will return an empty string as well.
  1010. The limit however must never be higher than what the stream can
  1011. output. Otherwise :meth:`readlines` will try to read past the
  1012. limit.
  1013. .. admonition:: Note on WSGI compliance
  1014. calls to :meth:`readline` and :meth:`readlines` are not
  1015. WSGI compliant because it passes a size argument to the
  1016. readline methods. Unfortunately the WSGI PEP is not safely
  1017. implementable without a size argument to :meth:`readline`
  1018. because there is no EOF marker in the stream. As a result
  1019. of that the use of :meth:`readline` is discouraged.
  1020. For the same reason iterating over the :class:`LimitedStream`
  1021. is not portable. It internally calls :meth:`readline`.
  1022. We strongly suggest using :meth:`read` only or using the
  1023. :func:`make_line_iter` which safely iterates line-based
  1024. over a WSGI input stream.
  1025. :param stream: the stream to wrap.
  1026. :param limit: the limit for the stream, must not be longer than
  1027. what the string can provide if the stream does not
  1028. end with `EOF` (like `wsgi.input`)
  1029. """
  1030. def __init__(self, stream, limit):
  1031. self._read = stream.read
  1032. self._readline = stream.readline
  1033. self._pos = 0
  1034. self.limit = limit
  1035. def __iter__(self):
  1036. return self
  1037. @property
  1038. def is_exhausted(self):
  1039. """If the stream is exhausted this attribute is `True`."""
  1040. return self._pos >= self.limit
  1041. def on_exhausted(self):
  1042. """This is called when the stream tries to read past the limit.
  1043. The return value of this function is returned from the reading
  1044. function.
  1045. """
  1046. # Read null bytes from the stream so that we get the
  1047. # correct end of stream marker.
  1048. return self._read(0)
  1049. def on_disconnect(self):
  1050. """What should happen if a disconnect is detected? The return
  1051. value of this function is returned from read functions in case
  1052. the client went away. By default a
  1053. :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
  1054. """
  1055. from werkzeug.exceptions import ClientDisconnected
  1056. raise ClientDisconnected()
  1057. def exhaust(self, chunk_size=1024 * 64):
  1058. """Exhaust the stream. This consumes all the data left until the
  1059. limit is reached.
  1060. :param chunk_size: the size for a chunk. It will read the chunk
  1061. until the stream is exhausted and throw away
  1062. the results.
  1063. """
  1064. to_read = self.limit - self._pos
  1065. chunk = chunk_size
  1066. while to_read > 0:
  1067. chunk = min(to_read, chunk)
  1068. self.read(chunk)
  1069. to_read -= chunk
  1070. def read(self, size=None):
  1071. """Read `size` bytes or if size is not provided everything is read.
  1072. :param size: the number of bytes read.
  1073. """
  1074. if self._pos >= self.limit:
  1075. return self.on_exhausted()
  1076. if size is None or size == -1: # -1 is for consistence with file
  1077. size = self.limit
  1078. to_read = min(self.limit - self._pos, size)
  1079. try:
  1080. read = self._read(to_read)
  1081. except (IOError, ValueError):
  1082. return self.on_disconnect()
  1083. if to_read and len(read) != to_read:
  1084. return self.on_disconnect()
  1085. self._pos += len(read)
  1086. return read
  1087. def readline(self, size=None):
  1088. """Reads one line from the stream."""
  1089. if self._pos >= self.limit:
  1090. return self.on_exhausted()
  1091. if size is None:
  1092. size = self.limit - self._pos
  1093. else:
  1094. size = min(size, self.limit - self._pos)
  1095. try:
  1096. line = self._readline(size)
  1097. except (ValueError, IOError):
  1098. return self.on_disconnect()
  1099. if size and not line:
  1100. return self.on_disconnect()
  1101. self._pos += len(line)
  1102. return line
  1103. def readlines(self, size=None):
  1104. """Reads a file into a list of strings. It calls :meth:`readline`
  1105. until the file is read to the end. It does support the optional
  1106. `size` argument if the underlaying stream supports it for
  1107. `readline`.
  1108. """
  1109. last_pos = self._pos
  1110. result = []
  1111. if size is not None:
  1112. end = min(self.limit, last_pos + size)
  1113. else:
  1114. end = self.limit
  1115. while 1:
  1116. if size is not None:
  1117. size -= last_pos - self._pos
  1118. if self._pos >= end:
  1119. break
  1120. result.append(self.readline(size))
  1121. if size is not None:
  1122. last_pos = self._pos
  1123. return result
  1124. def tell(self):
  1125. """Returns the position of the stream.
  1126. .. versionadded:: 0.9
  1127. """
  1128. return self._pos
  1129. def __next__(self):
  1130. line = self.readline()
  1131. if not line:
  1132. raise StopIteration()
  1133. return line
  1134. def readable(self):
  1135. return True