multipartparser.py 27 KB

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