formparser.py 21 KB

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