You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

937 lines
32 KiB

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