multipart.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. from __future__ import annotations
  2. import re
  3. import typing as t
  4. from dataclasses import dataclass
  5. from enum import auto
  6. from enum import Enum
  7. from ..datastructures import Headers
  8. from ..exceptions import RequestEntityTooLarge
  9. from ..http import parse_options_header
  10. class Event:
  11. pass
  12. @dataclass(frozen=True)
  13. class Preamble(Event):
  14. data: bytes
  15. @dataclass(frozen=True)
  16. class Field(Event):
  17. name: str
  18. headers: Headers
  19. @dataclass(frozen=True)
  20. class File(Event):
  21. name: str
  22. filename: str
  23. headers: Headers
  24. @dataclass(frozen=True)
  25. class Data(Event):
  26. data: bytes
  27. more_data: bool
  28. @dataclass(frozen=True)
  29. class Epilogue(Event):
  30. data: bytes
  31. class NeedData(Event):
  32. pass
  33. NEED_DATA = NeedData()
  34. class State(Enum):
  35. PREAMBLE = auto()
  36. PART = auto()
  37. DATA = auto()
  38. DATA_START = auto()
  39. EPILOGUE = auto()
  40. COMPLETE = auto()
  41. # Multipart line breaks MUST be CRLF (\r\n) by RFC-7578, except that
  42. # many implementations break this and either use CR or LF alone.
  43. LINE_BREAK = b"(?:\r\n|\n|\r)"
  44. BLANK_LINE_RE = re.compile(b"(?:\r\n\r\n|\r\r|\n\n)", re.MULTILINE)
  45. LINE_BREAK_RE = re.compile(LINE_BREAK, re.MULTILINE)
  46. # Header values can be continued via a space or tab after the linebreak, as
  47. # per RFC2231
  48. HEADER_CONTINUATION_RE = re.compile(b"%s[ \t]" % LINE_BREAK, re.MULTILINE)
  49. # This must be long enough to contain any line breaks plus any
  50. # additional boundary markers (--) such that they will be found in a
  51. # subsequent search
  52. SEARCH_EXTRA_LENGTH = 8
  53. class MultipartDecoder:
  54. """Decodes a multipart message as bytes into Python events.
  55. The part data is returned as available to allow the caller to save
  56. the data from memory to disk, if desired.
  57. .. versionchanged:: 3.1.4
  58. Handle chunks that split a``\r\n`` sequence.
  59. """
  60. def __init__(
  61. self,
  62. boundary: bytes,
  63. max_form_memory_size: int | None = None,
  64. *,
  65. max_parts: int | None = None,
  66. ) -> None:
  67. self.buffer = bytearray()
  68. self.complete = False
  69. self.max_form_memory_size = max_form_memory_size
  70. self.max_parts = max_parts
  71. self.state = State.PREAMBLE
  72. self.boundary = boundary
  73. # Note in the below \h i.e. horizontal whitespace is used
  74. # as [^\S\n\r] as \h isn't supported in python.
  75. # The preamble must end with a boundary where the boundary is
  76. # prefixed by a line break, RFC2046. Except that many
  77. # implementations including Werkzeug's tests omit the line
  78. # break prefix. In addition the first boundary could be the
  79. # epilogue boundary (for empty form-data) hence the matching
  80. # group to understand if it is an epilogue boundary.
  81. self.preamble_re = re.compile(
  82. rb"%s?--%s(--[^\S\n\r]*%s?|[^\S\n\r]*%s)"
  83. % (LINE_BREAK, re.escape(boundary), LINE_BREAK, LINE_BREAK),
  84. re.MULTILINE,
  85. )
  86. # A boundary must include a line break prefix and suffix, and
  87. # may include trailing whitespace. In addition the boundary
  88. # could be the epilogue boundary hence the matching group to
  89. # understand if it is an epilogue boundary.
  90. self.boundary_re = re.compile(
  91. rb"%s--%s(--[^\S\n\r]*%s?|[^\S\n\r]*%s)"
  92. % (LINE_BREAK, re.escape(boundary), LINE_BREAK, LINE_BREAK),
  93. re.MULTILINE,
  94. )
  95. self._search_position = 0
  96. self._parts_decoded = 0
  97. def receive_data(self, data: bytes | None) -> None:
  98. if data is None:
  99. self.complete = True
  100. elif (
  101. self.max_form_memory_size is not None
  102. and len(self.buffer) + len(data) > self.max_form_memory_size
  103. ):
  104. # Ensure that data within single event does not exceed limit.
  105. # Also checked across accumulated events in MultiPartParser.
  106. raise RequestEntityTooLarge()
  107. else:
  108. self.buffer.extend(data)
  109. def next_event(self) -> Event:
  110. event: Event = NEED_DATA
  111. if self.state == State.PREAMBLE:
  112. match = self.preamble_re.search(self.buffer, self._search_position)
  113. if match is not None:
  114. if match.group(1).startswith(b"--"):
  115. self.state = State.EPILOGUE
  116. else:
  117. self.state = State.PART
  118. data = bytes(self.buffer[: match.start()])
  119. del self.buffer[: match.end()]
  120. event = Preamble(data=data)
  121. self._search_position = 0
  122. else:
  123. # Update the search start position to be equal to the
  124. # current buffer length (already searched) minus a
  125. # safe buffer for part of the search target.
  126. self._search_position = max(
  127. 0, len(self.buffer) - len(self.boundary) - SEARCH_EXTRA_LENGTH
  128. )
  129. elif self.state == State.PART:
  130. match = BLANK_LINE_RE.search(self.buffer, self._search_position)
  131. if match is not None:
  132. headers = self._parse_headers(self.buffer[: match.start()])
  133. # The final header ends with a single CRLF, however a
  134. # blank line indicates the start of the
  135. # body. Therefore the end is after the first CRLF.
  136. headers_end = (match.start() + match.end()) // 2
  137. del self.buffer[:headers_end]
  138. if "content-disposition" not in headers:
  139. raise ValueError("Missing Content-Disposition header")
  140. disposition, extra = parse_options_header(
  141. headers["content-disposition"]
  142. )
  143. name = t.cast(str, extra.get("name"))
  144. filename = extra.get("filename")
  145. if filename is not None:
  146. event = File(
  147. filename=filename,
  148. headers=headers,
  149. name=name,
  150. )
  151. else:
  152. event = Field(
  153. headers=headers,
  154. name=name,
  155. )
  156. self.state = State.DATA_START
  157. self._search_position = 0
  158. self._parts_decoded += 1
  159. if self.max_parts is not None and self._parts_decoded > self.max_parts:
  160. raise RequestEntityTooLarge()
  161. else:
  162. # Update the search start position to be equal to the
  163. # current buffer length (already searched) minus a
  164. # safe buffer for part of the search target.
  165. self._search_position = max(0, len(self.buffer) - SEARCH_EXTRA_LENGTH)
  166. elif self.state == State.DATA_START:
  167. data, del_index, more_data = self._parse_data(self.buffer, start=True)
  168. del self.buffer[:del_index]
  169. event = Data(data=data, more_data=more_data)
  170. if more_data:
  171. self.state = State.DATA
  172. elif self.state == State.DATA:
  173. data, del_index, more_data = self._parse_data(self.buffer, start=False)
  174. del self.buffer[:del_index]
  175. if data or not more_data:
  176. event = Data(data=data, more_data=more_data)
  177. elif self.state == State.EPILOGUE and self.complete:
  178. event = Epilogue(data=bytes(self.buffer))
  179. del self.buffer[:]
  180. self.state = State.COMPLETE
  181. if self.complete and isinstance(event, NeedData):
  182. raise ValueError(f"Invalid form-data cannot parse beyond {self.state}")
  183. return event
  184. def _parse_headers(self, data: bytes | bytearray) -> Headers:
  185. headers: list[tuple[str, str]] = []
  186. # Merge the continued headers into one line
  187. data = HEADER_CONTINUATION_RE.sub(b" ", data)
  188. # Now there is one header per line
  189. for line in data.splitlines():
  190. line = line.strip(b" \t")
  191. if line != b"":
  192. name, _, value = line.decode().partition(":")
  193. headers.append((name.strip(" \t"), value.strip(" \t")))
  194. return Headers(headers)
  195. def _parse_data(
  196. self, data: bytes | bytearray, *, start: bool
  197. ) -> tuple[bytes, int, bool]:
  198. # Body parts must start with CRLF (or CR or LF)
  199. if start:
  200. match = LINE_BREAK_RE.match(data)
  201. data_start = t.cast(t.Match[bytes], match).end()
  202. else:
  203. data_start = 0
  204. if self.buffer.find(b"--" + self.boundary) == -1:
  205. # No complete boundary in the buffer, but there may be
  206. # a partial boundary at the end.
  207. data_end = del_index = (
  208. self._last_partial_boundary_index(data[data_start:]) + data_start
  209. )
  210. more_data = True
  211. else:
  212. match = self.boundary_re.search(data)
  213. if match is not None:
  214. if match.group(1).startswith(b"--"):
  215. self.state = State.EPILOGUE
  216. else:
  217. self.state = State.PART
  218. data_end = match.start()
  219. del_index = match.end()
  220. else:
  221. data_end = del_index = (
  222. self._last_partial_boundary_index(data[data_start:]) + data_start
  223. )
  224. more_data = match is None
  225. return bytes(data[data_start:data_end]), del_index, more_data
  226. def _last_partial_boundary_index(self, data: bytes | bytearray) -> int:
  227. # Find the last index following which a partial boundary
  228. # could be present in the data. This will be the earliest
  229. # position of a LF or a CR, unless that position is more
  230. # than a complete boundary from the end in which case there
  231. # is no partial boundary.
  232. complete_boundary_index = len(data) - len(b"\r\n--" + self.boundary)
  233. try:
  234. last_nl = data.rindex(b"\n")
  235. except ValueError:
  236. last_nl = len(data)
  237. else:
  238. if last_nl < complete_boundary_index:
  239. last_nl = len(data)
  240. try:
  241. last_cr = data.rindex(b"\r")
  242. except ValueError:
  243. last_cr = len(data)
  244. else:
  245. if last_cr < complete_boundary_index:
  246. last_cr = len(data)
  247. return min(last_nl, last_cr)
  248. class MultipartEncoder:
  249. """Used by the test client to create a multipart body. This is not secure
  250. and must only be used during testing, never in applications.
  251. :meta private:
  252. """
  253. def __init__(self, boundary: bytes) -> None:
  254. self.boundary = boundary
  255. self.state = State.PREAMBLE
  256. def send_event(self, event: Event) -> bytes:
  257. if isinstance(event, Preamble) and self.state == State.PREAMBLE:
  258. self.state = State.PART
  259. return event.data
  260. elif isinstance(event, (Field, File)) and self.state in {
  261. State.PREAMBLE,
  262. State.PART,
  263. State.DATA,
  264. }:
  265. data = b"\r\n--" + self.boundary + b"\r\n"
  266. data += b'Content-Disposition: form-data; name="%s"' % event.name.encode()
  267. if isinstance(event, File):
  268. data += b'; filename="%s"' % event.filename.encode()
  269. data += b"\r\n"
  270. for name, value in t.cast(Field, event).headers:
  271. if name.lower() != "content-disposition":
  272. data += f"{name}: {value}\r\n".encode()
  273. self.state = State.DATA_START
  274. return data
  275. elif isinstance(event, Data) and self.state == State.DATA_START:
  276. self.state = State.DATA
  277. if len(event.data) > 0:
  278. return b"\r\n" + event.data
  279. else:
  280. return event.data
  281. elif isinstance(event, Data) and self.state == State.DATA:
  282. return event.data
  283. elif isinstance(event, Epilogue):
  284. self.state = State.COMPLETE
  285. return b"\r\n--" + self.boundary + b"--\r\n" + event.data
  286. else:
  287. raise ValueError(f"Cannot generate {event} in state: {self.state}")