formparser.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.formparser
  4. ~~~~~~~~~~~~~~~~~~~
  5. This module implements the form parsing. It supports url-encoded forms
  6. as well as non-nested multipart uploads.
  7. :copyright: 2007 Pallets
  8. :license: BSD-3-Clause
  9. """
  10. import codecs
  11. import re
  12. from functools import update_wrapper
  13. from itertools import chain
  14. from itertools import repeat
  15. from itertools import tee
  16. from . import exceptions
  17. from ._compat import BytesIO
  18. from ._compat import text_type
  19. from ._compat import to_native
  20. from .datastructures import FileStorage
  21. from .datastructures import Headers
  22. from .datastructures import MultiDict
  23. from .http import parse_options_header
  24. from .urls import url_decode_stream
  25. from .wsgi import get_content_length
  26. from .wsgi import get_input_stream
  27. from .wsgi import make_line_iter
  28. # there are some platforms where SpooledTemporaryFile is not available.
  29. # In that case we need to provide a fallback.
  30. try:
  31. from tempfile import SpooledTemporaryFile
  32. except ImportError:
  33. from tempfile import TemporaryFile
  34. SpooledTemporaryFile = None
  35. #: an iterator that yields empty strings
  36. _empty_string_iter = repeat("")
  37. #: a regular expression for multipart boundaries
  38. _multipart_boundary_re = re.compile("^[ -~]{0,200}[!-~]$")
  39. #: supported http encodings that are also available in python we support
  40. #: for multipart messages.
  41. _supported_multipart_encodings = frozenset(["base64", "quoted-printable"])
  42. def default_stream_factory(
  43. total_content_length, filename, content_type, content_length=None
  44. ):
  45. """The stream factory that is used per default."""
  46. max_size = 1024 * 500
  47. if SpooledTemporaryFile is not None:
  48. return SpooledTemporaryFile(max_size=max_size, mode="wb+")
  49. if total_content_length is None or total_content_length > max_size:
  50. return TemporaryFile("wb+")
  51. return BytesIO()
  52. def parse_form_data(
  53. environ,
  54. stream_factory=None,
  55. charset="utf-8",
  56. errors="replace",
  57. max_form_memory_size=None,
  58. max_content_length=None,
  59. cls=None,
  60. silent=True,
  61. ):
  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. Have a look at :ref:`dealing-with-request-data` for more details.
  71. .. versionadded:: 0.5
  72. The `max_form_memory_size`, `max_content_length` and
  73. `cls` parameters were added.
  74. .. versionadded:: 0.5.1
  75. The optional `silent` flag was added.
  76. :param environ: the WSGI environment to be used for parsing.
  77. :param stream_factory: An optional callable that returns a new read and
  78. writeable file descriptor. This callable works
  79. the same as :meth:`~BaseResponse._get_file_stream`.
  80. :param charset: The character set for URL and url encoded form data.
  81. :param errors: The encoding error behavior.
  82. :param max_form_memory_size: the maximum number of bytes to be accepted for
  83. in-memory stored form data. If the data
  84. exceeds the value specified an
  85. :exc:`~exceptions.RequestEntityTooLarge`
  86. exception is raised.
  87. :param max_content_length: If this is provided and the transmitted data
  88. is longer than this value an
  89. :exc:`~exceptions.RequestEntityTooLarge`
  90. exception is raised.
  91. :param cls: an optional dict class to use. If this is not specified
  92. or `None` the default :class:`MultiDict` is used.
  93. :param silent: If set to False parsing errors will not be caught.
  94. :return: A tuple in the form ``(stream, form, files)``.
  95. """
  96. return FormDataParser(
  97. stream_factory,
  98. charset,
  99. errors,
  100. max_form_memory_size,
  101. max_content_length,
  102. cls,
  103. silent,
  104. ).parse_from_environ(environ)
  105. def exhaust_stream(f):
  106. """Helper decorator for methods that exhausts the stream on return."""
  107. def wrapper(self, stream, *args, **kwargs):
  108. try:
  109. return f(self, stream, *args, **kwargs)
  110. finally:
  111. exhaust = getattr(stream, "exhaust", None)
  112. if exhaust is not None:
  113. exhaust()
  114. else:
  115. while 1:
  116. chunk = stream.read(1024 * 64)
  117. if not chunk:
  118. break
  119. return update_wrapper(wrapper, f)
  120. class FormDataParser(object):
  121. """This class implements parsing of form data for Werkzeug. By itself
  122. it can parse multipart and url encoded form data. It can be subclassed
  123. and extended but for most mimetypes it is a better idea to use the
  124. untouched stream and expose it as separate attributes on a request
  125. object.
  126. .. versionadded:: 0.8
  127. :param stream_factory: An optional callable that returns a new read and
  128. writeable file descriptor. This callable works
  129. the same as :meth:`~BaseResponse._get_file_stream`.
  130. :param charset: The character set for URL and url encoded form data.
  131. :param errors: The encoding error behavior.
  132. :param max_form_memory_size: the maximum number of bytes to be accepted for
  133. in-memory stored form data. If the data
  134. exceeds the value specified an
  135. :exc:`~exceptions.RequestEntityTooLarge`
  136. exception is raised.
  137. :param max_content_length: If this is provided and the transmitted data
  138. is longer than this value an
  139. :exc:`~exceptions.RequestEntityTooLarge`
  140. exception is raised.
  141. :param cls: an optional dict class to use. If this is not specified
  142. or `None` the default :class:`MultiDict` is used.
  143. :param silent: If set to False parsing errors will not be caught.
  144. """
  145. def __init__(
  146. self,
  147. stream_factory=None,
  148. charset="utf-8",
  149. errors="replace",
  150. max_form_memory_size=None,
  151. max_content_length=None,
  152. cls=None,
  153. silent=True,
  154. ):
  155. if stream_factory is None:
  156. stream_factory = default_stream_factory
  157. self.stream_factory = stream_factory
  158. self.charset = charset
  159. self.errors = errors
  160. self.max_form_memory_size = max_form_memory_size
  161. self.max_content_length = max_content_length
  162. if cls is None:
  163. cls = MultiDict
  164. self.cls = cls
  165. self.silent = silent
  166. def get_parse_func(self, mimetype, options):
  167. return self.parse_functions.get(mimetype)
  168. def parse_from_environ(self, environ):
  169. """Parses the information from the environment as form data.
  170. :param environ: the WSGI environment to be used for parsing.
  171. :return: A tuple in the form ``(stream, form, files)``.
  172. """
  173. content_type = environ.get("CONTENT_TYPE", "")
  174. content_length = get_content_length(environ)
  175. mimetype, options = parse_options_header(content_type)
  176. return self.parse(get_input_stream(environ), mimetype, content_length, options)
  177. def parse(self, stream, mimetype, content_length, options=None):
  178. """Parses the information from the given stream, mimetype,
  179. content length and mimetype parameters.
  180. :param stream: an input stream
  181. :param mimetype: the mimetype of the data
  182. :param content_length: the content length of the incoming data
  183. :param options: optional mimetype parameters (used for
  184. the multipart boundary for instance)
  185. :return: A tuple in the form ``(stream, form, files)``.
  186. """
  187. if (
  188. self.max_content_length is not None
  189. and content_length is not None
  190. and content_length > self.max_content_length
  191. ):
  192. raise exceptions.RequestEntityTooLarge()
  193. if options is None:
  194. options = {}
  195. parse_func = self.get_parse_func(mimetype, options)
  196. if parse_func is not None:
  197. try:
  198. return parse_func(self, stream, mimetype, content_length, options)
  199. except ValueError:
  200. if not self.silent:
  201. raise
  202. return stream, self.cls(), self.cls()
  203. @exhaust_stream
  204. def _parse_multipart(self, stream, mimetype, content_length, options):
  205. parser = MultiPartParser(
  206. self.stream_factory,
  207. self.charset,
  208. self.errors,
  209. max_form_memory_size=self.max_form_memory_size,
  210. cls=self.cls,
  211. )
  212. boundary = options.get("boundary")
  213. if boundary is None:
  214. raise ValueError("Missing boundary")
  215. if isinstance(boundary, text_type):
  216. boundary = boundary.encode("ascii")
  217. form, files = parser.parse(stream, boundary, content_length)
  218. return stream, form, files
  219. @exhaust_stream
  220. def _parse_urlencoded(self, stream, mimetype, content_length, options):
  221. if (
  222. self.max_form_memory_size is not None
  223. and content_length is not None
  224. and content_length > self.max_form_memory_size
  225. ):
  226. raise exceptions.RequestEntityTooLarge()
  227. form = url_decode_stream(stream, self.charset, errors=self.errors, cls=self.cls)
  228. return stream, form, self.cls()
  229. #: mapping of mimetypes to parsing functions
  230. parse_functions = {
  231. "multipart/form-data": _parse_multipart,
  232. "application/x-www-form-urlencoded": _parse_urlencoded,
  233. "application/x-url-encoded": _parse_urlencoded,
  234. }
  235. def is_valid_multipart_boundary(boundary):
  236. """Checks if the string given is a valid multipart boundary."""
  237. return _multipart_boundary_re.match(boundary) is not None
  238. def _line_parse(line):
  239. """Removes line ending characters and returns a tuple (`stripped_line`,
  240. `is_terminated`).
  241. """
  242. if line[-2:] in ["\r\n", b"\r\n"]:
  243. return line[:-2], True
  244. elif line[-1:] in ["\r", "\n", b"\r", b"\n"]:
  245. return line[:-1], True
  246. return line, False
  247. def parse_multipart_headers(iterable):
  248. """Parses multipart headers from an iterable that yields lines (including
  249. the trailing newline symbol). The iterable has to be newline terminated.
  250. The iterable will stop at the line where the headers ended so it can be
  251. further consumed.
  252. :param iterable: iterable of strings that are newline terminated
  253. """
  254. result = []
  255. for line in iterable:
  256. line = to_native(line)
  257. line, line_terminated = _line_parse(line)
  258. if not line_terminated:
  259. raise ValueError("unexpected end of line in multipart header")
  260. if not line:
  261. break
  262. elif line[0] in " \t" and result:
  263. key, value = result[-1]
  264. result[-1] = (key, value + "\n " + line[1:])
  265. else:
  266. parts = line.split(":", 1)
  267. if len(parts) == 2:
  268. result.append((parts[0].strip(), parts[1].strip()))
  269. # we link the list to the headers, no need to create a copy, the
  270. # list was not shared anyways.
  271. return Headers(result)
  272. _begin_form = "begin_form"
  273. _begin_file = "begin_file"
  274. _cont = "cont"
  275. _end = "end"
  276. class MultiPartParser(object):
  277. def __init__(
  278. self,
  279. stream_factory=None,
  280. charset="utf-8",
  281. errors="replace",
  282. max_form_memory_size=None,
  283. cls=None,
  284. buffer_size=64 * 1024,
  285. ):
  286. self.charset = charset
  287. self.errors = errors
  288. self.max_form_memory_size = max_form_memory_size
  289. self.stream_factory = (
  290. default_stream_factory if stream_factory is None else stream_factory
  291. )
  292. self.cls = MultiDict if cls is None else cls
  293. # make sure the buffer size is divisible by four so that we can base64
  294. # decode chunk by chunk
  295. assert buffer_size % 4 == 0, "buffer size has to be divisible by 4"
  296. # also the buffer size has to be at least 1024 bytes long or long headers
  297. # will freak out the system
  298. assert buffer_size >= 1024, "buffer size has to be at least 1KB"
  299. self.buffer_size = buffer_size
  300. def _fix_ie_filename(self, filename):
  301. """Internet Explorer 6 transmits the full file name if a file is
  302. uploaded. This function strips the full path if it thinks the
  303. filename is Windows-like absolute.
  304. """
  305. if filename[1:3] == ":\\" or filename[:2] == "\\\\":
  306. return filename.split("\\")[-1]
  307. return filename
  308. def _find_terminator(self, iterator):
  309. """The terminator might have some additional newlines before it.
  310. There is at least one application that sends additional newlines
  311. before headers (the python setuptools package).
  312. """
  313. for line in iterator:
  314. if not line:
  315. break
  316. line = line.strip()
  317. if line:
  318. return line
  319. return b""
  320. def fail(self, message):
  321. raise ValueError(message)
  322. def get_part_encoding(self, headers):
  323. transfer_encoding = headers.get("content-transfer-encoding")
  324. if (
  325. transfer_encoding is not None
  326. and transfer_encoding in _supported_multipart_encodings
  327. ):
  328. return transfer_encoding
  329. def get_part_charset(self, headers):
  330. # Figure out input charset for current part
  331. content_type = headers.get("content-type")
  332. if content_type:
  333. mimetype, ct_params = parse_options_header(content_type)
  334. return ct_params.get("charset", self.charset)
  335. return self.charset
  336. def start_file_streaming(self, filename, headers, total_content_length):
  337. if isinstance(filename, bytes):
  338. filename = filename.decode(self.charset, self.errors)
  339. filename = self._fix_ie_filename(filename)
  340. content_type = headers.get("content-type")
  341. try:
  342. content_length = int(headers["content-length"])
  343. except (KeyError, ValueError):
  344. content_length = 0
  345. container = self.stream_factory(
  346. total_content_length=total_content_length,
  347. filename=filename,
  348. content_type=content_type,
  349. content_length=content_length,
  350. )
  351. return filename, container
  352. def in_memory_threshold_reached(self, bytes):
  353. raise exceptions.RequestEntityTooLarge()
  354. def validate_boundary(self, boundary):
  355. if not boundary:
  356. self.fail("Missing boundary")
  357. if not is_valid_multipart_boundary(boundary):
  358. self.fail("Invalid boundary: %s" % boundary)
  359. if len(boundary) > self.buffer_size: # pragma: no cover
  360. # this should never happen because we check for a minimum size
  361. # of 1024 and boundaries may not be longer than 200. The only
  362. # situation when this happens is for non debug builds where
  363. # the assert is skipped.
  364. self.fail("Boundary longer than buffer size")
  365. def parse_lines(self, file, boundary, content_length, cap_at_buffer=True):
  366. """Generate parts of
  367. ``('begin_form', (headers, name))``
  368. ``('begin_file', (headers, name, filename))``
  369. ``('cont', bytestring)``
  370. ``('end', None)``
  371. Always obeys the grammar
  372. parts = ( begin_form cont* end |
  373. begin_file cont* end )*
  374. """
  375. next_part = b"--" + boundary
  376. last_part = next_part + b"--"
  377. iterator = chain(
  378. make_line_iter(
  379. file,
  380. limit=content_length,
  381. buffer_size=self.buffer_size,
  382. cap_at_buffer=cap_at_buffer,
  383. ),
  384. _empty_string_iter,
  385. )
  386. terminator = self._find_terminator(iterator)
  387. if terminator == last_part:
  388. return
  389. elif terminator != next_part:
  390. self.fail("Expected boundary at start of multipart data")
  391. while terminator != last_part:
  392. headers = parse_multipart_headers(iterator)
  393. disposition = headers.get("content-disposition")
  394. if disposition is None:
  395. self.fail("Missing Content-Disposition header")
  396. disposition, extra = parse_options_header(disposition)
  397. transfer_encoding = self.get_part_encoding(headers)
  398. name = extra.get("name")
  399. filename = extra.get("filename")
  400. # if no content type is given we stream into memory. A list is
  401. # used as a temporary container.
  402. if filename is None:
  403. yield _begin_form, (headers, name)
  404. # otherwise we parse the rest of the headers and ask the stream
  405. # factory for something we can write in.
  406. else:
  407. yield _begin_file, (headers, name, filename)
  408. buf = b""
  409. for line in iterator:
  410. if not line:
  411. self.fail("unexpected end of stream")
  412. if line[:2] == b"--":
  413. terminator = line.rstrip()
  414. if terminator in (next_part, last_part):
  415. break
  416. if transfer_encoding is not None:
  417. if transfer_encoding == "base64":
  418. transfer_encoding = "base64_codec"
  419. try:
  420. line = codecs.decode(line, transfer_encoding)
  421. except Exception:
  422. self.fail("could not decode transfer encoded chunk")
  423. # we have something in the buffer from the last iteration.
  424. # this is usually a newline delimiter.
  425. if buf:
  426. yield _cont, buf
  427. buf = b""
  428. # If the line ends with windows CRLF we write everything except
  429. # the last two bytes. In all other cases however we write
  430. # everything except the last byte. If it was a newline, that's
  431. # fine, otherwise it does not matter because we will write it
  432. # the next iteration. this ensures we do not write the
  433. # final newline into the stream. That way we do not have to
  434. # truncate the stream. However we do have to make sure that
  435. # if something else than a newline is in there we write it
  436. # out.
  437. if line[-2:] == b"\r\n":
  438. buf = b"\r\n"
  439. cutoff = -2
  440. else:
  441. buf = line[-1:]
  442. cutoff = -1
  443. yield _cont, line[:cutoff]
  444. else: # pragma: no cover
  445. raise ValueError("unexpected end of part")
  446. # if we have a leftover in the buffer that is not a newline
  447. # character we have to flush it, otherwise we will chop of
  448. # certain values.
  449. if buf not in (b"", b"\r", b"\n", b"\r\n"):
  450. yield _cont, buf
  451. yield _end, None
  452. def parse_parts(self, file, boundary, content_length):
  453. """Generate ``('file', (name, val))`` and
  454. ``('form', (name, val))`` parts.
  455. """
  456. in_memory = 0
  457. for ellt, ell in self.parse_lines(file, boundary, content_length):
  458. if ellt == _begin_file:
  459. headers, name, filename = ell
  460. is_file = True
  461. guard_memory = False
  462. filename, container = self.start_file_streaming(
  463. filename, headers, content_length
  464. )
  465. _write = container.write
  466. elif ellt == _begin_form:
  467. headers, name = ell
  468. is_file = False
  469. container = []
  470. _write = container.append
  471. guard_memory = self.max_form_memory_size is not None
  472. elif ellt == _cont:
  473. _write(ell)
  474. # if we write into memory and there is a memory size limit we
  475. # count the number of bytes in memory and raise an exception if
  476. # there is too much data in memory.
  477. if guard_memory:
  478. in_memory += len(ell)
  479. if in_memory > self.max_form_memory_size:
  480. self.in_memory_threshold_reached(in_memory)
  481. elif ellt == _end:
  482. if is_file:
  483. container.seek(0)
  484. yield (
  485. "file",
  486. (name, FileStorage(container, filename, name, headers=headers)),
  487. )
  488. else:
  489. part_charset = self.get_part_charset(headers)
  490. yield (
  491. "form",
  492. (name, b"".join(container).decode(part_charset, self.errors)),
  493. )
  494. def parse(self, file, boundary, content_length):
  495. formstream, filestream = tee(
  496. self.parse_parts(file, boundary, content_length), 2
  497. )
  498. form = (p[1] for p in formstream if p[0] == "form")
  499. files = (p[1] for p in filestream if p[0] == "file")
  500. return self.cls(form), self.cls(files)