25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1068 lines
36KB

  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.wsgi
  4. ~~~~~~~~~~~~~
  5. This module implements WSGI related helpers.
  6. :copyright: 2007 Pallets
  7. :license: BSD-3-Clause
  8. """
  9. import io
  10. import re
  11. import warnings
  12. from functools import partial
  13. from functools import update_wrapper
  14. from itertools import chain
  15. from ._compat import BytesIO
  16. from ._compat import implements_iterator
  17. from ._compat import make_literal_wrapper
  18. from ._compat import string_types
  19. from ._compat import text_type
  20. from ._compat import to_bytes
  21. from ._compat import to_unicode
  22. from ._compat import try_coerce_native
  23. from ._compat import wsgi_get_bytes
  24. from ._internal import _encode_idna
  25. from .urls import uri_to_iri
  26. from .urls import url_join
  27. from .urls import url_parse
  28. from .urls import url_quote
  29. def responder(f):
  30. """Marks a function as responder. Decorate a function with it and it
  31. will automatically call the return value as WSGI application.
  32. Example::
  33. @responder
  34. def application(environ, start_response):
  35. return Response('Hello World!')
  36. """
  37. return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
  38. def get_current_url(
  39. environ,
  40. root_only=False,
  41. strip_querystring=False,
  42. host_only=False,
  43. trusted_hosts=None,
  44. ):
  45. """A handy helper function that recreates the full URL as IRI for the
  46. current request or parts of it. Here's an example:
  47. >>> from werkzeug.test import create_environ
  48. >>> env = create_environ("/?param=foo", "http://localhost/script")
  49. >>> get_current_url(env)
  50. 'http://localhost/script/?param=foo'
  51. >>> get_current_url(env, root_only=True)
  52. 'http://localhost/script/'
  53. >>> get_current_url(env, host_only=True)
  54. 'http://localhost/'
  55. >>> get_current_url(env, strip_querystring=True)
  56. 'http://localhost/script/'
  57. This optionally it verifies that the host is in a list of trusted hosts.
  58. If the host is not in there it will raise a
  59. :exc:`~werkzeug.exceptions.SecurityError`.
  60. Note that the string returned might contain unicode characters as the
  61. representation is an IRI not an URI. If you need an ASCII only
  62. representation you can use the :func:`~werkzeug.urls.iri_to_uri`
  63. function:
  64. >>> from werkzeug.urls import iri_to_uri
  65. >>> iri_to_uri(get_current_url(env))
  66. 'http://localhost/script/?param=foo'
  67. :param environ: the WSGI environment to get the current URL from.
  68. :param root_only: set `True` if you only want the root URL.
  69. :param strip_querystring: set to `True` if you don't want the querystring.
  70. :param host_only: set to `True` if the host URL should be returned.
  71. :param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
  72. for more information.
  73. """
  74. tmp = [environ["wsgi.url_scheme"], "://", get_host(environ, trusted_hosts)]
  75. cat = tmp.append
  76. if host_only:
  77. return uri_to_iri("".join(tmp) + "/")
  78. cat(url_quote(wsgi_get_bytes(environ.get("SCRIPT_NAME", ""))).rstrip("/"))
  79. cat("/")
  80. if not root_only:
  81. cat(url_quote(wsgi_get_bytes(environ.get("PATH_INFO", "")).lstrip(b"/")))
  82. if not strip_querystring:
  83. qs = get_query_string(environ)
  84. if qs:
  85. cat("?" + qs)
  86. return uri_to_iri("".join(tmp))
  87. def host_is_trusted(hostname, trusted_list):
  88. """Checks if a host is trusted against a list. This also takes care
  89. of port normalization.
  90. .. versionadded:: 0.9
  91. :param hostname: the hostname to check
  92. :param trusted_list: a list of hostnames to check against. If a
  93. hostname starts with a dot it will match against
  94. all subdomains as well.
  95. """
  96. if not hostname:
  97. return False
  98. if isinstance(trusted_list, string_types):
  99. trusted_list = [trusted_list]
  100. def _normalize(hostname):
  101. if ":" in hostname:
  102. hostname = hostname.rsplit(":", 1)[0]
  103. return _encode_idna(hostname)
  104. try:
  105. hostname = _normalize(hostname)
  106. except UnicodeError:
  107. return False
  108. for ref in trusted_list:
  109. if ref.startswith("."):
  110. ref = ref[1:]
  111. suffix_match = True
  112. else:
  113. suffix_match = False
  114. try:
  115. ref = _normalize(ref)
  116. except UnicodeError:
  117. return False
  118. if ref == hostname:
  119. return True
  120. if suffix_match and hostname.endswith(b"." + ref):
  121. return True
  122. return False
  123. def get_host(environ, trusted_hosts=None):
  124. """Return the host for the given WSGI environment. This first checks
  125. the ``Host`` header. If it's not present, then ``SERVER_NAME`` and
  126. ``SERVER_PORT`` are used. The host will only contain the port if it
  127. is different than the standard port for the protocol.
  128. Optionally, verify that the host is trusted using
  129. :func:`host_is_trusted` and raise a
  130. :exc:`~werkzeug.exceptions.SecurityError` if it is not.
  131. :param environ: The WSGI environment to get the host from.
  132. :param trusted_hosts: A list of trusted hosts.
  133. :return: Host, with port if necessary.
  134. :raise ~werkzeug.exceptions.SecurityError: If the host is not
  135. trusted.
  136. """
  137. if "HTTP_HOST" in environ:
  138. rv = environ["HTTP_HOST"]
  139. if environ["wsgi.url_scheme"] == "http" and rv.endswith(":80"):
  140. rv = rv[:-3]
  141. elif environ["wsgi.url_scheme"] == "https" and rv.endswith(":443"):
  142. rv = rv[:-4]
  143. else:
  144. rv = environ["SERVER_NAME"]
  145. if (environ["wsgi.url_scheme"], environ["SERVER_PORT"]) not in (
  146. ("https", "443"),
  147. ("http", "80"),
  148. ):
  149. rv += ":" + environ["SERVER_PORT"]
  150. if trusted_hosts is not None:
  151. if not host_is_trusted(rv, trusted_hosts):
  152. from .exceptions import SecurityError
  153. raise SecurityError('Host "%s" is not trusted' % rv)
  154. return rv
  155. def get_content_length(environ):
  156. """Returns the content length from the WSGI environment as
  157. integer. If it's not available or chunked transfer encoding is used,
  158. ``None`` is returned.
  159. .. versionadded:: 0.9
  160. :param environ: the WSGI environ to fetch the content length from.
  161. """
  162. if environ.get("HTTP_TRANSFER_ENCODING", "") == "chunked":
  163. return None
  164. content_length = environ.get("CONTENT_LENGTH")
  165. if content_length is not None:
  166. try:
  167. return max(0, int(content_length))
  168. except (ValueError, TypeError):
  169. pass
  170. def get_input_stream(environ, safe_fallback=True):
  171. """Returns the input stream from the WSGI environment and wraps it
  172. in the most sensible way possible. The stream returned is not the
  173. raw WSGI stream in most cases but one that is safe to read from
  174. without taking into account the content length.
  175. If content length is not set, the stream will be empty for safety reasons.
  176. If the WSGI server supports chunked or infinite streams, it should set
  177. the ``wsgi.input_terminated`` value in the WSGI environ to indicate that.
  178. .. versionadded:: 0.9
  179. :param environ: the WSGI environ to fetch the stream from.
  180. :param safe_fallback: use an empty stream as a safe fallback when the
  181. content length is not set. Disabling this allows infinite streams,
  182. which can be a denial-of-service risk.
  183. """
  184. stream = environ["wsgi.input"]
  185. content_length = get_content_length(environ)
  186. # A wsgi extension that tells us if the input is terminated. In
  187. # that case we return the stream unchanged as we know we can safely
  188. # read it until the end.
  189. if environ.get("wsgi.input_terminated"):
  190. return stream
  191. # If the request doesn't specify a content length, returning the stream is
  192. # potentially dangerous because it could be infinite, malicious or not. If
  193. # safe_fallback is true, return an empty stream instead for safety.
  194. if content_length is None:
  195. return BytesIO() if safe_fallback else stream
  196. # Otherwise limit the stream to the content length
  197. return LimitedStream(stream, content_length)
  198. def get_query_string(environ):
  199. """Returns the `QUERY_STRING` from the WSGI environment. This also takes
  200. care about the WSGI decoding dance on Python 3 environments as a
  201. native string. The string returned will be restricted to ASCII
  202. characters.
  203. .. versionadded:: 0.9
  204. :param environ: the WSGI environment object to get the query string from.
  205. """
  206. qs = wsgi_get_bytes(environ.get("QUERY_STRING", ""))
  207. # QUERY_STRING really should be ascii safe but some browsers
  208. # will send us some unicode stuff (I am looking at you IE).
  209. # In that case we want to urllib quote it badly.
  210. return try_coerce_native(url_quote(qs, safe=":&%=+$!*'(),"))
  211. def get_path_info(environ, charset="utf-8", errors="replace"):
  212. """Returns the `PATH_INFO` from the WSGI environment and properly
  213. decodes it. This also takes care about the WSGI decoding dance
  214. on Python 3 environments. if the `charset` is set to `None` a
  215. bytestring is returned.
  216. .. versionadded:: 0.9
  217. :param environ: the WSGI environment object to get the path from.
  218. :param charset: the charset for the path info, or `None` if no
  219. decoding should be performed.
  220. :param errors: the decoding error handling.
  221. """
  222. path = wsgi_get_bytes(environ.get("PATH_INFO", ""))
  223. return to_unicode(path, charset, errors, allow_none_charset=True)
  224. def get_script_name(environ, charset="utf-8", errors="replace"):
  225. """Returns the `SCRIPT_NAME` from the WSGI environment and properly
  226. decodes it. This also takes care about the WSGI decoding dance
  227. on Python 3 environments. if the `charset` is set to `None` a
  228. bytestring is returned.
  229. .. versionadded:: 0.9
  230. :param environ: the WSGI environment object to get the path from.
  231. :param charset: the charset for the path, or `None` if no
  232. decoding should be performed.
  233. :param errors: the decoding error handling.
  234. """
  235. path = wsgi_get_bytes(environ.get("SCRIPT_NAME", ""))
  236. return to_unicode(path, charset, errors, allow_none_charset=True)
  237. def pop_path_info(environ, charset="utf-8", errors="replace"):
  238. """Removes and returns the next segment of `PATH_INFO`, pushing it onto
  239. `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`.
  240. If the `charset` is set to `None` a bytestring is returned.
  241. If there are empty segments (``'/foo//bar``) these are ignored but
  242. properly pushed to the `SCRIPT_NAME`:
  243. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  244. >>> pop_path_info(env)
  245. 'a'
  246. >>> env['SCRIPT_NAME']
  247. '/foo/a'
  248. >>> pop_path_info(env)
  249. 'b'
  250. >>> env['SCRIPT_NAME']
  251. '/foo/a/b'
  252. .. versionadded:: 0.5
  253. .. versionchanged:: 0.9
  254. The path is now decoded and a charset and encoding
  255. parameter can be provided.
  256. :param environ: the WSGI environment that is modified.
  257. """
  258. path = environ.get("PATH_INFO")
  259. if not path:
  260. return None
  261. script_name = environ.get("SCRIPT_NAME", "")
  262. # shift multiple leading slashes over
  263. old_path = path
  264. path = path.lstrip("/")
  265. if path != old_path:
  266. script_name += "/" * (len(old_path) - len(path))
  267. if "/" not in path:
  268. environ["PATH_INFO"] = ""
  269. environ["SCRIPT_NAME"] = script_name + path
  270. rv = wsgi_get_bytes(path)
  271. else:
  272. segment, path = path.split("/", 1)
  273. environ["PATH_INFO"] = "/" + path
  274. environ["SCRIPT_NAME"] = script_name + segment
  275. rv = wsgi_get_bytes(segment)
  276. return to_unicode(rv, charset, errors, allow_none_charset=True)
  277. def peek_path_info(environ, charset="utf-8", errors="replace"):
  278. """Returns the next segment on the `PATH_INFO` or `None` if there
  279. is none. Works like :func:`pop_path_info` without modifying the
  280. environment:
  281. >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
  282. >>> peek_path_info(env)
  283. 'a'
  284. >>> peek_path_info(env)
  285. 'a'
  286. If the `charset` is set to `None` a bytestring is returned.
  287. .. versionadded:: 0.5
  288. .. versionchanged:: 0.9
  289. The path is now decoded and a charset and encoding
  290. parameter can be provided.
  291. :param environ: the WSGI environment that is checked.
  292. """
  293. segments = environ.get("PATH_INFO", "").lstrip("/").split("/", 1)
  294. if segments:
  295. return to_unicode(
  296. wsgi_get_bytes(segments[0]), charset, errors, allow_none_charset=True
  297. )
  298. def extract_path_info(
  299. environ_or_baseurl,
  300. path_or_url,
  301. charset="utf-8",
  302. errors="werkzeug.url_quote",
  303. collapse_http_schemes=True,
  304. ):
  305. """Extracts the path info from the given URL (or WSGI environment) and
  306. path. The path info returned is a unicode string, not a bytestring
  307. suitable for a WSGI environment. The URLs might also be IRIs.
  308. If the path info could not be determined, `None` is returned.
  309. Some examples:
  310. >>> extract_path_info('http://example.com/app', '/app/hello')
  311. u'/hello'
  312. >>> extract_path_info('http://example.com/app',
  313. ... 'https://example.com/app/hello')
  314. u'/hello'
  315. >>> extract_path_info('http://example.com/app',
  316. ... 'https://example.com/app/hello',
  317. ... collapse_http_schemes=False) is None
  318. True
  319. Instead of providing a base URL you can also pass a WSGI environment.
  320. :param environ_or_baseurl: a WSGI environment dict, a base URL or
  321. base IRI. This is the root of the
  322. application.
  323. :param path_or_url: an absolute path from the server root, a
  324. relative path (in which case it's the path info)
  325. or a full URL. Also accepts IRIs and unicode
  326. parameters.
  327. :param charset: the charset for byte data in URLs
  328. :param errors: the error handling on decode
  329. :param collapse_http_schemes: if set to `False` the algorithm does
  330. not assume that http and https on the
  331. same server point to the same
  332. resource.
  333. .. versionchanged:: 0.15
  334. The ``errors`` parameter defaults to leaving invalid bytes
  335. quoted instead of replacing them.
  336. .. versionadded:: 0.6
  337. """
  338. def _normalize_netloc(scheme, netloc):
  339. parts = netloc.split(u"@", 1)[-1].split(u":", 1)
  340. if len(parts) == 2:
  341. netloc, port = parts
  342. if (scheme == u"http" and port == u"80") or (
  343. scheme == u"https" and port == u"443"
  344. ):
  345. port = None
  346. else:
  347. netloc = parts[0]
  348. port = None
  349. if port is not None:
  350. netloc += u":" + port
  351. return netloc
  352. # make sure whatever we are working on is a IRI and parse it
  353. path = uri_to_iri(path_or_url, charset, errors)
  354. if isinstance(environ_or_baseurl, dict):
  355. environ_or_baseurl = get_current_url(environ_or_baseurl, root_only=True)
  356. base_iri = uri_to_iri(environ_or_baseurl, charset, errors)
  357. base_scheme, base_netloc, base_path = url_parse(base_iri)[:3]
  358. cur_scheme, cur_netloc, cur_path, = url_parse(url_join(base_iri, path))[:3]
  359. # normalize the network location
  360. base_netloc = _normalize_netloc(base_scheme, base_netloc)
  361. cur_netloc = _normalize_netloc(cur_scheme, cur_netloc)
  362. # is that IRI even on a known HTTP scheme?
  363. if collapse_http_schemes:
  364. for scheme in base_scheme, cur_scheme:
  365. if scheme not in (u"http", u"https"):
  366. return None
  367. else:
  368. if not (base_scheme in (u"http", u"https") and base_scheme == cur_scheme):
  369. return None
  370. # are the netlocs compatible?
  371. if base_netloc != cur_netloc:
  372. return None
  373. # are we below the application path?
  374. base_path = base_path.rstrip(u"/")
  375. if not cur_path.startswith(base_path):
  376. return None
  377. return u"/" + cur_path[len(base_path) :].lstrip(u"/")
  378. @implements_iterator
  379. class ClosingIterator(object):
  380. """The WSGI specification requires that all middlewares and gateways
  381. respect the `close` callback of the iterable returned by the application.
  382. Because it is useful to add another close action to a returned iterable
  383. and adding a custom iterable is a boring task this class can be used for
  384. that::
  385. return ClosingIterator(app(environ, start_response), [cleanup_session,
  386. cleanup_locals])
  387. If there is just one close function it can be passed instead of the list.
  388. A closing iterator is not needed if the application uses response objects
  389. and finishes the processing if the response is started::
  390. try:
  391. return response(environ, start_response)
  392. finally:
  393. cleanup_session()
  394. cleanup_locals()
  395. """
  396. def __init__(self, iterable, callbacks=None):
  397. iterator = iter(iterable)
  398. self._next = partial(next, iterator)
  399. if callbacks is None:
  400. callbacks = []
  401. elif callable(callbacks):
  402. callbacks = [callbacks]
  403. else:
  404. callbacks = list(callbacks)
  405. iterable_close = getattr(iterable, "close", None)
  406. if iterable_close:
  407. callbacks.insert(0, iterable_close)
  408. self._callbacks = callbacks
  409. def __iter__(self):
  410. return self
  411. def __next__(self):
  412. return self._next()
  413. def close(self):
  414. for callback in self._callbacks:
  415. callback()
  416. def wrap_file(environ, file, buffer_size=8192):
  417. """Wraps a file. This uses the WSGI server's file wrapper if available
  418. or otherwise the generic :class:`FileWrapper`.
  419. .. versionadded:: 0.5
  420. If the file wrapper from the WSGI server is used it's important to not
  421. iterate over it from inside the application but to pass it through
  422. unchanged. If you want to pass out a file wrapper inside a response
  423. object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`.
  424. More information about file wrappers are available in :pep:`333`.
  425. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  426. :param buffer_size: number of bytes for one iteration.
  427. """
  428. return environ.get("wsgi.file_wrapper", FileWrapper)(file, buffer_size)
  429. @implements_iterator
  430. class FileWrapper(object):
  431. """This class can be used to convert a :class:`file`-like object into
  432. an iterable. It yields `buffer_size` blocks until the file is fully
  433. read.
  434. You should not use this class directly but rather use the
  435. :func:`wrap_file` function that uses the WSGI server's file wrapper
  436. support if it's available.
  437. .. versionadded:: 0.5
  438. If you're using this object together with a :class:`BaseResponse` you have
  439. to use the `direct_passthrough` mode.
  440. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  441. :param buffer_size: number of bytes for one iteration.
  442. """
  443. def __init__(self, file, buffer_size=8192):
  444. self.file = file
  445. self.buffer_size = buffer_size
  446. def close(self):
  447. if hasattr(self.file, "close"):
  448. self.file.close()
  449. def seekable(self):
  450. if hasattr(self.file, "seekable"):
  451. return self.file.seekable()
  452. if hasattr(self.file, "seek"):
  453. return True
  454. return False
  455. def seek(self, *args):
  456. if hasattr(self.file, "seek"):
  457. self.file.seek(*args)
  458. def tell(self):
  459. if hasattr(self.file, "tell"):
  460. return self.file.tell()
  461. return None
  462. def __iter__(self):
  463. return self
  464. def __next__(self):
  465. data = self.file.read(self.buffer_size)
  466. if data:
  467. return data
  468. raise StopIteration()
  469. @implements_iterator
  470. class _RangeWrapper(object):
  471. # private for now, but should we make it public in the future ?
  472. """This class can be used to convert an iterable object into
  473. an iterable that will only yield a piece of the underlying content.
  474. It yields blocks until the underlying stream range is fully read.
  475. The yielded blocks will have a size that can't exceed the original
  476. iterator defined block size, but that can be smaller.
  477. If you're using this object together with a :class:`BaseResponse` you have
  478. to use the `direct_passthrough` mode.
  479. :param iterable: an iterable object with a :meth:`__next__` method.
  480. :param start_byte: byte from which read will start.
  481. :param byte_range: how many bytes to read.
  482. """
  483. def __init__(self, iterable, start_byte=0, byte_range=None):
  484. self.iterable = iter(iterable)
  485. self.byte_range = byte_range
  486. self.start_byte = start_byte
  487. self.end_byte = None
  488. if byte_range is not None:
  489. self.end_byte = self.start_byte + self.byte_range
  490. self.read_length = 0
  491. self.seekable = hasattr(iterable, "seekable") and iterable.seekable()
  492. self.end_reached = False
  493. def __iter__(self):
  494. return self
  495. def _next_chunk(self):
  496. try:
  497. chunk = next(self.iterable)
  498. self.read_length += len(chunk)
  499. return chunk
  500. except StopIteration:
  501. self.end_reached = True
  502. raise
  503. def _first_iteration(self):
  504. chunk = None
  505. if self.seekable:
  506. self.iterable.seek(self.start_byte)
  507. self.read_length = self.iterable.tell()
  508. contextual_read_length = self.read_length
  509. else:
  510. while self.read_length <= self.start_byte:
  511. chunk = self._next_chunk()
  512. if chunk is not None:
  513. chunk = chunk[self.start_byte - self.read_length :]
  514. contextual_read_length = self.start_byte
  515. return chunk, contextual_read_length
  516. def _next(self):
  517. if self.end_reached:
  518. raise StopIteration()
  519. chunk = None
  520. contextual_read_length = self.read_length
  521. if self.read_length == 0:
  522. chunk, contextual_read_length = self._first_iteration()
  523. if chunk is None:
  524. chunk = self._next_chunk()
  525. if self.end_byte is not None and self.read_length >= self.end_byte:
  526. self.end_reached = True
  527. return chunk[: self.end_byte - contextual_read_length]
  528. return chunk
  529. def __next__(self):
  530. chunk = self._next()
  531. if chunk:
  532. return chunk
  533. self.end_reached = True
  534. raise StopIteration()
  535. def close(self):
  536. if hasattr(self.iterable, "close"):
  537. self.iterable.close()
  538. def _make_chunk_iter(stream, limit, buffer_size):
  539. """Helper for the line and chunk iter functions."""
  540. if isinstance(stream, (bytes, bytearray, text_type)):
  541. raise TypeError(
  542. "Passed a string or byte object instead of true iterator or stream."
  543. )
  544. if not hasattr(stream, "read"):
  545. for item in stream:
  546. if item:
  547. yield item
  548. return
  549. if not isinstance(stream, LimitedStream) and limit is not None:
  550. stream = LimitedStream(stream, limit)
  551. _read = stream.read
  552. while 1:
  553. item = _read(buffer_size)
  554. if not item:
  555. break
  556. yield item
  557. def make_line_iter(stream, limit=None, buffer_size=10 * 1024, cap_at_buffer=False):
  558. """Safely iterates line-based over an input stream. If the input stream
  559. is not a :class:`LimitedStream` the `limit` parameter is mandatory.
  560. This uses the stream's :meth:`~file.read` method internally as opposite
  561. to the :meth:`~file.readline` method that is unsafe and can only be used
  562. in violation of the WSGI specification. The same problem applies to the
  563. `__iter__` function of the input stream which calls :meth:`~file.readline`
  564. without arguments.
  565. If you need line-by-line processing it's strongly recommended to iterate
  566. over the input stream using this helper function.
  567. .. versionchanged:: 0.8
  568. This function now ensures that the limit was reached.
  569. .. versionadded:: 0.9
  570. added support for iterators as input stream.
  571. .. versionadded:: 0.11.10
  572. added support for the `cap_at_buffer` parameter.
  573. :param stream: the stream or iterate to iterate over.
  574. :param limit: the limit in bytes for the stream. (Usually
  575. content length. Not necessary if the `stream`
  576. is a :class:`LimitedStream`.
  577. :param buffer_size: The optional buffer size.
  578. :param cap_at_buffer: if this is set chunks are split if they are longer
  579. than the buffer size. Internally this is implemented
  580. that the buffer size might be exhausted by a factor
  581. of two however.
  582. """
  583. _iter = _make_chunk_iter(stream, limit, buffer_size)
  584. first_item = next(_iter, "")
  585. if not first_item:
  586. return
  587. s = make_literal_wrapper(first_item)
  588. empty = s("")
  589. cr = s("\r")
  590. lf = s("\n")
  591. crlf = s("\r\n")
  592. _iter = chain((first_item,), _iter)
  593. def _iter_basic_lines():
  594. _join = empty.join
  595. buffer = []
  596. while 1:
  597. new_data = next(_iter, "")
  598. if not new_data:
  599. break
  600. new_buf = []
  601. buf_size = 0
  602. for item in chain(buffer, new_data.splitlines(True)):
  603. new_buf.append(item)
  604. buf_size += len(item)
  605. if item and item[-1:] in crlf:
  606. yield _join(new_buf)
  607. new_buf = []
  608. elif cap_at_buffer and buf_size >= buffer_size:
  609. rv = _join(new_buf)
  610. while len(rv) >= buffer_size:
  611. yield rv[:buffer_size]
  612. rv = rv[buffer_size:]
  613. new_buf = [rv]
  614. buffer = new_buf
  615. if buffer:
  616. yield _join(buffer)
  617. # This hackery is necessary to merge 'foo\r' and '\n' into one item
  618. # of 'foo\r\n' if we were unlucky and we hit a chunk boundary.
  619. previous = empty
  620. for item in _iter_basic_lines():
  621. if item == lf and previous[-1:] == cr:
  622. previous += item
  623. item = empty
  624. if previous:
  625. yield previous
  626. previous = item
  627. if previous:
  628. yield previous
  629. def make_chunk_iter(
  630. stream, separator, limit=None, buffer_size=10 * 1024, cap_at_buffer=False
  631. ):
  632. """Works like :func:`make_line_iter` but accepts a separator
  633. which divides chunks. If you want newline based processing
  634. you should use :func:`make_line_iter` instead as it
  635. supports arbitrary newline markers.
  636. .. versionadded:: 0.8
  637. .. versionadded:: 0.9
  638. added support for iterators as input stream.
  639. .. versionadded:: 0.11.10
  640. added support for the `cap_at_buffer` parameter.
  641. :param stream: the stream or iterate to iterate over.
  642. :param separator: the separator that divides chunks.
  643. :param limit: the limit in bytes for the stream. (Usually
  644. content length. Not necessary if the `stream`
  645. is otherwise already limited).
  646. :param buffer_size: The optional buffer size.
  647. :param cap_at_buffer: if this is set chunks are split if they are longer
  648. than the buffer size. Internally this is implemented
  649. that the buffer size might be exhausted by a factor
  650. of two however.
  651. """
  652. _iter = _make_chunk_iter(stream, limit, buffer_size)
  653. first_item = next(_iter, "")
  654. if not first_item:
  655. return
  656. _iter = chain((first_item,), _iter)
  657. if isinstance(first_item, text_type):
  658. separator = to_unicode(separator)
  659. _split = re.compile(r"(%s)" % re.escape(separator)).split
  660. _join = u"".join
  661. else:
  662. separator = to_bytes(separator)
  663. _split = re.compile(b"(" + re.escape(separator) + b")").split
  664. _join = b"".join
  665. buffer = []
  666. while 1:
  667. new_data = next(_iter, "")
  668. if not new_data:
  669. break
  670. chunks = _split(new_data)
  671. new_buf = []
  672. buf_size = 0
  673. for item in chain(buffer, chunks):
  674. if item == separator:
  675. yield _join(new_buf)
  676. new_buf = []
  677. buf_size = 0
  678. else:
  679. buf_size += len(item)
  680. new_buf.append(item)
  681. if cap_at_buffer and buf_size >= buffer_size:
  682. rv = _join(new_buf)
  683. while len(rv) >= buffer_size:
  684. yield rv[:buffer_size]
  685. rv = rv[buffer_size:]
  686. new_buf = [rv]
  687. buf_size = len(rv)
  688. buffer = new_buf
  689. if buffer:
  690. yield _join(buffer)
  691. @implements_iterator
  692. class LimitedStream(io.IOBase):
  693. """Wraps a stream so that it doesn't read more than n bytes. If the
  694. stream is exhausted and the caller tries to get more bytes from it
  695. :func:`on_exhausted` is called which by default returns an empty
  696. string. The return value of that function is forwarded
  697. to the reader function. So if it returns an empty string
  698. :meth:`read` will return an empty string as well.
  699. The limit however must never be higher than what the stream can
  700. output. Otherwise :meth:`readlines` will try to read past the
  701. limit.
  702. .. admonition:: Note on WSGI compliance
  703. calls to :meth:`readline` and :meth:`readlines` are not
  704. WSGI compliant because it passes a size argument to the
  705. readline methods. Unfortunately the WSGI PEP is not safely
  706. implementable without a size argument to :meth:`readline`
  707. because there is no EOF marker in the stream. As a result
  708. of that the use of :meth:`readline` is discouraged.
  709. For the same reason iterating over the :class:`LimitedStream`
  710. is not portable. It internally calls :meth:`readline`.
  711. We strongly suggest using :meth:`read` only or using the
  712. :func:`make_line_iter` which safely iterates line-based
  713. over a WSGI input stream.
  714. :param stream: the stream to wrap.
  715. :param limit: the limit for the stream, must not be longer than
  716. what the string can provide if the stream does not
  717. end with `EOF` (like `wsgi.input`)
  718. """
  719. def __init__(self, stream, limit):
  720. self._read = stream.read
  721. self._readline = stream.readline
  722. self._pos = 0
  723. self.limit = limit
  724. def __iter__(self):
  725. return self
  726. @property
  727. def is_exhausted(self):
  728. """If the stream is exhausted this attribute is `True`."""
  729. return self._pos >= self.limit
  730. def on_exhausted(self):
  731. """This is called when the stream tries to read past the limit.
  732. The return value of this function is returned from the reading
  733. function.
  734. """
  735. # Read null bytes from the stream so that we get the
  736. # correct end of stream marker.
  737. return self._read(0)
  738. def on_disconnect(self):
  739. """What should happen if a disconnect is detected? The return
  740. value of this function is returned from read functions in case
  741. the client went away. By default a
  742. :exc:`~werkzeug.exceptions.ClientDisconnected` exception is raised.
  743. """
  744. from .exceptions import ClientDisconnected
  745. raise ClientDisconnected()
  746. def exhaust(self, chunk_size=1024 * 64):
  747. """Exhaust the stream. This consumes all the data left until the
  748. limit is reached.
  749. :param chunk_size: the size for a chunk. It will read the chunk
  750. until the stream is exhausted and throw away
  751. the results.
  752. """
  753. to_read = self.limit - self._pos
  754. chunk = chunk_size
  755. while to_read > 0:
  756. chunk = min(to_read, chunk)
  757. self.read(chunk)
  758. to_read -= chunk
  759. def read(self, size=None):
  760. """Read `size` bytes or if size is not provided everything is read.
  761. :param size: the number of bytes read.
  762. """
  763. if self._pos >= self.limit:
  764. return self.on_exhausted()
  765. if size is None or size == -1: # -1 is for consistence with file
  766. size = self.limit
  767. to_read = min(self.limit - self._pos, size)
  768. try:
  769. read = self._read(to_read)
  770. except (IOError, ValueError):
  771. return self.on_disconnect()
  772. if to_read and len(read) != to_read:
  773. return self.on_disconnect()
  774. self._pos += len(read)
  775. return read
  776. def readline(self, size=None):
  777. """Reads one line from the stream."""
  778. if self._pos >= self.limit:
  779. return self.on_exhausted()
  780. if size is None:
  781. size = self.limit - self._pos
  782. else:
  783. size = min(size, self.limit - self._pos)
  784. try:
  785. line = self._readline(size)
  786. except (ValueError, IOError):
  787. return self.on_disconnect()
  788. if size and not line:
  789. return self.on_disconnect()
  790. self._pos += len(line)
  791. return line
  792. def readlines(self, size=None):
  793. """Reads a file into a list of strings. It calls :meth:`readline`
  794. until the file is read to the end. It does support the optional
  795. `size` argument if the underlaying stream supports it for
  796. `readline`.
  797. """
  798. last_pos = self._pos
  799. result = []
  800. if size is not None:
  801. end = min(self.limit, last_pos + size)
  802. else:
  803. end = self.limit
  804. while 1:
  805. if size is not None:
  806. size -= last_pos - self._pos
  807. if self._pos >= end:
  808. break
  809. result.append(self.readline(size))
  810. if size is not None:
  811. last_pos = self._pos
  812. return result
  813. def tell(self):
  814. """Returns the position of the stream.
  815. .. versionadded:: 0.9
  816. """
  817. return self._pos
  818. def __next__(self):
  819. line = self.readline()
  820. if not line:
  821. raise StopIteration()
  822. return line
  823. def readable(self):
  824. return True
  825. # DEPRECATED
  826. from .middleware.dispatcher import DispatcherMiddleware as _DispatcherMiddleware
  827. from .middleware.http_proxy import ProxyMiddleware as _ProxyMiddleware
  828. from .middleware.shared_data import SharedDataMiddleware as _SharedDataMiddleware
  829. class ProxyMiddleware(_ProxyMiddleware):
  830. """
  831. .. deprecated:: 0.15
  832. ``werkzeug.wsgi.ProxyMiddleware`` has moved to
  833. :mod:`werkzeug.middleware.http_proxy`. This import will be
  834. removed in 1.0.
  835. """
  836. def __init__(self, *args, **kwargs):
  837. warnings.warn(
  838. "'werkzeug.wsgi.ProxyMiddleware' has moved to 'werkzeug"
  839. ".middleware.http_proxy.ProxyMiddleware'. This import is"
  840. " deprecated as of version 0.15 and will be removed in"
  841. " version 1.0.",
  842. DeprecationWarning,
  843. stacklevel=2,
  844. )
  845. super(ProxyMiddleware, self).__init__(*args, **kwargs)
  846. class SharedDataMiddleware(_SharedDataMiddleware):
  847. """
  848. .. deprecated:: 0.15
  849. ``werkzeug.wsgi.SharedDataMiddleware`` has moved to
  850. :mod:`werkzeug.middleware.shared_data`. This import will be
  851. removed in 1.0.
  852. """
  853. def __init__(self, *args, **kwargs):
  854. warnings.warn(
  855. "'werkzeug.wsgi.SharedDataMiddleware' has moved to"
  856. " 'werkzeug.middleware.shared_data.SharedDataMiddleware'."
  857. " This import is deprecated as of version 0.15 and will be"
  858. " removed in version 1.0.",
  859. DeprecationWarning,
  860. stacklevel=2,
  861. )
  862. super(SharedDataMiddleware, self).__init__(*args, **kwargs)
  863. class DispatcherMiddleware(_DispatcherMiddleware):
  864. """
  865. .. deprecated:: 0.15
  866. ``werkzeug.wsgi.DispatcherMiddleware`` has moved to
  867. :mod:`werkzeug.middleware.dispatcher`. This import will be
  868. removed in 1.0.
  869. """
  870. def __init__(self, *args, **kwargs):
  871. warnings.warn(
  872. "'werkzeug.wsgi.DispatcherMiddleware' has moved to"
  873. " 'werkzeug.middleware.dispatcher.DispatcherMiddleware'."
  874. " This import is deprecated as of version 0.15 and will be"
  875. " removed in version 1.0.",
  876. DeprecationWarning,
  877. stacklevel=2,
  878. )
  879. super(DispatcherMiddleware, self).__init__(*args, **kwargs)