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.

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