You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

multipartparser.py 24 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. """
  2. Multi-part parsing for file uploads.
  3. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to
  4. file upload handlers for processing.
  5. """
  6. from __future__ import unicode_literals
  7. import base64
  8. import binascii
  9. import cgi
  10. import sys
  11. from django.conf import settings
  12. from django.core.exceptions import SuspiciousMultipartForm
  13. from django.core.files.uploadhandler import (
  14. SkipFile, StopFutureHandlers, StopUpload,
  15. )
  16. from django.utils import six
  17. from django.utils.datastructures import MultiValueDict
  18. from django.utils.encoding import force_text
  19. from django.utils.six.moves.urllib.parse import unquote
  20. from django.utils.text import unescape_entities
  21. __all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted')
  22. class MultiPartParserError(Exception):
  23. pass
  24. class InputStreamExhausted(Exception):
  25. """
  26. No more reads are allowed from this device.
  27. """
  28. pass
  29. RAW = "raw"
  30. FILE = "file"
  31. FIELD = "field"
  32. _BASE64_DECODE_ERROR = TypeError if six.PY2 else binascii.Error
  33. class MultiPartParser(object):
  34. """
  35. A rfc2388 multipart/form-data parser.
  36. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks
  37. and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``.
  38. """
  39. def __init__(self, META, input_data, upload_handlers, encoding=None):
  40. """
  41. Initialize the MultiPartParser object.
  42. :META:
  43. The standard ``META`` dictionary in Django request objects.
  44. :input_data:
  45. The raw post data, as a file-like object.
  46. :upload_handlers:
  47. A list of UploadHandler instances that perform operations on the uploaded
  48. data.
  49. :encoding:
  50. The encoding with which to treat the incoming data.
  51. """
  52. #
  53. # Content-Type should contain multipart and the boundary information.
  54. #
  55. content_type = META.get('HTTP_CONTENT_TYPE', META.get('CONTENT_TYPE', ''))
  56. if not content_type.startswith('multipart/'):
  57. raise MultiPartParserError('Invalid Content-Type: %s' % content_type)
  58. # Parse the header to get the boundary to split the parts.
  59. ctypes, opts = parse_header(content_type.encode('ascii'))
  60. boundary = opts.get('boundary')
  61. if not boundary or not cgi.valid_boundary(boundary):
  62. raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary)
  63. # Content-Length should contain the length of the body we are about
  64. # to receive.
  65. try:
  66. content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0)))
  67. except (ValueError, TypeError):
  68. content_length = 0
  69. if content_length < 0:
  70. # This means we shouldn't continue...raise an error.
  71. raise MultiPartParserError("Invalid content length: %r" % content_length)
  72. if isinstance(boundary, six.text_type):
  73. boundary = boundary.encode('ascii')
  74. self._boundary = boundary
  75. self._input_data = input_data
  76. # For compatibility with low-level network APIs (with 32-bit integers),
  77. # the chunk size should be < 2^31, but still divisible by 4.
  78. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
  79. self._chunk_size = min([2 ** 31 - 4] + possible_sizes)
  80. self._meta = META
  81. self._encoding = encoding or settings.DEFAULT_CHARSET
  82. self._content_length = content_length
  83. self._upload_handlers = upload_handlers
  84. def parse(self):
  85. """
  86. Parse the POST data and break it into a FILES MultiValueDict and a POST
  87. MultiValueDict.
  88. Returns a tuple containing the POST and FILES dictionary, respectively.
  89. """
  90. # We have to import QueryDict down here to avoid a circular import.
  91. from django.http import QueryDict
  92. encoding = self._encoding
  93. handlers = self._upload_handlers
  94. # HTTP spec says that Content-Length >= 0 is valid
  95. # handling content-length == 0 before continuing
  96. if self._content_length == 0:
  97. return QueryDict('', encoding=self._encoding), MultiValueDict()
  98. # See if any of the handlers take care of the parsing.
  99. # This allows overriding everything if need be.
  100. for handler in handlers:
  101. result = handler.handle_raw_input(self._input_data,
  102. self._meta,
  103. self._content_length,
  104. self._boundary,
  105. encoding)
  106. # Check to see if it was handled
  107. if result is not None:
  108. return result[0], result[1]
  109. # Create the data structures to be used later.
  110. self._post = QueryDict('', mutable=True)
  111. self._files = MultiValueDict()
  112. # Instantiate the parser and stream:
  113. stream = LazyStream(ChunkIter(self._input_data, self._chunk_size))
  114. # Whether or not to signal a file-completion at the beginning of the loop.
  115. old_field_name = None
  116. counters = [0] * len(handlers)
  117. try:
  118. for item_type, meta_data, field_stream in Parser(stream, self._boundary):
  119. if old_field_name:
  120. # We run this at the beginning of the next loop
  121. # since we cannot be sure a file is complete until
  122. # we hit the next boundary/part of the multipart content.
  123. self.handle_file_complete(old_field_name, counters)
  124. old_field_name = None
  125. try:
  126. disposition = meta_data['content-disposition'][1]
  127. field_name = disposition['name'].strip()
  128. except (KeyError, IndexError, AttributeError):
  129. continue
  130. transfer_encoding = meta_data.get('content-transfer-encoding')
  131. if transfer_encoding is not None:
  132. transfer_encoding = transfer_encoding[0].strip()
  133. field_name = force_text(field_name, encoding, errors='replace')
  134. if item_type == FIELD:
  135. # This is a post field, we can just set it in the post
  136. if transfer_encoding == 'base64':
  137. raw_data = field_stream.read()
  138. try:
  139. data = base64.b64decode(raw_data)
  140. except _BASE64_DECODE_ERROR:
  141. data = raw_data
  142. else:
  143. data = field_stream.read()
  144. self._post.appendlist(field_name,
  145. force_text(data, encoding, errors='replace'))
  146. elif item_type == FILE:
  147. # This is a file, use the handler...
  148. file_name = disposition.get('filename')
  149. if file_name:
  150. file_name = force_text(file_name, encoding, errors='replace')
  151. file_name = self.IE_sanitize(unescape_entities(file_name))
  152. if not file_name:
  153. continue
  154. content_type, content_type_extra = meta_data.get('content-type', ('', {}))
  155. content_type = content_type.strip()
  156. charset = content_type_extra.get('charset')
  157. try:
  158. content_length = int(meta_data.get('content-length')[0])
  159. except (IndexError, TypeError, ValueError):
  160. content_length = None
  161. counters = [0] * len(handlers)
  162. try:
  163. for handler in handlers:
  164. try:
  165. handler.new_file(field_name, file_name,
  166. content_type, content_length,
  167. charset, content_type_extra)
  168. except StopFutureHandlers:
  169. break
  170. for chunk in field_stream:
  171. if transfer_encoding == 'base64':
  172. # We only special-case base64 transfer encoding
  173. # We should always decode base64 chunks by multiple of 4,
  174. # ignoring whitespace.
  175. stripped_chunk = b"".join(chunk.split())
  176. remaining = len(stripped_chunk) % 4
  177. while remaining != 0:
  178. over_chunk = field_stream.read(4 - remaining)
  179. stripped_chunk += b"".join(over_chunk.split())
  180. remaining = len(stripped_chunk) % 4
  181. try:
  182. chunk = base64.b64decode(stripped_chunk)
  183. except Exception as e:
  184. # Since this is only a chunk, any error is an unfixable error.
  185. msg = "Could not decode base64 data: %r" % e
  186. six.reraise(MultiPartParserError, MultiPartParserError(msg), sys.exc_info()[2])
  187. for i, handler in enumerate(handlers):
  188. chunk_length = len(chunk)
  189. chunk = handler.receive_data_chunk(chunk,
  190. counters[i])
  191. counters[i] += chunk_length
  192. if chunk is None:
  193. # If the chunk received by the handler is None, then don't continue.
  194. break
  195. except SkipFile:
  196. self._close_files()
  197. # Just use up the rest of this file...
  198. exhaust(field_stream)
  199. else:
  200. # Handle file upload completions on next iteration.
  201. old_field_name = field_name
  202. else:
  203. # If this is neither a FIELD or a FILE, just exhaust the stream.
  204. exhaust(stream)
  205. except StopUpload as e:
  206. self._close_files()
  207. if not e.connection_reset:
  208. exhaust(self._input_data)
  209. else:
  210. # Make sure that the request data is all fed
  211. exhaust(self._input_data)
  212. # Signal that the upload has completed.
  213. for handler in handlers:
  214. retval = handler.upload_complete()
  215. if retval:
  216. break
  217. return self._post, self._files
  218. def handle_file_complete(self, old_field_name, counters):
  219. """
  220. Handle all the signaling that takes place when a file is complete.
  221. """
  222. for i, handler in enumerate(self._upload_handlers):
  223. file_obj = handler.file_complete(counters[i])
  224. if file_obj:
  225. # If it returns a file object, then set the files dict.
  226. self._files.appendlist(
  227. force_text(old_field_name, self._encoding, errors='replace'),
  228. file_obj)
  229. break
  230. def IE_sanitize(self, filename):
  231. """Cleanup filename from Internet Explorer full paths."""
  232. return filename and filename[filename.rfind("\\") + 1:].strip()
  233. def _close_files(self):
  234. # Free up all file handles.
  235. # FIXME: this currently assumes that upload handlers store the file as 'file'
  236. # We should document that... (Maybe add handler.free_file to complement new_file)
  237. for handler in self._upload_handlers:
  238. if hasattr(handler, 'file'):
  239. handler.file.close()
  240. class LazyStream(six.Iterator):
  241. """
  242. The LazyStream wrapper allows one to get and "unget" bytes from a stream.
  243. Given a producer object (an iterator that yields bytestrings), the
  244. LazyStream object will support iteration, reading, and keeping a "look-back"
  245. variable in case you need to "unget" some bytes.
  246. """
  247. def __init__(self, producer, length=None):
  248. """
  249. Every LazyStream must have a producer when instantiated.
  250. A producer is an iterable that returns a string each time it
  251. is called.
  252. """
  253. self._producer = producer
  254. self._empty = False
  255. self._leftover = b''
  256. self.length = length
  257. self.position = 0
  258. self._remaining = length
  259. self._unget_history = []
  260. def tell(self):
  261. return self.position
  262. def read(self, size=None):
  263. def parts():
  264. remaining = self._remaining if size is None else size
  265. # do the whole thing in one shot if no limit was provided.
  266. if remaining is None:
  267. yield b''.join(self)
  268. return
  269. # otherwise do some bookkeeping to return exactly enough
  270. # of the stream and stashing any extra content we get from
  271. # the producer
  272. while remaining != 0:
  273. assert remaining > 0, 'remaining bytes to read should never go negative'
  274. try:
  275. chunk = next(self)
  276. except StopIteration:
  277. return
  278. else:
  279. emitting = chunk[:remaining]
  280. self.unget(chunk[remaining:])
  281. remaining -= len(emitting)
  282. yield emitting
  283. out = b''.join(parts())
  284. return out
  285. def __next__(self):
  286. """
  287. Used when the exact number of bytes to read is unimportant.
  288. This procedure just returns whatever is chunk is conveniently returned
  289. from the iterator instead. Useful to avoid unnecessary bookkeeping if
  290. performance is an issue.
  291. """
  292. if self._leftover:
  293. output = self._leftover
  294. self._leftover = b''
  295. else:
  296. output = next(self._producer)
  297. self._unget_history = []
  298. self.position += len(output)
  299. return output
  300. def close(self):
  301. """
  302. Used to invalidate/disable this lazy stream.
  303. Replaces the producer with an empty list. Any leftover bytes that have
  304. already been read will still be reported upon read() and/or next().
  305. """
  306. self._producer = []
  307. def __iter__(self):
  308. return self
  309. def unget(self, bytes):
  310. """
  311. Places bytes back onto the front of the lazy stream.
  312. Future calls to read() will return those bytes first. The
  313. stream position and thus tell() will be rewound.
  314. """
  315. if not bytes:
  316. return
  317. self._update_unget_history(len(bytes))
  318. self.position -= len(bytes)
  319. self._leftover = b''.join([bytes, self._leftover])
  320. def _update_unget_history(self, num_bytes):
  321. """
  322. Updates the unget history as a sanity check to see if we've pushed
  323. back the same number of bytes in one chunk. If we keep ungetting the
  324. same number of bytes many times (here, 50), we're mostly likely in an
  325. infinite loop of some sort. This is usually caused by a
  326. maliciously-malformed MIME request.
  327. """
  328. self._unget_history = [num_bytes] + self._unget_history[:49]
  329. number_equal = len([current_number for current_number in self._unget_history
  330. if current_number == num_bytes])
  331. if number_equal > 40:
  332. raise SuspiciousMultipartForm(
  333. "The multipart parser got stuck, which shouldn't happen with"
  334. " normal uploaded files. Check for malicious upload activity;"
  335. " if there is none, report this to the Django developers."
  336. )
  337. class ChunkIter(six.Iterator):
  338. """
  339. An iterable that will yield chunks of data. Given a file-like object as the
  340. constructor, this object will yield chunks of read operations from that
  341. object.
  342. """
  343. def __init__(self, flo, chunk_size=64 * 1024):
  344. self.flo = flo
  345. self.chunk_size = chunk_size
  346. def __next__(self):
  347. try:
  348. data = self.flo.read(self.chunk_size)
  349. except InputStreamExhausted:
  350. raise StopIteration()
  351. if data:
  352. return data
  353. else:
  354. raise StopIteration()
  355. def __iter__(self):
  356. return self
  357. class InterBoundaryIter(six.Iterator):
  358. """
  359. A Producer that will iterate over boundaries.
  360. """
  361. def __init__(self, stream, boundary):
  362. self._stream = stream
  363. self._boundary = boundary
  364. def __iter__(self):
  365. return self
  366. def __next__(self):
  367. try:
  368. return LazyStream(BoundaryIter(self._stream, self._boundary))
  369. except InputStreamExhausted:
  370. raise StopIteration()
  371. class BoundaryIter(six.Iterator):
  372. """
  373. A Producer that is sensitive to boundaries.
  374. Will happily yield bytes until a boundary is found. Will yield the bytes
  375. before the boundary, throw away the boundary bytes themselves, and push the
  376. post-boundary bytes back on the stream.
  377. The future calls to next() after locating the boundary will raise a
  378. StopIteration exception.
  379. """
  380. def __init__(self, stream, boundary):
  381. self._stream = stream
  382. self._boundary = boundary
  383. self._done = False
  384. # rollback an additional six bytes because the format is like
  385. # this: CRLF<boundary>[--CRLF]
  386. self._rollback = len(boundary) + 6
  387. # Try to use mx fast string search if available. Otherwise
  388. # use Python find. Wrap the latter for consistency.
  389. unused_char = self._stream.read(1)
  390. if not unused_char:
  391. raise InputStreamExhausted()
  392. self._stream.unget(unused_char)
  393. def __iter__(self):
  394. return self
  395. def __next__(self):
  396. if self._done:
  397. raise StopIteration()
  398. stream = self._stream
  399. rollback = self._rollback
  400. bytes_read = 0
  401. chunks = []
  402. for bytes in stream:
  403. bytes_read += len(bytes)
  404. chunks.append(bytes)
  405. if bytes_read > rollback:
  406. break
  407. if not bytes:
  408. break
  409. else:
  410. self._done = True
  411. if not chunks:
  412. raise StopIteration()
  413. chunk = b''.join(chunks)
  414. boundary = self._find_boundary(chunk, len(chunk) < self._rollback)
  415. if boundary:
  416. end, next = boundary
  417. stream.unget(chunk[next:])
  418. self._done = True
  419. return chunk[:end]
  420. else:
  421. # make sure we don't treat a partial boundary (and
  422. # its separators) as data
  423. if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6):
  424. # There's nothing left, we should just return and mark as done.
  425. self._done = True
  426. return chunk
  427. else:
  428. stream.unget(chunk[-rollback:])
  429. return chunk[:-rollback]
  430. def _find_boundary(self, data, eof=False):
  431. """
  432. Finds a multipart boundary in data.
  433. Should no boundary exist in the data None is returned instead. Otherwise
  434. a tuple containing the indices of the following are returned:
  435. * the end of current encapsulation
  436. * the start of the next encapsulation
  437. """
  438. index = data.find(self._boundary)
  439. if index < 0:
  440. return None
  441. else:
  442. end = index
  443. next = index + len(self._boundary)
  444. # backup over CRLF
  445. last = max(0, end - 1)
  446. if data[last:last + 1] == b'\n':
  447. end -= 1
  448. last = max(0, end - 1)
  449. if data[last:last + 1] == b'\r':
  450. end -= 1
  451. return end, next
  452. def exhaust(stream_or_iterable):
  453. """
  454. Completely exhausts an iterator or stream.
  455. Raise a MultiPartParserError if the argument is not a stream or an iterable.
  456. """
  457. iterator = None
  458. try:
  459. iterator = iter(stream_or_iterable)
  460. except TypeError:
  461. iterator = ChunkIter(stream_or_iterable, 16384)
  462. if iterator is None:
  463. raise MultiPartParserError('multipartparser.exhaust() was passed a non-iterable or stream parameter')
  464. for __ in iterator:
  465. pass
  466. def parse_boundary_stream(stream, max_header_size):
  467. """
  468. Parses one and exactly one stream that encapsulates a boundary.
  469. """
  470. # Stream at beginning of header, look for end of header
  471. # and parse it if found. The header must fit within one
  472. # chunk.
  473. chunk = stream.read(max_header_size)
  474. # 'find' returns the top of these four bytes, so we'll
  475. # need to munch them later to prevent them from polluting
  476. # the payload.
  477. header_end = chunk.find(b'\r\n\r\n')
  478. def _parse_header(line):
  479. main_value_pair, params = parse_header(line)
  480. try:
  481. name, value = main_value_pair.split(':', 1)
  482. except ValueError:
  483. raise ValueError("Invalid header: %r" % line)
  484. return name, (value, params)
  485. if header_end == -1:
  486. # we find no header, so we just mark this fact and pass on
  487. # the stream verbatim
  488. stream.unget(chunk)
  489. return (RAW, {}, stream)
  490. header = chunk[:header_end]
  491. # here we place any excess chunk back onto the stream, as
  492. # well as throwing away the CRLFCRLF bytes from above.
  493. stream.unget(chunk[header_end + 4:])
  494. TYPE = RAW
  495. outdict = {}
  496. # Eliminate blank lines
  497. for line in header.split(b'\r\n'):
  498. # This terminology ("main value" and "dictionary of
  499. # parameters") is from the Python docs.
  500. try:
  501. name, (value, params) = _parse_header(line)
  502. except ValueError:
  503. continue
  504. if name == 'content-disposition':
  505. TYPE = FIELD
  506. if params.get('filename'):
  507. TYPE = FILE
  508. outdict[name] = value, params
  509. if TYPE == RAW:
  510. stream.unget(chunk)
  511. return (TYPE, outdict, stream)
  512. class Parser(object):
  513. def __init__(self, stream, boundary):
  514. self._stream = stream
  515. self._separator = b'--' + boundary
  516. def __iter__(self):
  517. boundarystream = InterBoundaryIter(self._stream, self._separator)
  518. for sub_stream in boundarystream:
  519. # Iterate over each part
  520. yield parse_boundary_stream(sub_stream, 1024)
  521. def parse_header(line):
  522. """ Parse the header into a key-value.
  523. Input (line): bytes, output: unicode for key/name, bytes for value which
  524. will be decoded later
  525. """
  526. plist = _parse_header_params(b';' + line)
  527. key = plist.pop(0).lower().decode('ascii')
  528. pdict = {}
  529. for p in plist:
  530. i = p.find(b'=')
  531. if i >= 0:
  532. has_encoding = False
  533. name = p[:i].strip().lower().decode('ascii')
  534. if name.endswith('*'):
  535. # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext")
  536. # http://tools.ietf.org/html/rfc2231#section-4
  537. name = name[:-1]
  538. if p.count(b"'") == 2:
  539. has_encoding = True
  540. value = p[i + 1:].strip()
  541. if has_encoding:
  542. encoding, lang, value = value.split(b"'")
  543. if six.PY3:
  544. value = unquote(value.decode(), encoding=encoding.decode())
  545. else:
  546. value = unquote(value).decode(encoding)
  547. if len(value) >= 2 and value[:1] == value[-1:] == b'"':
  548. value = value[1:-1]
  549. value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"')
  550. pdict[name] = value
  551. return key, pdict
  552. def _parse_header_params(s):
  553. plist = []
  554. while s[:1] == b';':
  555. s = s[1:]
  556. end = s.find(b';')
  557. while end > 0 and s.count(b'"', 0, end) % 2:
  558. end = s.find(b';', end + 1)
  559. if end < 0:
  560. end = len(s)
  561. f = s[:end]
  562. plist.append(f.strip())
  563. s = s[end:]
  564. return plist