wsgi.py 22 KB

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