multipartparser.py 23 KB

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