multipartparser.py 27 KB

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