wsgi.py 33 KB

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