formparser.py 15 KB

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