formparser.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. from __future__ import annotations
  2. import typing as t
  3. from io import BytesIO
  4. from urllib.parse import parse_qsl
  5. from ._internal import _plain_int
  6. from .datastructures import FileStorage
  7. from .datastructures import Headers
  8. from .datastructures import MultiDict
  9. from .exceptions import RequestEntityTooLarge
  10. from .http import parse_options_header
  11. from .sansio.multipart import Data
  12. from .sansio.multipart import Epilogue
  13. from .sansio.multipart import Field
  14. from .sansio.multipart import File
  15. from .sansio.multipart import MultipartDecoder
  16. from .sansio.multipart import NeedData
  17. from .wsgi import get_content_length
  18. from .wsgi import get_input_stream
  19. # there are some platforms where SpooledTemporaryFile is not available.
  20. # In that case we need to provide a fallback.
  21. try:
  22. from tempfile import SpooledTemporaryFile
  23. except ImportError:
  24. from tempfile import TemporaryFile
  25. SpooledTemporaryFile = None # type: ignore
  26. if t.TYPE_CHECKING:
  27. import typing as te
  28. from _typeshed.wsgi import WSGIEnvironment
  29. t_parse_result = tuple[
  30. t.IO[bytes], MultiDict[str, str], MultiDict[str, FileStorage]
  31. ]
  32. class TStreamFactory(te.Protocol):
  33. def __call__(
  34. self,
  35. total_content_length: int | None,
  36. content_type: str | None,
  37. filename: str | None,
  38. content_length: int | None = None,
  39. ) -> t.IO[bytes]: ...
  40. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  41. def default_stream_factory(
  42. total_content_length: int | None,
  43. content_type: str | None,
  44. filename: str | None,
  45. content_length: int | None = None,
  46. ) -> t.IO[bytes]:
  47. max_size = 1024 * 500
  48. if SpooledTemporaryFile is not None:
  49. return t.cast(t.IO[bytes], SpooledTemporaryFile(max_size=max_size, mode="rb+"))
  50. elif total_content_length is None or total_content_length > max_size:
  51. return t.cast(t.IO[bytes], TemporaryFile("rb+"))
  52. return BytesIO()
  53. def parse_form_data(
  54. environ: WSGIEnvironment,
  55. stream_factory: TStreamFactory | None = None,
  56. max_form_memory_size: int | None = None,
  57. max_content_length: int | None = None,
  58. cls: type[MultiDict[str, t.Any]] | None = None,
  59. silent: bool = True,
  60. *,
  61. max_form_parts: int | None = None,
  62. ) -> t_parse_result:
  63. """Parse the form data in the environ and return it as tuple in the form
  64. ``(stream, form, files)``. You should only call this method if the
  65. transport method is `POST`, `PUT`, or `PATCH`.
  66. If the mimetype of the data transmitted is `multipart/form-data` the
  67. files multidict will be filled with `FileStorage` objects. If the
  68. mimetype is unknown the input stream is wrapped and returned as first
  69. argument, else the stream is empty.
  70. This is a shortcut for the common usage of :class:`FormDataParser`.
  71. :param environ: the WSGI environment to be used for parsing.
  72. :param stream_factory: An optional callable that returns a new read and
  73. writeable file descriptor. This callable works
  74. the same as :meth:`Response._get_file_stream`.
  75. :param max_content_length: If the data is larger than this many bytes, raise
  76. :exc:`.RequestEntityTooLarge`. This is used by :meth:`parse_from_environ`
  77. to set up a limited stream. When using :meth:`parse`, you must get a
  78. limited stream with :func:`.get_input_stream`.
  79. :param max_form_memory_size: If a ``multipart/form-data`` text part is larger
  80. than this many bytes, raise :exc:`~exceptions.RequestEntityTooLarge`.
  81. File parts are written to disk after this size. This is an additional
  82. check, it does not replace using a limited stream and
  83. ``max_content_length``.
  84. :param max_form_parts: If more than this number of ``multipart/form-data``
  85. parts are received, raise :exc:`.RequestEntityTooLarge`. This is an
  86. additional check, it does not replace using a limited stream and
  87. ``max_content_length``.
  88. :param cls: an optional dict class to use. If this is not specified
  89. or `None` the default :class:`MultiDict` is used.
  90. :param silent: If set to False parsing errors will not be caught.
  91. :return: A tuple in the form ``(stream, form, files)``.
  92. .. versionchanged:: 3.1.9
  93. ``max_form_memory_size`` is not applied to
  94. ``application/x-www-form-urlencoded``.
  95. .. versionchanged:: 3.0
  96. The ``charset`` and ``errors`` parameters were removed.
  97. .. versionchanged:: 2.3
  98. Added the ``max_form_parts`` parameter.
  99. .. versionadded:: 0.5.1
  100. Added the ``silent`` parameter.
  101. .. versionadded:: 0.5
  102. Added the ``max_form_memory_size``, ``max_content_length``, and ``cls``
  103. parameters.
  104. """
  105. return FormDataParser(
  106. stream_factory=stream_factory,
  107. max_form_memory_size=max_form_memory_size,
  108. max_content_length=max_content_length,
  109. max_form_parts=max_form_parts,
  110. silent=silent,
  111. cls=cls,
  112. ).parse_from_environ(environ)
  113. class FormDataParser:
  114. """This class implements parsing of form data for Werkzeug. By itself
  115. it can parse multipart and url encoded form data. It can be subclassed
  116. and extended but for most mimetypes it is a better idea to use the
  117. untouched stream and expose it as separate attributes on a request
  118. object.
  119. :param stream_factory: An optional callable that returns a new read and
  120. writeable file descriptor. This callable works
  121. the same as :meth:`Response._get_file_stream`.
  122. :param max_content_length: If the data is larger than this many bytes, raise
  123. :exc:`.RequestEntityTooLarge`. This is used by :meth:`parse_from_environ`
  124. to set up a limited stream. When using :meth:`parse`, you must get a
  125. limited stream with :func:`.get_input_stream`.
  126. :param max_form_memory_size: If a ``multipart/form-data`` text part is larger
  127. than this many bytes, raise :exc:`~exceptions.RequestEntityTooLarge`.
  128. File parts are written to disk after this size. This is an additional
  129. check, it does not replace using a limited stream and
  130. ``max_content_length``.
  131. :param max_form_parts: If more than this number of ``multipart/form-data``
  132. parts are received, raise :exc:`.RequestEntityTooLarge`. This is an
  133. additional check, it does not replace using a limited stream and
  134. ``max_content_length``.
  135. :param cls: an optional dict class to use. If this is not specified
  136. or `None` the default :class:`MultiDict` is used.
  137. :param silent: If set to False parsing errors will not be caught.
  138. .. versionchanged:: 3.0
  139. The ``charset`` and ``errors`` parameters were removed.
  140. .. versionchanged:: 3.0
  141. The ``parse_functions`` attribute and ``get_parse_func`` methods were removed.
  142. .. versionchanged:: 2.2.3
  143. Added the ``max_form_parts`` parameter.
  144. .. versionadded:: 0.8
  145. """
  146. def __init__(
  147. self,
  148. stream_factory: TStreamFactory | None = None,
  149. max_form_memory_size: int | None = None,
  150. max_content_length: int | None = None,
  151. cls: type[MultiDict[str, t.Any]] | None = None,
  152. silent: bool = True,
  153. *,
  154. max_form_parts: int | None = None,
  155. ) -> None:
  156. if stream_factory is None:
  157. stream_factory = default_stream_factory
  158. self.stream_factory = stream_factory
  159. self.max_content_length = max_content_length
  160. self.max_form_memory_size = max_form_memory_size
  161. self.max_form_parts = max_form_parts
  162. if cls is None:
  163. cls = t.cast("type[MultiDict[str, t.Any]]", MultiDict)
  164. self.cls = cls
  165. self.silent = silent
  166. def parse_from_environ(self, environ: WSGIEnvironment) -> t_parse_result:
  167. """Parses the information from the environment as form data.
  168. :param environ: the WSGI environment to be used for parsing.
  169. :return: A tuple in the form ``(stream, form, files)``.
  170. """
  171. stream = get_input_stream(environ, max_content_length=self.max_content_length)
  172. content_length = get_content_length(environ)
  173. mimetype, options = parse_options_header(environ.get("CONTENT_TYPE"))
  174. return self.parse(
  175. stream,
  176. content_length=content_length,
  177. mimetype=mimetype,
  178. options=options,
  179. )
  180. def parse(
  181. self,
  182. stream: t.IO[bytes],
  183. mimetype: str,
  184. content_length: int | None,
  185. options: dict[str, str] | None = None,
  186. ) -> t_parse_result:
  187. """Parses the information from the given stream, mimetype,
  188. content length and mimetype parameters.
  189. :param stream: A limited input stream, from :meth:`.get_input_stream`.
  190. :param mimetype: The mimetype used to choose how to parse the form.
  191. ``multipart/form-data`` and ``application/x-www-form-urlencoded``
  192. are supported.
  193. :param content_length: the content length of the incoming data
  194. :param options: optional mimetype parameters (used for
  195. the multipart boundary for instance)
  196. :return: A tuple in the form ``(stream, form, files)``.
  197. .. versionchanged:: 3.0
  198. The invalid ``application/x-url-encoded`` content type is not
  199. treated as ``application/x-www-form-urlencoded``.
  200. """
  201. if mimetype == "multipart/form-data":
  202. parse_func = self._parse_multipart
  203. elif mimetype == "application/x-www-form-urlencoded":
  204. parse_func = self._parse_urlencoded
  205. else:
  206. return stream, self.cls(), self.cls()
  207. if options is None:
  208. options = {}
  209. try:
  210. return parse_func(stream, mimetype, content_length, options)
  211. except ValueError:
  212. if not self.silent:
  213. raise
  214. return stream, self.cls(), self.cls()
  215. def _parse_multipart(
  216. self,
  217. stream: t.IO[bytes],
  218. mimetype: str,
  219. content_length: int | None,
  220. options: dict[str, str],
  221. ) -> t_parse_result:
  222. parser = MultiPartParser(
  223. stream_factory=self.stream_factory,
  224. max_form_memory_size=self.max_form_memory_size,
  225. max_form_parts=self.max_form_parts,
  226. cls=self.cls,
  227. )
  228. boundary = options.get("boundary", "").encode("ascii")
  229. if not boundary:
  230. raise ValueError("Missing boundary")
  231. form, files = parser.parse(stream, boundary, content_length)
  232. return stream, form, files
  233. def _parse_urlencoded(
  234. self,
  235. stream: t.IO[bytes],
  236. mimetype: str,
  237. content_length: int | None,
  238. options: dict[str, str],
  239. ) -> t_parse_result:
  240. # The stream must already be limited to max_content_length.
  241. # max_form_memory_size can't apply, since the entire stream is read at
  242. # once instead of incrementally parsed.
  243. # max_form_parts could be applied here, but doesn't impose a useful
  244. # limit given the previous points and because the parser is much simpler
  245. # and faster already.
  246. items = parse_qsl(
  247. stream.read().decode(),
  248. keep_blank_values=True,
  249. errors="werkzeug.url_quote",
  250. )
  251. return stream, self.cls(items), self.cls()
  252. class MultiPartParser:
  253. def __init__(
  254. self,
  255. stream_factory: TStreamFactory | None = None,
  256. max_form_memory_size: int | None = None,
  257. cls: type[MultiDict[str, t.Any]] | None = None,
  258. buffer_size: int = 64 * 1024,
  259. max_form_parts: int | None = None,
  260. ) -> None:
  261. self.max_form_memory_size = max_form_memory_size
  262. self.max_form_parts = max_form_parts
  263. if stream_factory is None:
  264. stream_factory = default_stream_factory
  265. self.stream_factory = stream_factory
  266. if cls is None:
  267. cls = t.cast("type[MultiDict[str, t.Any]]", MultiDict)
  268. self.cls = cls
  269. self.buffer_size = buffer_size
  270. def fail(self, message: str) -> te.NoReturn:
  271. raise ValueError(message)
  272. def get_part_charset(self, headers: Headers) -> str:
  273. # Figure out input charset for current part
  274. content_type = headers.get("content-type")
  275. if content_type:
  276. parameters = parse_options_header(content_type)[1]
  277. ct_charset = parameters.get("charset", "").lower()
  278. # A safe list of encodings. Modern clients should only send ASCII or UTF-8.
  279. # This list will not be extended further.
  280. if ct_charset in {"ascii", "us-ascii", "utf-8", "iso-8859-1"}:
  281. return ct_charset
  282. return "utf-8"
  283. def start_file_streaming(
  284. self, event: File, total_content_length: int | None
  285. ) -> t.IO[bytes]:
  286. content_type = event.headers.get("content-type")
  287. try:
  288. content_length = _plain_int(event.headers["content-length"])
  289. except (KeyError, ValueError):
  290. content_length = 0
  291. container = self.stream_factory(
  292. total_content_length=total_content_length,
  293. filename=event.filename,
  294. content_type=content_type,
  295. content_length=content_length,
  296. )
  297. return container
  298. def parse(
  299. self, stream: t.IO[bytes], boundary: bytes, content_length: int | None
  300. ) -> tuple[MultiDict[str, str], MultiDict[str, FileStorage]]:
  301. current_part: Field | File
  302. field_size: int | None = None
  303. container: t.IO[bytes] | list[bytes]
  304. _write: t.Callable[[bytes], t.Any]
  305. parser = MultipartDecoder(
  306. boundary,
  307. max_form_memory_size=self.max_form_memory_size,
  308. max_parts=self.max_form_parts,
  309. )
  310. fields = []
  311. files = []
  312. for data in _chunk_iter(stream.read, self.buffer_size):
  313. parser.receive_data(data)
  314. event = parser.next_event()
  315. while not isinstance(event, (Epilogue, NeedData)):
  316. if isinstance(event, Field):
  317. current_part = event
  318. field_size = 0
  319. container = []
  320. _write = container.append
  321. elif isinstance(event, File):
  322. current_part = event
  323. field_size = None
  324. container = self.start_file_streaming(event, content_length)
  325. _write = container.write
  326. elif isinstance(event, Data):
  327. if self.max_form_memory_size is not None and field_size is not None:
  328. # Ensure that accumulated data events do not exceed limit.
  329. # Also checked within single event in MultipartDecoder.
  330. field_size += len(event.data)
  331. if field_size > self.max_form_memory_size:
  332. raise RequestEntityTooLarge()
  333. _write(event.data)
  334. if not event.more_data:
  335. if isinstance(current_part, Field):
  336. value = b"".join(container).decode(
  337. self.get_part_charset(current_part.headers), "replace"
  338. )
  339. fields.append((current_part.name, value))
  340. else:
  341. container = t.cast(t.IO[bytes], container)
  342. container.seek(0)
  343. files.append(
  344. (
  345. current_part.name,
  346. FileStorage(
  347. container,
  348. current_part.filename,
  349. current_part.name,
  350. headers=current_part.headers,
  351. ),
  352. )
  353. )
  354. event = parser.next_event()
  355. return self.cls(fields), self.cls(files)
  356. def _chunk_iter(read: t.Callable[[int], bytes], size: int) -> t.Iterator[bytes | None]:
  357. """Read data in chunks for multipart/form-data parsing. Stop if no data is read.
  358. Yield ``None`` at the end to signal end of parsing.
  359. """
  360. while True:
  361. data = read(size)
  362. if not data:
  363. break
  364. yield data
  365. yield None