formparser.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import typing as t
  2. import warnings
  3. from functools import update_wrapper
  4. from io import BytesIO
  5. from itertools import chain
  6. from typing import Union
  7. from . import exceptions
  8. from ._internal import _to_str
  9. from .datastructures import FileStorage
  10. from .datastructures import Headers
  11. from .datastructures import MultiDict
  12. from .http import parse_options_header
  13. from .sansio.multipart import Data
  14. from .sansio.multipart import Epilogue
  15. from .sansio.multipart import Field
  16. from .sansio.multipart import File
  17. from .sansio.multipart import MultipartDecoder
  18. from .sansio.multipart import NeedData
  19. from .urls import url_decode_stream
  20. from .wsgi import _make_chunk_iter
  21. from .wsgi import get_content_length
  22. from .wsgi import get_input_stream
  23. # there are some platforms where SpooledTemporaryFile is not available.
  24. # In that case we need to provide a fallback.
  25. try:
  26. from tempfile import SpooledTemporaryFile
  27. except ImportError:
  28. from tempfile import TemporaryFile
  29. SpooledTemporaryFile = None # type: ignore
  30. if t.TYPE_CHECKING:
  31. import typing as te
  32. from _typeshed.wsgi import WSGIEnvironment
  33. t_parse_result = t.Tuple[t.IO[bytes], MultiDict, MultiDict]
  34. class TStreamFactory(te.Protocol):
  35. def __call__(
  36. self,
  37. total_content_length: t.Optional[int],
  38. content_type: t.Optional[str],
  39. filename: t.Optional[str],
  40. content_length: t.Optional[int] = None,
  41. ) -> t.IO[bytes]:
  42. ...
  43. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  44. def _exhaust(stream: t.IO[bytes]) -> None:
  45. bts = stream.read(64 * 1024)
  46. while bts:
  47. bts = stream.read(64 * 1024)
  48. def default_stream_factory(
  49. total_content_length: t.Optional[int],
  50. content_type: t.Optional[str],
  51. filename: t.Optional[str],
  52. content_length: t.Optional[int] = None,
  53. ) -> t.IO[bytes]:
  54. max_size = 1024 * 500
  55. if SpooledTemporaryFile is not None:
  56. return t.cast(t.IO[bytes], SpooledTemporaryFile(max_size=max_size, mode="rb+"))
  57. elif total_content_length is None or total_content_length > max_size:
  58. return t.cast(t.IO[bytes], TemporaryFile("rb+"))
  59. return BytesIO()
  60. def parse_form_data(
  61. environ: "WSGIEnvironment",
  62. stream_factory: t.Optional["TStreamFactory"] = None,
  63. charset: str = "utf-8",
  64. errors: str = "replace",
  65. max_form_memory_size: t.Optional[int] = None,
  66. max_content_length: t.Optional[int] = None,
  67. cls: t.Optional[t.Type[MultiDict]] = None,
  68. silent: bool = True,
  69. ) -> "t_parse_result":
  70. """Parse the form data in the environ and return it as tuple in the form
  71. ``(stream, form, files)``. You should only call this method if the
  72. transport method is `POST`, `PUT`, or `PATCH`.
  73. If the mimetype of the data transmitted is `multipart/form-data` the
  74. files multidict will be filled with `FileStorage` objects. If the
  75. mimetype is unknown the input stream is wrapped and returned as first
  76. argument, else the stream is empty.
  77. This is a shortcut for the common usage of :class:`FormDataParser`.
  78. Have a look at :doc:`/request_data` for more details.
  79. .. versionadded:: 0.5
  80. The `max_form_memory_size`, `max_content_length` and
  81. `cls` parameters were added.
  82. .. versionadded:: 0.5.1
  83. The optional `silent` flag was added.
  84. :param environ: the WSGI environment to be used for parsing.
  85. :param stream_factory: An optional callable that returns a new read and
  86. writeable file descriptor. This callable works
  87. the same as :meth:`Response._get_file_stream`.
  88. :param charset: The character set for URL and url encoded form data.
  89. :param errors: The encoding error behavior.
  90. :param max_form_memory_size: the maximum number of bytes to be accepted for
  91. in-memory stored form data. If the data
  92. exceeds the value specified an
  93. :exc:`~exceptions.RequestEntityTooLarge`
  94. exception is raised.
  95. :param max_content_length: If this is provided and the transmitted data
  96. is longer than this value an
  97. :exc:`~exceptions.RequestEntityTooLarge`
  98. exception is raised.
  99. :param cls: an optional dict class to use. If this is not specified
  100. or `None` the default :class:`MultiDict` is used.
  101. :param silent: If set to False parsing errors will not be caught.
  102. :return: A tuple in the form ``(stream, form, files)``.
  103. """
  104. return FormDataParser(
  105. stream_factory,
  106. charset,
  107. errors,
  108. max_form_memory_size,
  109. max_content_length,
  110. cls,
  111. silent,
  112. ).parse_from_environ(environ)
  113. def exhaust_stream(f: F) -> F:
  114. """Helper decorator for methods that exhausts the stream on return."""
  115. def wrapper(self, stream, *args, **kwargs): # type: ignore
  116. try:
  117. return f(self, stream, *args, **kwargs)
  118. finally:
  119. exhaust = getattr(stream, "exhaust", None)
  120. if exhaust is not None:
  121. exhaust()
  122. else:
  123. while True:
  124. chunk = stream.read(1024 * 64)
  125. if not chunk:
  126. break
  127. return update_wrapper(t.cast(F, wrapper), f)
  128. class FormDataParser:
  129. """This class implements parsing of form data for Werkzeug. By itself
  130. it can parse multipart and url encoded form data. It can be subclassed
  131. and extended but for most mimetypes it is a better idea to use the
  132. untouched stream and expose it as separate attributes on a request
  133. object.
  134. .. versionadded:: 0.8
  135. :param stream_factory: An optional callable that returns a new read and
  136. writeable file descriptor. This callable works
  137. the same as :meth:`Response._get_file_stream`.
  138. :param charset: The character set for URL and url encoded form data.
  139. :param errors: The encoding error behavior.
  140. :param max_form_memory_size: the maximum number of bytes to be accepted for
  141. in-memory stored form data. If the data
  142. exceeds the value specified an
  143. :exc:`~exceptions.RequestEntityTooLarge`
  144. exception is raised.
  145. :param max_content_length: If this is provided and the transmitted data
  146. is longer than this value an
  147. :exc:`~exceptions.RequestEntityTooLarge`
  148. exception is raised.
  149. :param cls: an optional dict class to use. If this is not specified
  150. or `None` the default :class:`MultiDict` is used.
  151. :param silent: If set to False parsing errors will not be caught.
  152. """
  153. def __init__(
  154. self,
  155. stream_factory: t.Optional["TStreamFactory"] = None,
  156. charset: str = "utf-8",
  157. errors: str = "replace",
  158. max_form_memory_size: t.Optional[int] = None,
  159. max_content_length: t.Optional[int] = None,
  160. cls: t.Optional[t.Type[MultiDict]] = None,
  161. silent: bool = True,
  162. ) -> None:
  163. if stream_factory is None:
  164. stream_factory = default_stream_factory
  165. self.stream_factory = stream_factory
  166. self.charset = charset
  167. self.errors = errors
  168. self.max_form_memory_size = max_form_memory_size
  169. self.max_content_length = max_content_length
  170. if cls is None:
  171. cls = MultiDict
  172. self.cls = cls
  173. self.silent = silent
  174. def get_parse_func(
  175. self, mimetype: str, options: t.Dict[str, str]
  176. ) -> t.Optional[
  177. t.Callable[
  178. ["FormDataParser", t.IO[bytes], str, t.Optional[int], t.Dict[str, str]],
  179. "t_parse_result",
  180. ]
  181. ]:
  182. return self.parse_functions.get(mimetype)
  183. def parse_from_environ(self, environ: "WSGIEnvironment") -> "t_parse_result":
  184. """Parses the information from the environment as form data.
  185. :param environ: the WSGI environment to be used for parsing.
  186. :return: A tuple in the form ``(stream, form, files)``.
  187. """
  188. content_type = environ.get("CONTENT_TYPE", "")
  189. content_length = get_content_length(environ)
  190. mimetype, options = parse_options_header(content_type)
  191. return self.parse(get_input_stream(environ), mimetype, content_length, options)
  192. def parse(
  193. self,
  194. stream: t.IO[bytes],
  195. mimetype: str,
  196. content_length: t.Optional[int],
  197. options: t.Optional[t.Dict[str, str]] = None,
  198. ) -> "t_parse_result":
  199. """Parses the information from the given stream, mimetype,
  200. content length and mimetype parameters.
  201. :param stream: an input stream
  202. :param mimetype: the mimetype of the data
  203. :param content_length: the content length of the incoming data
  204. :param options: optional mimetype parameters (used for
  205. the multipart boundary for instance)
  206. :return: A tuple in the form ``(stream, form, files)``.
  207. """
  208. if (
  209. self.max_content_length is not None
  210. and content_length is not None
  211. and content_length > self.max_content_length
  212. ):
  213. # if the input stream is not exhausted, firefox reports Connection Reset
  214. _exhaust(stream)
  215. raise exceptions.RequestEntityTooLarge()
  216. if options is None:
  217. options = {}
  218. parse_func = self.get_parse_func(mimetype, options)
  219. if parse_func is not None:
  220. try:
  221. return parse_func(self, stream, mimetype, content_length, options)
  222. except ValueError:
  223. if not self.silent:
  224. raise
  225. return stream, self.cls(), self.cls()
  226. @exhaust_stream
  227. def _parse_multipart(
  228. self,
  229. stream: t.IO[bytes],
  230. mimetype: str,
  231. content_length: t.Optional[int],
  232. options: t.Dict[str, str],
  233. ) -> "t_parse_result":
  234. parser = MultiPartParser(
  235. self.stream_factory,
  236. self.charset,
  237. self.errors,
  238. max_form_memory_size=self.max_form_memory_size,
  239. cls=self.cls,
  240. )
  241. boundary = options.get("boundary", "").encode("ascii")
  242. if not boundary:
  243. raise ValueError("Missing boundary")
  244. form, files = parser.parse(stream, boundary, content_length)
  245. return stream, form, files
  246. @exhaust_stream
  247. def _parse_urlencoded(
  248. self,
  249. stream: t.IO[bytes],
  250. mimetype: str,
  251. content_length: t.Optional[int],
  252. options: t.Dict[str, str],
  253. ) -> "t_parse_result":
  254. if (
  255. self.max_form_memory_size is not None
  256. and content_length is not None
  257. and content_length > self.max_form_memory_size
  258. ):
  259. # if the input stream is not exhausted, firefox reports Connection Reset
  260. _exhaust(stream)
  261. raise exceptions.RequestEntityTooLarge()
  262. form = url_decode_stream(stream, self.charset, errors=self.errors, cls=self.cls)
  263. return stream, form, self.cls()
  264. #: mapping of mimetypes to parsing functions
  265. parse_functions: t.Dict[
  266. str,
  267. t.Callable[
  268. ["FormDataParser", t.IO[bytes], str, t.Optional[int], t.Dict[str, str]],
  269. "t_parse_result",
  270. ],
  271. ] = {
  272. "multipart/form-data": _parse_multipart,
  273. "application/x-www-form-urlencoded": _parse_urlencoded,
  274. "application/x-url-encoded": _parse_urlencoded,
  275. }
  276. def _line_parse(line: str) -> t.Tuple[str, bool]:
  277. """Removes line ending characters and returns a tuple (`stripped_line`,
  278. `is_terminated`).
  279. """
  280. if line[-2:] == "\r\n":
  281. return line[:-2], True
  282. elif line[-1:] in {"\r", "\n"}:
  283. return line[:-1], True
  284. return line, False
  285. def parse_multipart_headers(iterable: t.Iterable[bytes]) -> Headers:
  286. """Parses multipart headers from an iterable that yields lines (including
  287. the trailing newline symbol). The iterable has to be newline terminated.
  288. The iterable will stop at the line where the headers ended so it can be
  289. further consumed.
  290. :param iterable: iterable of strings that are newline terminated
  291. """
  292. warnings.warn(
  293. "'parse_multipart_headers' is deprecated and will be removed in"
  294. " Werkzeug 2.1.",
  295. DeprecationWarning,
  296. stacklevel=2,
  297. )
  298. result: t.List[t.Tuple[str, str]] = []
  299. for b_line in iterable:
  300. line = _to_str(b_line)
  301. line, line_terminated = _line_parse(line)
  302. if not line_terminated:
  303. raise ValueError("unexpected end of line in multipart header")
  304. if not line:
  305. break
  306. elif line[0] in " \t" and result:
  307. key, value = result[-1]
  308. result[-1] = (key, f"{value}\n {line[1:]}")
  309. else:
  310. parts = line.split(":", 1)
  311. if len(parts) == 2:
  312. result.append((parts[0].strip(), parts[1].strip()))
  313. # we link the list to the headers, no need to create a copy, the
  314. # list was not shared anyways.
  315. return Headers(result)
  316. class MultiPartParser:
  317. def __init__(
  318. self,
  319. stream_factory: t.Optional["TStreamFactory"] = None,
  320. charset: str = "utf-8",
  321. errors: str = "replace",
  322. max_form_memory_size: t.Optional[int] = None,
  323. cls: t.Optional[t.Type[MultiDict]] = None,
  324. buffer_size: int = 64 * 1024,
  325. ) -> None:
  326. self.charset = charset
  327. self.errors = errors
  328. self.max_form_memory_size = max_form_memory_size
  329. if stream_factory is None:
  330. stream_factory = default_stream_factory
  331. self.stream_factory = stream_factory
  332. if cls is None:
  333. cls = MultiDict
  334. self.cls = cls
  335. self.buffer_size = buffer_size
  336. def fail(self, message: str) -> "te.NoReturn":
  337. raise ValueError(message)
  338. def get_part_charset(self, headers: Headers) -> str:
  339. # Figure out input charset for current part
  340. content_type = headers.get("content-type")
  341. if content_type:
  342. mimetype, ct_params = parse_options_header(content_type)
  343. return ct_params.get("charset", self.charset)
  344. return self.charset
  345. def start_file_streaming(
  346. self, event: File, total_content_length: t.Optional[int]
  347. ) -> t.IO[bytes]:
  348. content_type = event.headers.get("content-type")
  349. try:
  350. content_length = int(event.headers["content-length"])
  351. except (KeyError, ValueError):
  352. content_length = 0
  353. container = self.stream_factory(
  354. total_content_length=total_content_length,
  355. filename=event.filename,
  356. content_type=content_type,
  357. content_length=content_length,
  358. )
  359. return container
  360. def parse(
  361. self, stream: t.IO[bytes], boundary: bytes, content_length: t.Optional[int]
  362. ) -> t.Tuple[MultiDict, MultiDict]:
  363. container: t.Union[t.IO[bytes], t.List[bytes]]
  364. _write: t.Callable[[bytes], t.Any]
  365. iterator = chain(
  366. _make_chunk_iter(
  367. stream,
  368. limit=content_length,
  369. buffer_size=self.buffer_size,
  370. ),
  371. [None],
  372. )
  373. parser = MultipartDecoder(boundary, self.max_form_memory_size)
  374. fields = []
  375. files = []
  376. current_part: Union[Field, File]
  377. for data in iterator:
  378. parser.receive_data(data)
  379. event = parser.next_event()
  380. while not isinstance(event, (Epilogue, NeedData)):
  381. if isinstance(event, Field):
  382. current_part = event
  383. container = []
  384. _write = container.append
  385. elif isinstance(event, File):
  386. current_part = event
  387. container = self.start_file_streaming(event, content_length)
  388. _write = container.write
  389. elif isinstance(event, Data):
  390. _write(event.data)
  391. if not event.more_data:
  392. if isinstance(current_part, Field):
  393. value = b"".join(container).decode(
  394. self.get_part_charset(current_part.headers), self.errors
  395. )
  396. fields.append((current_part.name, value))
  397. else:
  398. container = t.cast(t.IO[bytes], container)
  399. container.seek(0)
  400. files.append(
  401. (
  402. current_part.name,
  403. FileStorage(
  404. container,
  405. current_part.filename,
  406. current_part.name,
  407. headers=current_part.headers,
  408. ),
  409. )
  410. )
  411. event = parser.next_event()
  412. return self.cls(fields), self.cls(files)