multipart.py 36 KB

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