Development of an internal social media platform with personalised dashboards for students
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 24KB

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