Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

587 строки
21KB

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