wsgi.py 34 KB

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