wsgi.py 34 KB

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