multipart.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. import base64
  2. import binascii
  3. import json
  4. import re
  5. import sys
  6. import uuid
  7. import warnings
  8. from collections import deque
  9. from collections.abc import Mapping, Sequence
  10. from types import TracebackType
  11. from typing import (
  12. TYPE_CHECKING,
  13. Any,
  14. AsyncIterator,
  15. Deque,
  16. Dict,
  17. Iterator,
  18. List,
  19. Optional,
  20. Tuple,
  21. Type,
  22. Union,
  23. cast,
  24. )
  25. from urllib.parse import parse_qsl, unquote, urlencode
  26. from multidict import CIMultiDict, CIMultiDictProxy
  27. from .abc import AbstractStreamWriter
  28. from .compression_utils import (
  29. DEFAULT_MAX_DECOMPRESS_SIZE,
  30. ZLibCompressor,
  31. ZLibDecompressor,
  32. )
  33. from .hdrs import (
  34. CONTENT_DISPOSITION,
  35. CONTENT_ENCODING,
  36. CONTENT_LENGTH,
  37. CONTENT_TRANSFER_ENCODING,
  38. CONTENT_TYPE,
  39. )
  40. from .helpers import CHAR, TOKEN, parse_mimetype, reify
  41. from .http import HeadersParser
  42. from .http_exceptions import BadHttpMessage
  43. from .log import internal_logger
  44. from .payload import (
  45. JsonPayload,
  46. LookupError,
  47. Order,
  48. Payload,
  49. StringPayload,
  50. get_payload,
  51. payload_type,
  52. )
  53. from .streams import StreamReader
  54. if sys.version_info >= (3, 11):
  55. from typing import Self
  56. else:
  57. from typing import TypeVar
  58. Self = TypeVar("Self", bound="BodyPartReader")
  59. __all__ = (
  60. "MultipartReader",
  61. "MultipartWriter",
  62. "BodyPartReader",
  63. "BadContentDispositionHeader",
  64. "BadContentDispositionParam",
  65. "parse_content_disposition",
  66. "content_disposition_filename",
  67. )
  68. if TYPE_CHECKING:
  69. from .client_reqrep import ClientResponse
  70. class BadContentDispositionHeader(RuntimeWarning):
  71. pass
  72. class BadContentDispositionParam(RuntimeWarning):
  73. pass
  74. def parse_content_disposition(
  75. header: Optional[str],
  76. ) -> Tuple[Optional[str], Dict[str, str]]:
  77. def is_token(string: str) -> bool:
  78. return bool(string) and TOKEN >= set(string)
  79. def is_quoted(string: str) -> bool:
  80. return string[0] == string[-1] == '"'
  81. def is_rfc5987(string: str) -> bool:
  82. return is_token(string) and string.count("'") == 2
  83. def is_extended_param(string: str) -> bool:
  84. return string.endswith("*")
  85. def is_continuous_param(string: str) -> bool:
  86. pos = string.find("*") + 1
  87. if not pos:
  88. return False
  89. substring = string[pos:-1] if string.endswith("*") else string[pos:]
  90. return substring.isdigit()
  91. def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str:
  92. return re.sub(f"\\\\([{chars}])", "\\1", text)
  93. if not header:
  94. return None, {}
  95. disptype, *parts = header.split(";")
  96. if not is_token(disptype):
  97. warnings.warn(BadContentDispositionHeader(header))
  98. return None, {}
  99. params: Dict[str, str] = {}
  100. while parts:
  101. item = parts.pop(0)
  102. if not item: # To handle trailing semicolons
  103. warnings.warn(BadContentDispositionHeader(header))
  104. continue
  105. if "=" not in item:
  106. warnings.warn(BadContentDispositionHeader(header))
  107. return None, {}
  108. key, value = item.split("=", 1)
  109. key = key.lower().strip()
  110. value = value.lstrip()
  111. if key in params:
  112. warnings.warn(BadContentDispositionHeader(header))
  113. return None, {}
  114. if not is_token(key):
  115. warnings.warn(BadContentDispositionParam(item))
  116. continue
  117. elif is_continuous_param(key):
  118. if is_quoted(value):
  119. value = unescape(value[1:-1])
  120. elif not is_token(value):
  121. warnings.warn(BadContentDispositionParam(item))
  122. continue
  123. elif is_extended_param(key):
  124. if is_rfc5987(value):
  125. encoding, _, value = value.split("'", 2)
  126. encoding = encoding or "utf-8"
  127. else:
  128. warnings.warn(BadContentDispositionParam(item))
  129. continue
  130. try:
  131. value = unquote(value, encoding, "strict")
  132. except UnicodeDecodeError: # pragma: nocover
  133. warnings.warn(BadContentDispositionParam(item))
  134. continue
  135. else:
  136. failed = True
  137. if is_quoted(value):
  138. failed = False
  139. value = unescape(value[1:-1].lstrip("\\/"))
  140. elif is_token(value):
  141. failed = False
  142. elif parts:
  143. # maybe just ; in filename, in any case this is just
  144. # one case fix, for proper fix we need to redesign parser
  145. _value = f"{value};{parts[0]}"
  146. if is_quoted(_value):
  147. parts.pop(0)
  148. value = unescape(_value[1:-1].lstrip("\\/"))
  149. failed = False
  150. if failed:
  151. warnings.warn(BadContentDispositionHeader(header))
  152. return None, {}
  153. params[key] = value
  154. return disptype.lower(), params
  155. def content_disposition_filename(
  156. params: Mapping[str, str], name: str = "filename"
  157. ) -> Optional[str]:
  158. name_suf = "%s*" % name
  159. if not params:
  160. return None
  161. elif name_suf in params:
  162. return params[name_suf]
  163. elif name in params:
  164. return params[name]
  165. else:
  166. parts = []
  167. fnparams = sorted(
  168. (key, value) for key, value in params.items() if key.startswith(name_suf)
  169. )
  170. for num, (key, value) in enumerate(fnparams):
  171. _, tail = key.split("*", 1)
  172. if tail.endswith("*"):
  173. tail = tail[:-1]
  174. if tail == str(num):
  175. parts.append(value)
  176. else:
  177. break
  178. if not parts:
  179. return None
  180. value = "".join(parts)
  181. if "'" in value:
  182. encoding, _, value = value.split("'", 2)
  183. encoding = encoding or "utf-8"
  184. return unquote(value, encoding, "strict")
  185. return value
  186. class MultipartResponseWrapper:
  187. """Wrapper around the MultipartReader.
  188. It takes care about
  189. underlying connection and close it when it needs in.
  190. """
  191. def __init__(
  192. self,
  193. resp: "ClientResponse",
  194. stream: "MultipartReader",
  195. ) -> None:
  196. self.resp = resp
  197. self.stream = stream
  198. def __aiter__(self) -> "MultipartResponseWrapper":
  199. return self
  200. async def __anext__(
  201. self,
  202. ) -> Union["MultipartReader", "BodyPartReader"]:
  203. part = await self.next()
  204. if part is None:
  205. raise StopAsyncIteration
  206. return part
  207. def at_eof(self) -> bool:
  208. """Returns True when all response data had been read."""
  209. return self.resp.content.at_eof()
  210. async def next(
  211. self,
  212. ) -> Optional[Union["MultipartReader", "BodyPartReader"]]:
  213. """Emits next multipart reader object."""
  214. item = await self.stream.next()
  215. if self.stream.at_eof():
  216. await self.release()
  217. return item
  218. async def release(self) -> None:
  219. """Release the connection gracefully.
  220. All remaining content is read to the void.
  221. """
  222. await self.resp.release()
  223. class BodyPartReader:
  224. """Multipart reader for single body part."""
  225. chunk_size = 8192
  226. def __init__(
  227. self,
  228. boundary: bytes,
  229. headers: "CIMultiDictProxy[str]",
  230. content: StreamReader,
  231. *,
  232. subtype: str = "mixed",
  233. default_charset: Optional[str] = None,
  234. max_decompress_size: int = DEFAULT_MAX_DECOMPRESS_SIZE,
  235. ) -> None:
  236. self.headers = headers
  237. self._boundary = boundary
  238. self._boundary_len = len(boundary) + 2 # Boundary + \r\n
  239. self._content = content
  240. self._default_charset = default_charset
  241. self._at_eof = False
  242. self._is_form_data = subtype == "form-data"
  243. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8
  244. length = None if self._is_form_data else self.headers.get(CONTENT_LENGTH, None)
  245. self._length = int(length) if length is not None else None
  246. self._read_bytes = 0
  247. self._unread: Deque[bytes] = deque()
  248. self._prev_chunk: Optional[bytes] = None
  249. self._content_eof = 0
  250. self._cache: Dict[str, Any] = {}
  251. self._max_decompress_size = max_decompress_size
  252. def __aiter__(self: Self) -> Self:
  253. return self
  254. async def __anext__(self) -> bytes:
  255. part = await self.next()
  256. if part is None:
  257. raise StopAsyncIteration
  258. return part
  259. async def next(self) -> Optional[bytes]:
  260. item = await self.read()
  261. if not item:
  262. return None
  263. return item
  264. async def read(self, *, decode: bool = False) -> bytes:
  265. """Reads body part data.
  266. decode: Decodes data following by encoding
  267. method from Content-Encoding header. If it missed
  268. data remains untouched
  269. """
  270. if self._at_eof:
  271. return b""
  272. data = bytearray()
  273. while not self._at_eof:
  274. data.extend(await self.read_chunk(self.chunk_size))
  275. if decode:
  276. decoded_data = bytearray()
  277. async for d in self.decode_iter(data):
  278. decoded_data.extend(d)
  279. return decoded_data
  280. return data
  281. async def read_chunk(self, size: int = chunk_size) -> bytes:
  282. """Reads body part content chunk of the specified size.
  283. size: chunk size
  284. """
  285. if self._at_eof:
  286. return b""
  287. if self._length:
  288. chunk = await self._read_chunk_from_length(size)
  289. else:
  290. chunk = await self._read_chunk_from_stream(size)
  291. # For the case of base64 data, we must read a fragment of size with a
  292. # remainder of 0 by dividing by 4 for string without symbols \n or \r
  293. encoding = self.headers.get(CONTENT_TRANSFER_ENCODING)
  294. if encoding and encoding.lower() == "base64":
  295. stripped_chunk = b"".join(chunk.split())
  296. remainder = len(stripped_chunk) % 4
  297. while remainder != 0 and not self.at_eof():
  298. over_chunk_size = 4 - remainder
  299. over_chunk = b""
  300. if self._prev_chunk:
  301. over_chunk = self._prev_chunk[:over_chunk_size]
  302. self._prev_chunk = self._prev_chunk[len(over_chunk) :]
  303. if len(over_chunk) != over_chunk_size:
  304. over_chunk += await self._content.read(4 - len(over_chunk))
  305. if not over_chunk:
  306. self._at_eof = True
  307. stripped_chunk += b"".join(over_chunk.split())
  308. chunk += over_chunk
  309. remainder = len(stripped_chunk) % 4
  310. self._read_bytes += len(chunk)
  311. if self._read_bytes == self._length:
  312. self._at_eof = True
  313. if self._at_eof and await self._content.readline() != b"\r\n":
  314. raise ValueError("Reader did not read all the data or it is malformed")
  315. return chunk
  316. async def _read_chunk_from_length(self, size: int) -> bytes:
  317. # Reads body part content chunk of the specified size.
  318. # The body part must has Content-Length header with proper value.
  319. assert self._length is not None, "Content-Length required for chunked read"
  320. chunk_size = min(size, self._length - self._read_bytes)
  321. chunk = await self._content.read(chunk_size)
  322. if self._content.at_eof():
  323. self._at_eof = True
  324. return chunk
  325. async def _read_chunk_from_stream(self, size: int) -> bytes:
  326. # Reads content chunk of body part with unknown length.
  327. # The Content-Length header for body part is not necessary.
  328. assert (
  329. size >= self._boundary_len
  330. ), "Chunk size must be greater or equal than boundary length + 2"
  331. first_chunk = self._prev_chunk is None
  332. if first_chunk:
  333. # We need to re-add the CRLF that got removed from headers parsing.
  334. self._prev_chunk = b"\r\n" + await self._content.read(size)
  335. chunk = b""
  336. # content.read() may return less than size, so we need to loop to ensure
  337. # we have enough data to detect the boundary.
  338. while len(chunk) < self._boundary_len:
  339. chunk += await self._content.read(size)
  340. self._content_eof += int(self._content.at_eof())
  341. if self._content_eof > 2:
  342. raise ValueError("Reading after EOF")
  343. if self._content_eof:
  344. break
  345. if len(chunk) > size:
  346. self._content.unread_data(chunk[size:])
  347. chunk = chunk[:size]
  348. assert self._prev_chunk is not None
  349. window = self._prev_chunk + chunk
  350. sub = b"\r\n" + self._boundary
  351. if first_chunk:
  352. idx = window.find(sub)
  353. else:
  354. idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub)))
  355. if idx >= 0:
  356. # pushing boundary back to content
  357. with warnings.catch_warnings():
  358. warnings.filterwarnings("ignore", category=DeprecationWarning)
  359. self._content.unread_data(window[idx:])
  360. self._prev_chunk = self._prev_chunk[:idx]
  361. chunk = window[len(self._prev_chunk) : idx]
  362. if not chunk:
  363. self._at_eof = True
  364. result = self._prev_chunk[2 if first_chunk else 0 :] # Strip initial CRLF
  365. self._prev_chunk = chunk
  366. return result
  367. async def readline(self) -> bytes:
  368. """Reads body part by line by line."""
  369. if self._at_eof:
  370. return b""
  371. if self._unread:
  372. line = self._unread.popleft()
  373. else:
  374. line = await self._content.readline()
  375. if line.startswith(self._boundary):
  376. # the very last boundary may not come with \r\n,
  377. # so set single rules for everyone
  378. sline = line.rstrip(b"\r\n")
  379. boundary = self._boundary
  380. last_boundary = self._boundary + b"--"
  381. # ensure that we read exactly the boundary, not something alike
  382. if sline == boundary or sline == last_boundary:
  383. self._at_eof = True
  384. self._unread.append(line)
  385. return b""
  386. else:
  387. next_line = await self._content.readline()
  388. if next_line.startswith(self._boundary):
  389. line = line[:-2] # strip CRLF but only once
  390. self._unread.append(next_line)
  391. return line
  392. async def release(self) -> None:
  393. """Like read(), but reads all the data to the void."""
  394. if self._at_eof:
  395. return
  396. while not self._at_eof:
  397. await self.read_chunk(self.chunk_size)
  398. async def text(self, *, encoding: Optional[str] = None) -> str:
  399. """Like read(), but assumes that body part contains text data."""
  400. data = await self.read(decode=True)
  401. # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm
  402. # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send
  403. encoding = encoding or self.get_charset(default="utf-8")
  404. return data.decode(encoding)
  405. async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]:
  406. """Like read(), but assumes that body parts contains JSON data."""
  407. data = await self.read(decode=True)
  408. if not data:
  409. return None
  410. encoding = encoding or self.get_charset(default="utf-8")
  411. return cast(Dict[str, Any], json.loads(data.decode(encoding)))
  412. async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]:
  413. """Like read(), but assumes that body parts contain form urlencoded data."""
  414. data = await self.read(decode=True)
  415. if not data:
  416. return []
  417. if encoding is not None:
  418. real_encoding = encoding
  419. else:
  420. real_encoding = self.get_charset(default="utf-8")
  421. try:
  422. decoded_data = data.rstrip().decode(real_encoding)
  423. except UnicodeDecodeError:
  424. raise ValueError("data cannot be decoded with %s encoding" % real_encoding)
  425. return parse_qsl(
  426. decoded_data,
  427. keep_blank_values=True,
  428. encoding=real_encoding,
  429. )
  430. def at_eof(self) -> bool:
  431. """Returns True if the boundary was reached or False otherwise."""
  432. return self._at_eof
  433. def _apply_content_transfer_decoding(self, data: bytes) -> bytes:
  434. """Apply Content-Transfer-Encoding decoding if header is present."""
  435. if CONTENT_TRANSFER_ENCODING in self.headers:
  436. return self._decode_content_transfer(data)
  437. return data
  438. def _needs_content_decoding(self) -> bool:
  439. """Check if Content-Encoding decoding should be applied."""
  440. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8
  441. return not self._is_form_data and CONTENT_ENCODING in self.headers
  442. def decode(self, data: bytes) -> bytes:
  443. """Decodes data synchronously.
  444. Decodes data according the specified Content-Encoding
  445. or Content-Transfer-Encoding headers value.
  446. Note: For large payloads, consider using decode_iter() instead
  447. to avoid blocking the event loop during decompression.
  448. """
  449. data = self._apply_content_transfer_decoding(data)
  450. if self._needs_content_decoding():
  451. return self._decode_content(data)
  452. return data
  453. async def decode_iter(self, data: bytes) -> AsyncIterator[bytes]:
  454. """Async generator that yields decoded data chunks.
  455. Decodes data according the specified Content-Encoding
  456. or Content-Transfer-Encoding headers value.
  457. This method offloads decompression to an executor for large payloads
  458. to avoid blocking the event loop.
  459. """
  460. data = self._apply_content_transfer_decoding(data)
  461. if self._needs_content_decoding():
  462. async for d in self._decode_content_async(data):
  463. yield d
  464. else:
  465. yield data
  466. def _decode_content(self, data: bytes) -> bytes:
  467. encoding = self.headers.get(CONTENT_ENCODING, "").lower()
  468. if encoding == "identity":
  469. return data
  470. if encoding in {"deflate", "gzip"}:
  471. return ZLibDecompressor(
  472. encoding=encoding,
  473. suppress_deflate_header=True,
  474. ).decompress_sync(data, max_length=self._max_decompress_size)
  475. raise RuntimeError(f"unknown content encoding: {encoding}")
  476. async def _decode_content_async(self, data: bytes) -> AsyncIterator[bytes]:
  477. encoding = self.headers.get(CONTENT_ENCODING, "").lower()
  478. if encoding == "identity":
  479. yield data
  480. elif encoding in {"deflate", "gzip"}:
  481. d = ZLibDecompressor(
  482. encoding=encoding,
  483. suppress_deflate_header=True,
  484. )
  485. yield await d.decompress(data, max_length=self._max_decompress_size)
  486. else:
  487. raise RuntimeError(f"unknown content encoding: {encoding}")
  488. def _decode_content_transfer(self, data: bytes) -> bytes:
  489. encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower()
  490. if encoding == "base64":
  491. return base64.b64decode(data)
  492. elif encoding == "quoted-printable":
  493. return binascii.a2b_qp(data)
  494. elif encoding in ("binary", "8bit", "7bit"):
  495. return data
  496. else:
  497. raise RuntimeError(f"unknown content transfer encoding: {encoding}")
  498. def get_charset(self, default: str) -> str:
  499. """Returns charset parameter from Content-Type header or default."""
  500. ctype = self.headers.get(CONTENT_TYPE, "")
  501. mimetype = parse_mimetype(ctype)
  502. return mimetype.parameters.get("charset", self._default_charset or default)
  503. @reify
  504. def name(self) -> Optional[str]:
  505. """Returns name specified in Content-Disposition header.
  506. If the header is missing or malformed, returns None.
  507. """
  508. _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION))
  509. return content_disposition_filename(params, "name")
  510. @reify
  511. def filename(self) -> Optional[str]:
  512. """Returns filename specified in Content-Disposition header.
  513. Returns None if the header is missing or malformed.
  514. """
  515. _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION))
  516. return content_disposition_filename(params, "filename")
  517. @payload_type(BodyPartReader, order=Order.try_first)
  518. class BodyPartReaderPayload(Payload):
  519. _value: BodyPartReader
  520. # _autoclose = False (inherited) - Streaming reader that may have resources
  521. def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None:
  522. super().__init__(value, *args, **kwargs)
  523. params: Dict[str, str] = {}
  524. if value.name is not None:
  525. params["name"] = value.name
  526. if value.filename is not None:
  527. params["filename"] = value.filename
  528. if params:
  529. self.set_content_disposition("attachment", True, **params)
  530. def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
  531. raise TypeError("Unable to decode.")
  532. async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
  533. """Raises TypeError as body parts should be consumed via write().
  534. This is intentional: BodyPartReader payloads are designed for streaming
  535. large data (potentially gigabytes) and must be consumed only once via
  536. the write() method to avoid memory exhaustion. They cannot be buffered
  537. in memory for reuse.
  538. """
  539. raise TypeError("Unable to read body part as bytes. Use write() to consume.")
  540. async def write(self, writer: AbstractStreamWriter) -> None:
  541. field = self._value
  542. while chunk := await field.read_chunk(size=2**18):
  543. async for d in field.decode_iter(chunk):
  544. await writer.write(d)
  545. class MultipartReader:
  546. """Multipart body reader."""
  547. #: Response wrapper, used when multipart readers constructs from response.
  548. response_wrapper_cls = MultipartResponseWrapper
  549. #: Multipart reader class, used to handle multipart/* body parts.
  550. #: None points to type(self)
  551. multipart_reader_cls: Optional[Type["MultipartReader"]] = None
  552. #: Body part reader class for non multipart/* content types.
  553. part_reader_cls = BodyPartReader
  554. def __init__(
  555. self,
  556. headers: Mapping[str, str],
  557. content: StreamReader,
  558. *,
  559. max_field_size: int = 8190,
  560. max_headers: int = 128,
  561. ) -> None:
  562. self._mimetype = parse_mimetype(headers[CONTENT_TYPE])
  563. assert self._mimetype.type == "multipart", "multipart/* content type expected"
  564. if "boundary" not in self._mimetype.parameters:
  565. raise ValueError(
  566. "boundary missed for Content-Type: %s" % headers[CONTENT_TYPE]
  567. )
  568. self.headers = headers
  569. self._boundary = ("--" + self._get_boundary()).encode()
  570. self._content = content
  571. self._default_charset: str | None = None
  572. self._last_part: MultipartReader | BodyPartReader | None = None
  573. self._max_field_size = max_field_size
  574. self._max_headers = max_headers
  575. self._at_eof = False
  576. self._at_bof = True
  577. self._unread: List[bytes] = []
  578. def __aiter__(self: Self) -> Self:
  579. return self
  580. async def __anext__(
  581. self,
  582. ) -> Optional[Union["MultipartReader", BodyPartReader]]:
  583. part = await self.next()
  584. if part is None:
  585. raise StopAsyncIteration
  586. return part
  587. @classmethod
  588. def from_response(
  589. cls,
  590. response: "ClientResponse",
  591. ) -> MultipartResponseWrapper:
  592. """Constructs reader instance from HTTP response.
  593. :param response: :class:`~aiohttp.client.ClientResponse` instance
  594. """
  595. obj = cls.response_wrapper_cls(
  596. response, cls(response.headers, response.content)
  597. )
  598. return obj
  599. def at_eof(self) -> bool:
  600. """Returns True if the final boundary was reached, false otherwise."""
  601. return self._at_eof
  602. async def next(
  603. self,
  604. ) -> Optional[Union["MultipartReader", BodyPartReader]]:
  605. """Emits the next multipart body part."""
  606. # So, if we're at BOF, we need to skip till the boundary.
  607. if self._at_eof:
  608. return None
  609. await self._maybe_release_last_part()
  610. if self._at_bof:
  611. await self._read_until_first_boundary()
  612. self._at_bof = False
  613. else:
  614. await self._read_boundary()
  615. if self._at_eof: # we just read the last boundary, nothing to do there
  616. return None
  617. part = await self.fetch_next_part()
  618. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.6
  619. if (
  620. self._last_part is None
  621. and self._mimetype.subtype == "form-data"
  622. and isinstance(part, BodyPartReader)
  623. ):
  624. _, params = parse_content_disposition(part.headers.get(CONTENT_DISPOSITION))
  625. if params.get("name") == "_charset_":
  626. # Longest encoding in https://encoding.spec.whatwg.org/encodings.json
  627. # is 19 characters, so 32 should be more than enough for any valid encoding.
  628. charset = await part.read_chunk(32)
  629. if len(charset) > 31:
  630. raise RuntimeError("Invalid default charset")
  631. self._default_charset = charset.strip().decode()
  632. part = await self.fetch_next_part()
  633. self._last_part = part
  634. return self._last_part
  635. async def release(self) -> None:
  636. """Reads all the body parts to the void till the final boundary."""
  637. while not self._at_eof:
  638. item = await self.next()
  639. if item is None:
  640. break
  641. await item.release()
  642. async def fetch_next_part(
  643. self,
  644. ) -> Union["MultipartReader", BodyPartReader]:
  645. """Returns the next body part reader."""
  646. headers = await self._read_headers()
  647. return self._get_part_reader(headers)
  648. def _get_part_reader(
  649. self,
  650. headers: "CIMultiDictProxy[str]",
  651. ) -> Union["MultipartReader", BodyPartReader]:
  652. """Dispatches the response by the `Content-Type` header.
  653. Returns a suitable reader instance.
  654. :param dict headers: Response headers
  655. """
  656. ctype = headers.get(CONTENT_TYPE, "")
  657. mimetype = parse_mimetype(ctype)
  658. if mimetype.type == "multipart":
  659. if self.multipart_reader_cls is None:
  660. return type(self)(headers, self._content)
  661. return self.multipart_reader_cls(
  662. headers,
  663. self._content,
  664. max_field_size=self._max_field_size,
  665. max_headers=self._max_headers,
  666. )
  667. else:
  668. return self.part_reader_cls(
  669. self._boundary,
  670. headers,
  671. self._content,
  672. subtype=self._mimetype.subtype,
  673. default_charset=self._default_charset,
  674. )
  675. def _get_boundary(self) -> str:
  676. boundary = self._mimetype.parameters["boundary"]
  677. if len(boundary) > 70:
  678. raise ValueError("boundary %r is too long (70 chars max)" % boundary)
  679. return boundary
  680. async def _readline(self) -> bytes:
  681. if self._unread:
  682. return self._unread.pop()
  683. return await self._content.readline()
  684. async def _read_until_first_boundary(self) -> None:
  685. while True:
  686. chunk = await self._readline()
  687. if chunk == b"":
  688. raise ValueError(
  689. "Could not find starting boundary %r" % (self._boundary)
  690. )
  691. chunk = chunk.rstrip()
  692. if chunk == self._boundary:
  693. return
  694. elif chunk == self._boundary + b"--":
  695. self._at_eof = True
  696. return
  697. async def _read_boundary(self) -> None:
  698. chunk = (await self._readline()).rstrip()
  699. if chunk == self._boundary:
  700. pass
  701. elif chunk == self._boundary + b"--":
  702. self._at_eof = True
  703. epilogue = await self._readline()
  704. next_line = await self._readline()
  705. # the epilogue is expected and then either the end of input or the
  706. # parent multipart boundary, if the parent boundary is found then
  707. # it should be marked as unread and handed to the parent for
  708. # processing
  709. if next_line[:2] == b"--":
  710. self._unread.append(next_line)
  711. # otherwise the request is likely missing an epilogue and both
  712. # lines should be passed to the parent for processing
  713. # (this handles the old behavior gracefully)
  714. else:
  715. self._unread.extend([next_line, epilogue])
  716. else:
  717. raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}")
  718. async def _read_headers(self) -> "CIMultiDictProxy[str]":
  719. lines = []
  720. while True:
  721. chunk = await self._content.readline(max_line_length=self._max_field_size)
  722. chunk = chunk.rstrip(b"\r\n")
  723. lines.append(chunk)
  724. if not chunk:
  725. break
  726. if len(lines) > self._max_headers:
  727. raise BadHttpMessage("Too many headers received")
  728. parser = HeadersParser(max_field_size=self._max_field_size)
  729. headers, raw_headers = parser.parse_headers(lines)
  730. return headers
  731. async def _maybe_release_last_part(self) -> None:
  732. """Ensures that the last read body part is read completely."""
  733. if self._last_part is not None:
  734. if not self._last_part.at_eof():
  735. await self._last_part.release()
  736. self._unread.extend(self._last_part._unread)
  737. self._last_part = None
  738. _Part = Tuple[Payload, str, str]
  739. class MultipartWriter(Payload):
  740. """Multipart body writer."""
  741. _value: None
  742. # _consumed = False (inherited) - Can be encoded multiple times
  743. _autoclose = True # No file handles, just collects parts in memory
  744. def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None:
  745. boundary = boundary if boundary is not None else uuid.uuid4().hex
  746. # The underlying Payload API demands a str (utf-8), not bytes,
  747. # so we need to ensure we don't lose anything during conversion.
  748. # As a result, require the boundary to be ASCII only.
  749. # In both situations.
  750. try:
  751. self._boundary = boundary.encode("ascii")
  752. except UnicodeEncodeError:
  753. raise ValueError("boundary should contain ASCII only chars") from None
  754. ctype = f"multipart/{subtype}; boundary={self._boundary_value}"
  755. super().__init__(None, content_type=ctype)
  756. self._parts: List[_Part] = []
  757. self._is_form_data = subtype == "form-data"
  758. def __enter__(self) -> "MultipartWriter":
  759. return self
  760. def __exit__(
  761. self,
  762. exc_type: Optional[Type[BaseException]],
  763. exc_val: Optional[BaseException],
  764. exc_tb: Optional[TracebackType],
  765. ) -> None:
  766. pass
  767. def __iter__(self) -> Iterator[_Part]:
  768. return iter(self._parts)
  769. def __len__(self) -> int:
  770. return len(self._parts)
  771. def __bool__(self) -> bool:
  772. return True
  773. _valid_tchar_regex = re.compile(rb"\A[!#$%&'*+\-.^_`|~\w]+\Z")
  774. _invalid_qdtext_char_regex = re.compile(rb"[\x00-\x08\x0A-\x1F\x7F]")
  775. @property
  776. def _boundary_value(self) -> str:
  777. """Wrap boundary parameter value in quotes, if necessary.
  778. Reads self.boundary and returns a unicode string.
  779. """
  780. # Refer to RFCs 7231, 7230, 5234.
  781. #
  782. # parameter = token "=" ( token / quoted-string )
  783. # token = 1*tchar
  784. # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
  785. # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
  786. # obs-text = %x80-FF
  787. # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
  788. # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
  789. # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
  790. # / DIGIT / ALPHA
  791. # ; any VCHAR, except delimiters
  792. # VCHAR = %x21-7E
  793. value = self._boundary
  794. if re.match(self._valid_tchar_regex, value):
  795. return value.decode("ascii") # cannot fail
  796. if re.search(self._invalid_qdtext_char_regex, value):
  797. raise ValueError("boundary value contains invalid characters")
  798. # escape %x5C and %x22
  799. quoted_value_content = value.replace(b"\\", b"\\\\")
  800. quoted_value_content = quoted_value_content.replace(b'"', b'\\"')
  801. return '"' + quoted_value_content.decode("ascii") + '"'
  802. @property
  803. def boundary(self) -> str:
  804. return self._boundary.decode("ascii")
  805. def append(self, obj: Any, headers: Optional[Mapping[str, str]] = None) -> Payload:
  806. if headers is None:
  807. headers = CIMultiDict()
  808. if isinstance(obj, Payload):
  809. obj.headers.update(headers)
  810. return self.append_payload(obj)
  811. else:
  812. try:
  813. payload = get_payload(obj, headers=headers)
  814. except LookupError:
  815. raise TypeError("Cannot create payload from %r" % obj)
  816. else:
  817. return self.append_payload(payload)
  818. def append_payload(self, payload: Payload) -> Payload:
  819. """Adds a new body part to multipart writer."""
  820. encoding: Optional[str] = None
  821. te_encoding: Optional[str] = None
  822. if self._is_form_data:
  823. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.7
  824. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8
  825. assert (
  826. not {CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TRANSFER_ENCODING}
  827. & payload.headers.keys()
  828. )
  829. # Set default Content-Disposition in case user doesn't create one
  830. if CONTENT_DISPOSITION not in payload.headers:
  831. name = f"section-{len(self._parts)}"
  832. payload.set_content_disposition("form-data", name=name)
  833. else:
  834. # compression
  835. encoding = payload.headers.get(CONTENT_ENCODING, "").lower()
  836. if encoding and encoding not in ("deflate", "gzip", "identity"):
  837. raise RuntimeError(f"unknown content encoding: {encoding}")
  838. if encoding == "identity":
  839. encoding = None
  840. # te encoding
  841. te_encoding = payload.headers.get(CONTENT_TRANSFER_ENCODING, "").lower()
  842. if te_encoding not in ("", "base64", "quoted-printable", "binary"):
  843. raise RuntimeError(f"unknown content transfer encoding: {te_encoding}")
  844. if te_encoding == "binary":
  845. te_encoding = None
  846. # size
  847. size = payload.size
  848. if size is not None and not (encoding or te_encoding):
  849. payload.headers[CONTENT_LENGTH] = str(size)
  850. self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type]
  851. return payload
  852. def append_json(
  853. self, obj: Any, headers: Optional[Mapping[str, str]] = None
  854. ) -> Payload:
  855. """Helper to append JSON part."""
  856. if headers is None:
  857. headers = CIMultiDict()
  858. return self.append_payload(JsonPayload(obj, headers=headers))
  859. def append_form(
  860. self,
  861. obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]],
  862. headers: Optional[Mapping[str, str]] = None,
  863. ) -> Payload:
  864. """Helper to append form urlencoded part."""
  865. assert isinstance(obj, (Sequence, Mapping))
  866. if headers is None:
  867. headers = CIMultiDict()
  868. if isinstance(obj, Mapping):
  869. obj = list(obj.items())
  870. data = urlencode(obj, doseq=True)
  871. return self.append_payload(
  872. StringPayload(
  873. data, headers=headers, content_type="application/x-www-form-urlencoded"
  874. )
  875. )
  876. @property
  877. def size(self) -> Optional[int]:
  878. """Size of the payload."""
  879. total = 0
  880. for part, encoding, te_encoding in self._parts:
  881. part_size = part.size
  882. if encoding or te_encoding or part_size is None:
  883. return None
  884. total += int(
  885. 2
  886. + len(self._boundary)
  887. + 2
  888. + part_size # b'--'+self._boundary+b'\r\n'
  889. + len(part._binary_headers)
  890. + 2 # b'\r\n'
  891. )
  892. total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n'
  893. return total
  894. def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
  895. """Return string representation of the multipart data.
  896. WARNING: This method may do blocking I/O if parts contain file payloads.
  897. It should not be called in the event loop. Use as_bytes().decode() instead.
  898. """
  899. return "".join(
  900. "--"
  901. + self.boundary
  902. + "\r\n"
  903. + part._binary_headers.decode(encoding, errors)
  904. + part.decode()
  905. for part, _e, _te in self._parts
  906. )
  907. async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes:
  908. """Return bytes representation of the multipart data.
  909. This method is async-safe and calls as_bytes on underlying payloads.
  910. """
  911. parts: List[bytes] = []
  912. # Process each part
  913. for part, _e, _te in self._parts:
  914. # Add boundary
  915. parts.append(b"--" + self._boundary + b"\r\n")
  916. # Add headers
  917. parts.append(part._binary_headers)
  918. # Add payload content using as_bytes for async safety
  919. part_bytes = await part.as_bytes(encoding, errors)
  920. parts.append(part_bytes)
  921. # Add trailing CRLF
  922. parts.append(b"\r\n")
  923. # Add closing boundary
  924. parts.append(b"--" + self._boundary + b"--\r\n")
  925. return b"".join(parts)
  926. async def write(
  927. self, writer: AbstractStreamWriter, close_boundary: bool = True
  928. ) -> None:
  929. """Write body."""
  930. for part, encoding, te_encoding in self._parts:
  931. if self._is_form_data:
  932. # https://datatracker.ietf.org/doc/html/rfc7578#section-4.2
  933. assert CONTENT_DISPOSITION in part.headers
  934. assert "name=" in part.headers[CONTENT_DISPOSITION]
  935. await writer.write(b"--" + self._boundary + b"\r\n")
  936. await writer.write(part._binary_headers)
  937. if encoding or te_encoding:
  938. w = MultipartPayloadWriter(writer)
  939. if encoding:
  940. w.enable_compression(encoding)
  941. if te_encoding:
  942. w.enable_encoding(te_encoding)
  943. await part.write(w) # type: ignore[arg-type]
  944. await w.write_eof()
  945. else:
  946. await part.write(writer)
  947. await writer.write(b"\r\n")
  948. if close_boundary:
  949. await writer.write(b"--" + self._boundary + b"--\r\n")
  950. async def close(self) -> None:
  951. """
  952. Close all part payloads that need explicit closing.
  953. IMPORTANT: This method must not await anything that might not finish
  954. immediately, as it may be called during cleanup/cancellation. Schedule
  955. any long-running operations without awaiting them.
  956. """
  957. if self._consumed:
  958. return
  959. self._consumed = True
  960. # Close all parts that need explicit closing
  961. # We catch and log exceptions to ensure all parts get a chance to close
  962. # we do not use asyncio.gather() here because we are not allowed
  963. # to suspend given we may be called during cleanup
  964. for idx, (part, _, _) in enumerate(self._parts):
  965. if not part.autoclose and not part.consumed:
  966. try:
  967. await part.close()
  968. except Exception as exc:
  969. internal_logger.error(
  970. "Failed to close multipart part %d: %s", idx, exc, exc_info=True
  971. )
  972. class MultipartPayloadWriter:
  973. def __init__(self, writer: AbstractStreamWriter) -> None:
  974. self._writer = writer
  975. self._encoding: Optional[str] = None
  976. self._compress: Optional[ZLibCompressor] = None
  977. self._encoding_buffer: Optional[bytearray] = None
  978. def enable_encoding(self, encoding: str) -> None:
  979. if encoding == "base64":
  980. self._encoding = encoding
  981. self._encoding_buffer = bytearray()
  982. elif encoding == "quoted-printable":
  983. self._encoding = "quoted-printable"
  984. def enable_compression(
  985. self, encoding: str = "deflate", strategy: Optional[int] = None
  986. ) -> None:
  987. self._compress = ZLibCompressor(
  988. encoding=encoding,
  989. suppress_deflate_header=True,
  990. strategy=strategy,
  991. )
  992. async def write_eof(self) -> None:
  993. if self._compress is not None:
  994. chunk = self._compress.flush()
  995. if chunk:
  996. self._compress = None
  997. await self.write(chunk)
  998. if self._encoding == "base64":
  999. if self._encoding_buffer:
  1000. await self._writer.write(base64.b64encode(self._encoding_buffer))
  1001. async def write(self, chunk: bytes) -> None:
  1002. if self._compress is not None:
  1003. if chunk:
  1004. chunk = await self._compress.compress(chunk)
  1005. if not chunk:
  1006. return
  1007. if self._encoding == "base64":
  1008. buf = self._encoding_buffer
  1009. assert buf is not None
  1010. buf.extend(chunk)
  1011. if buf:
  1012. div, mod = divmod(len(buf), 3)
  1013. enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :])
  1014. if enc_chunk:
  1015. b64chunk = base64.b64encode(enc_chunk)
  1016. await self._writer.write(b64chunk)
  1017. elif self._encoding == "quoted-printable":
  1018. await self._writer.write(binascii.b2a_qp(chunk))
  1019. else:
  1020. await self._writer.write(chunk)