formparser.py 15 KB

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