wsgi.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. from __future__ import annotations
  2. import io
  3. import typing as t
  4. from functools import partial
  5. from functools import update_wrapper
  6. from .exceptions import ClientDisconnected
  7. from .exceptions import RequestEntityTooLarge
  8. from .sansio import utils as _sansio_utils
  9. from .sansio.utils import host_is_trusted # noqa: F401 # Imported as part of API
  10. if t.TYPE_CHECKING:
  11. from _typeshed.wsgi import WSGIApplication
  12. from _typeshed.wsgi import WSGIEnvironment
  13. def responder(f: t.Callable[..., WSGIApplication]) -> WSGIApplication:
  14. """Marks a function as responder. Decorate a function with it and it
  15. will automatically call the return value as WSGI application.
  16. Example::
  17. @responder
  18. def application(environ, start_response):
  19. return Response('Hello World!')
  20. """
  21. return update_wrapper(lambda *a: f(*a)(*a[-2:]), f)
  22. def get_current_url(
  23. environ: WSGIEnvironment,
  24. root_only: bool = False,
  25. strip_querystring: bool = False,
  26. host_only: bool = False,
  27. trusted_hosts: t.Iterable[str] | None = None,
  28. ) -> str:
  29. """Recreate the URL for a request from the parts in a WSGI
  30. environment.
  31. The URL is an IRI, not a URI, so it may contain Unicode characters.
  32. Use :func:`~werkzeug.urls.iri_to_uri` to convert it to ASCII.
  33. :param environ: The WSGI environment to get the URL parts from.
  34. :param root_only: Only build the root path, don't include the
  35. remaining path or query string.
  36. :param strip_querystring: Don't include the query string.
  37. :param host_only: Only build the scheme and host.
  38. :param trusted_hosts: A list of trusted host names to validate the
  39. host against.
  40. """
  41. parts = {
  42. "scheme": environ["wsgi.url_scheme"],
  43. "host": get_host(environ, trusted_hosts),
  44. }
  45. if not host_only:
  46. parts["root_path"] = environ.get("SCRIPT_NAME", "")
  47. if not root_only:
  48. parts["path"] = environ.get("PATH_INFO", "")
  49. if not strip_querystring:
  50. parts["query_string"] = environ.get("QUERY_STRING", "").encode("latin1")
  51. return _sansio_utils.get_current_url(**parts)
  52. def _get_server(
  53. environ: WSGIEnvironment,
  54. ) -> tuple[str, int | None] | None:
  55. name = environ.get("SERVER_NAME")
  56. if name is None:
  57. return None
  58. try:
  59. port: int | None = int(environ.get("SERVER_PORT", None))
  60. except (TypeError, ValueError):
  61. # unix socket
  62. port = None
  63. return name, port
  64. def get_host(
  65. environ: WSGIEnvironment, trusted_hosts: t.Iterable[str] | None = None
  66. ) -> str:
  67. """Return the host for the given WSGI environment.
  68. The ``Host`` header is preferred, then ``SERVER_NAME`` if it's not
  69. set. The returned host will only contain the port if it is different
  70. than the standard port for the protocol.
  71. Optionally, verify that the host is trusted using
  72. :func:`host_is_trusted` and raise a
  73. :exc:`~werkzeug.exceptions.SecurityError` if it is not.
  74. :param environ: A WSGI environment dict.
  75. :param trusted_hosts: A list of trusted host names.
  76. :return: Host, with port if necessary.
  77. :raise ~werkzeug.exceptions.SecurityError: If the host is not
  78. trusted.
  79. """
  80. return _sansio_utils.get_host(
  81. environ["wsgi.url_scheme"],
  82. environ.get("HTTP_HOST"),
  83. _get_server(environ),
  84. trusted_hosts,
  85. )
  86. def get_content_length(environ: WSGIEnvironment) -> int | None:
  87. """Return the ``Content-Length`` header value as an int. If the header is not given
  88. or the ``Transfer-Encoding`` header is ``chunked``, ``None`` is returned to indicate
  89. a streaming request. If the value is not an integer, or negative, 0 is returned.
  90. :param environ: The WSGI environ to get the content length from.
  91. .. versionadded:: 0.9
  92. """
  93. return _sansio_utils.get_content_length(
  94. http_content_length=environ.get("CONTENT_LENGTH"),
  95. http_transfer_encoding=environ.get("HTTP_TRANSFER_ENCODING"),
  96. )
  97. def get_input_stream(
  98. environ: WSGIEnvironment,
  99. safe_fallback: bool = True,
  100. max_content_length: int | None = None,
  101. ) -> t.IO[bytes]:
  102. """Return the WSGI input stream, wrapped so that it may be read safely without going
  103. past the ``Content-Length`` header value or ``max_content_length``.
  104. If ``Content-Length`` exceeds ``max_content_length``, a
  105. :exc:`RequestEntityTooLarge`` ``413 Content Too Large`` error is raised.
  106. If the WSGI server sets ``environ["wsgi.input_terminated"]``, it indicates that the
  107. server handles terminating the stream, so it is safe to read directly. For example,
  108. a server that knows how to handle chunked requests safely would set this.
  109. If ``max_content_length`` is set, it can be enforced on streams if
  110. ``wsgi.input_terminated`` is set. Otherwise, an empty stream is returned unless the
  111. user explicitly disables this safe fallback.
  112. If the limit is reached before the underlying stream is exhausted (such as a file
  113. that is too large, or an infinite stream), the remaining contents of the stream
  114. cannot be read safely. Depending on how the server handles this, clients may show a
  115. "connection reset" failure instead of seeing the 413 response.
  116. :param environ: The WSGI environ containing the stream.
  117. :param safe_fallback: Return an empty stream when ``Content-Length`` is not set.
  118. Disabling this allows infinite streams, which can be a denial-of-service risk.
  119. :param max_content_length: The maximum length that content-length or streaming
  120. requests may not exceed.
  121. .. versionchanged:: 2.3.2
  122. ``max_content_length`` is only applied to streaming requests if the server sets
  123. ``wsgi.input_terminated``.
  124. .. versionchanged:: 2.3
  125. Check ``max_content_length`` and raise an error if it is exceeded.
  126. .. versionadded:: 0.9
  127. """
  128. stream = t.cast(t.IO[bytes], environ["wsgi.input"])
  129. content_length = get_content_length(environ)
  130. if content_length is not None and max_content_length is not None:
  131. if content_length > max_content_length:
  132. raise RequestEntityTooLarge()
  133. # A WSGI server can set this to indicate that it terminates the input stream. In
  134. # that case the stream is safe without wrapping, or can enforce a max length.
  135. if "wsgi.input_terminated" in environ:
  136. if max_content_length is not None:
  137. # If this is moved above, it can cause the stream to hang if a read attempt
  138. # is made when the client sends no data. For example, the development server
  139. # does not handle buffering except for chunked encoding.
  140. return t.cast(
  141. t.IO[bytes], LimitedStream(stream, max_content_length, is_max=True)
  142. )
  143. return stream
  144. # No limit given, return an empty stream unless the user explicitly allows the
  145. # potentially infinite stream. An infinite stream is dangerous if it's not expected,
  146. # as it can tie up a worker indefinitely.
  147. if content_length is None:
  148. return io.BytesIO() if safe_fallback else stream
  149. return t.cast(t.IO[bytes], LimitedStream(stream, content_length))
  150. def get_path_info(environ: WSGIEnvironment) -> str:
  151. """Return ``PATH_INFO`` from the WSGI environment.
  152. :param environ: WSGI environment to get the path from.
  153. .. versionchanged:: 3.0
  154. The ``charset`` and ``errors`` parameters were removed.
  155. .. versionadded:: 0.9
  156. """
  157. path: bytes = environ.get("PATH_INFO", "").encode("latin1")
  158. return path.decode(errors="replace")
  159. class ClosingIterator:
  160. """The WSGI specification requires that all middlewares and gateways
  161. respect the `close` callback of the iterable returned by the application.
  162. Because it is useful to add another close action to a returned iterable
  163. and adding a custom iterable is a boring task this class can be used for
  164. that::
  165. return ClosingIterator(app(environ, start_response), [cleanup_session,
  166. cleanup_locals])
  167. If there is just one close function it can be passed instead of the list.
  168. A closing iterator is not needed if the application uses response objects
  169. and finishes the processing if the response is started::
  170. try:
  171. return response(environ, start_response)
  172. finally:
  173. cleanup_session()
  174. cleanup_locals()
  175. """
  176. def __init__(
  177. self,
  178. iterable: t.Iterable[bytes],
  179. callbacks: None
  180. | (t.Callable[[], None] | t.Iterable[t.Callable[[], None]]) = None,
  181. ) -> None:
  182. iterator = iter(iterable)
  183. self._next = t.cast(t.Callable[[], bytes], partial(next, iterator))
  184. if callbacks is None:
  185. callbacks = []
  186. elif callable(callbacks):
  187. callbacks = [callbacks]
  188. else:
  189. callbacks = list(callbacks)
  190. iterable_close = getattr(iterable, "close", None)
  191. if iterable_close:
  192. callbacks.insert(0, iterable_close)
  193. self._callbacks = callbacks
  194. def __iter__(self) -> ClosingIterator:
  195. return self
  196. def __next__(self) -> bytes:
  197. return self._next()
  198. def close(self) -> None:
  199. for callback in self._callbacks:
  200. callback()
  201. def wrap_file(
  202. environ: WSGIEnvironment, file: t.IO[bytes], buffer_size: int = 8192
  203. ) -> t.Iterable[bytes]:
  204. """Wraps a file. This uses the WSGI server's file wrapper if available
  205. or otherwise the generic :class:`FileWrapper`.
  206. .. versionadded:: 0.5
  207. If the file wrapper from the WSGI server is used it's important to not
  208. iterate over it from inside the application but to pass it through
  209. unchanged. If you want to pass out a file wrapper inside a response
  210. object you have to set :attr:`Response.direct_passthrough` to `True`.
  211. More information about file wrappers are available in :pep:`333`.
  212. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  213. :param buffer_size: number of bytes for one iteration.
  214. """
  215. return environ.get("wsgi.file_wrapper", FileWrapper)( # type: ignore
  216. file, buffer_size
  217. )
  218. class FileWrapper:
  219. """This class can be used to convert a :class:`file`-like object into
  220. an iterable. It yields `buffer_size` blocks until the file is fully
  221. read.
  222. You should not use this class directly but rather use the
  223. :func:`wrap_file` function that uses the WSGI server's file wrapper
  224. support if it's available.
  225. .. versionadded:: 0.5
  226. If you're using this object together with a :class:`Response` you have
  227. to use the `direct_passthrough` mode.
  228. :param file: a :class:`file`-like object with a :meth:`~file.read` method.
  229. :param buffer_size: number of bytes for one iteration.
  230. """
  231. def __init__(self, file: t.IO[bytes], buffer_size: int = 8192) -> None:
  232. self.file = file
  233. self.buffer_size = buffer_size
  234. def close(self) -> None:
  235. if hasattr(self.file, "close"):
  236. self.file.close()
  237. def seekable(self) -> bool:
  238. if hasattr(self.file, "seekable"):
  239. return self.file.seekable()
  240. if hasattr(self.file, "seek"):
  241. return True
  242. return False
  243. def seek(self, *args: t.Any) -> None:
  244. if hasattr(self.file, "seek"):
  245. self.file.seek(*args)
  246. def tell(self) -> int | None:
  247. if hasattr(self.file, "tell"):
  248. return self.file.tell()
  249. return None
  250. def __iter__(self) -> FileWrapper:
  251. return self
  252. def __next__(self) -> bytes:
  253. data = self.file.read(self.buffer_size)
  254. if data:
  255. return data
  256. raise StopIteration()
  257. class _RangeWrapper:
  258. # private for now, but should we make it public in the future ?
  259. """This class can be used to convert an iterable object into
  260. an iterable that will only yield a piece of the underlying content.
  261. It yields blocks until the underlying stream range is fully read.
  262. The yielded blocks will have a size that can't exceed the original
  263. iterator defined block size, but that can be smaller.
  264. If you're using this object together with a :class:`Response` you have
  265. to use the `direct_passthrough` mode.
  266. :param iterable: an iterable object with a :meth:`__next__` method.
  267. :param start_byte: byte from which read will start.
  268. :param byte_range: how many bytes to read.
  269. """
  270. def __init__(
  271. self,
  272. iterable: t.Iterable[bytes] | t.IO[bytes],
  273. start_byte: int = 0,
  274. byte_range: int | None = None,
  275. ):
  276. self.iterable = iter(iterable)
  277. self.byte_range = byte_range
  278. self.start_byte = start_byte
  279. self.end_byte = None
  280. if byte_range is not None:
  281. self.end_byte = start_byte + byte_range
  282. self.read_length = 0
  283. self.seekable = hasattr(iterable, "seekable") and iterable.seekable()
  284. self.end_reached = False
  285. def __iter__(self) -> _RangeWrapper:
  286. return self
  287. def _next_chunk(self) -> bytes:
  288. try:
  289. chunk = next(self.iterable)
  290. self.read_length += len(chunk)
  291. return chunk
  292. except StopIteration:
  293. self.end_reached = True
  294. raise
  295. def _first_iteration(self) -> tuple[bytes | None, int]:
  296. chunk = None
  297. if self.seekable:
  298. self.iterable.seek(self.start_byte) # type: ignore
  299. self.read_length = self.iterable.tell() # type: ignore
  300. contextual_read_length = self.read_length
  301. else:
  302. while self.read_length <= self.start_byte:
  303. chunk = self._next_chunk()
  304. if chunk is not None:
  305. chunk = chunk[self.start_byte - self.read_length :]
  306. contextual_read_length = self.start_byte
  307. return chunk, contextual_read_length
  308. def _next(self) -> bytes:
  309. if self.end_reached:
  310. raise StopIteration()
  311. chunk = None
  312. contextual_read_length = self.read_length
  313. if self.read_length == 0:
  314. chunk, contextual_read_length = self._first_iteration()
  315. if chunk is None:
  316. chunk = self._next_chunk()
  317. if self.end_byte is not None and self.read_length >= self.end_byte:
  318. self.end_reached = True
  319. return chunk[: self.end_byte - contextual_read_length]
  320. return chunk
  321. def __next__(self) -> bytes:
  322. chunk = self._next()
  323. if chunk:
  324. return chunk
  325. self.end_reached = True
  326. raise StopIteration()
  327. def close(self) -> None:
  328. if hasattr(self.iterable, "close"):
  329. self.iterable.close()
  330. class LimitedStream(io.RawIOBase):
  331. """Wrap a stream so that it doesn't read more than a given limit. This is used to
  332. limit ``wsgi.input`` to the ``Content-Length`` header value or
  333. :attr:`.Request.max_content_length`.
  334. When attempting to read after the limit has been reached, :meth:`on_exhausted` is
  335. called. When the limit is a maximum, this raises :exc:`.RequestEntityTooLarge`.
  336. If reading from the stream returns zero bytes or raises an error,
  337. :meth:`on_disconnect` is called, which raises :exc:`.ClientDisconnected`. When the
  338. limit is a maximum and zero bytes were read, no error is raised, since it may be the
  339. end of the stream.
  340. If the limit is reached before the underlying stream is exhausted (such as a file
  341. that is too large, or an infinite stream), the remaining contents of the stream
  342. cannot be read safely. Depending on how the server handles this, clients may show a
  343. "connection reset" failure instead of seeing the 413 response.
  344. :param stream: The stream to read from. Must be a readable binary IO object.
  345. :param limit: The limit in bytes to not read past. Should be either the
  346. ``Content-Length`` header value or ``request.max_content_length``.
  347. :param is_max: Whether the given ``limit`` is ``request.max_content_length`` instead
  348. of the ``Content-Length`` header value. This changes how exhausted and
  349. disconnect events are handled.
  350. .. versionchanged:: 2.3
  351. Handle ``max_content_length`` differently than ``Content-Length``.
  352. .. versionchanged:: 2.3
  353. Implements ``io.RawIOBase`` rather than ``io.IOBase``.
  354. """
  355. def __init__(self, stream: t.IO[bytes], limit: int, is_max: bool = False) -> None:
  356. self._stream = stream
  357. self._pos = 0
  358. self.limit = limit
  359. self._limit_is_max = is_max
  360. @property
  361. def is_exhausted(self) -> bool:
  362. """Whether the current stream position has reached the limit."""
  363. return self._pos >= self.limit
  364. def on_exhausted(self) -> None:
  365. """Called when attempting to read after the limit has been reached.
  366. The default behavior is to do nothing, unless the limit is a maximum, in which
  367. case it raises :exc:`.RequestEntityTooLarge`.
  368. .. versionchanged:: 2.3
  369. Raises ``RequestEntityTooLarge`` if the limit is a maximum.
  370. .. versionchanged:: 2.3
  371. Any return value is ignored.
  372. """
  373. if self._limit_is_max:
  374. raise RequestEntityTooLarge()
  375. def on_disconnect(self, error: Exception | None = None) -> None:
  376. """Called when an attempted read receives zero bytes before the limit was
  377. reached. This indicates that the client disconnected before sending the full
  378. request body.
  379. The default behavior is to raise :exc:`.ClientDisconnected`, unless the limit is
  380. a maximum and no error was raised.
  381. .. versionchanged:: 2.3
  382. Added the ``error`` parameter. Do nothing if the limit is a maximum and no
  383. error was raised.
  384. .. versionchanged:: 2.3
  385. Any return value is ignored.
  386. """
  387. if not self._limit_is_max or error is not None:
  388. raise ClientDisconnected()
  389. # If the limit is a maximum, then we may have read zero bytes because the
  390. # streaming body is complete. There's no way to distinguish that from the
  391. # client disconnecting early.
  392. def exhaust(self) -> bytes:
  393. """Exhaust the stream by reading until the limit is reached or the client
  394. disconnects, returning the remaining data.
  395. .. versionchanged:: 2.3
  396. Return the remaining data.
  397. .. versionchanged:: 2.2.3
  398. Handle case where wrapped stream returns fewer bytes than requested.
  399. """
  400. if not self.is_exhausted:
  401. return self.readall()
  402. return b""
  403. def readinto(self, b: bytearray) -> int | None: # type: ignore[override]
  404. size = len(b)
  405. remaining = self.limit - self._pos
  406. if remaining <= 0:
  407. self.on_exhausted()
  408. return 0
  409. if hasattr(self._stream, "readinto"):
  410. # Use stream.readinto if it's available.
  411. if size <= remaining:
  412. # The size fits in the remaining limit, use the buffer directly.
  413. try:
  414. out_size: int | None = self._stream.readinto(b)
  415. except (OSError, ValueError) as e:
  416. self.on_disconnect(error=e)
  417. return 0
  418. else:
  419. # Use a temp buffer with the remaining limit as the size.
  420. temp_b = bytearray(remaining)
  421. try:
  422. out_size = self._stream.readinto(temp_b)
  423. except (OSError, ValueError) as e:
  424. self.on_disconnect(error=e)
  425. return 0
  426. if out_size:
  427. b[:out_size] = temp_b
  428. else:
  429. # WSGI requires that stream.read is available.
  430. try:
  431. data = self._stream.read(min(size, remaining))
  432. except (OSError, ValueError) as e:
  433. self.on_disconnect(error=e)
  434. return 0
  435. out_size = len(data)
  436. b[:out_size] = data
  437. if not out_size:
  438. # Read zero bytes from the stream.
  439. self.on_disconnect()
  440. return 0
  441. self._pos += out_size
  442. return out_size
  443. def readall(self) -> bytes:
  444. if self.is_exhausted:
  445. self.on_exhausted()
  446. return b""
  447. out = bytearray()
  448. # The parent implementation uses "while True", which results in an extra read.
  449. while not self.is_exhausted:
  450. data = self.read(1024 * 64)
  451. # Stream may return empty before a max limit is reached.
  452. if not data:
  453. break
  454. out.extend(data)
  455. return bytes(out)
  456. def tell(self) -> int:
  457. """Return the current stream position.
  458. .. versionadded:: 0.9
  459. """
  460. return self._pos
  461. def readable(self) -> bool:
  462. return True