formparser.py 21 KB

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