response.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. from __future__ import absolute_import
  2. import io
  3. import logging
  4. import sys
  5. import warnings
  6. import zlib
  7. from contextlib import contextmanager
  8. from socket import error as SocketError
  9. from socket import timeout as SocketTimeout
  10. try:
  11. try:
  12. import brotlicffi as brotli
  13. except ImportError:
  14. import brotli
  15. except ImportError:
  16. brotli = None
  17. from . import util
  18. from ._collections import HTTPHeaderDict
  19. from .connection import BaseSSLError, HTTPException
  20. from .exceptions import (
  21. BodyNotHttplibCompatible,
  22. DecodeError,
  23. HTTPError,
  24. IncompleteRead,
  25. InvalidChunkLength,
  26. InvalidHeader,
  27. ProtocolError,
  28. ReadTimeoutError,
  29. ResponseNotChunked,
  30. SSLError,
  31. )
  32. from .packages import six
  33. from .util.response import is_fp_closed, is_response_to_head
  34. log = logging.getLogger(__name__)
  35. class DeflateDecoder(object):
  36. def __init__(self):
  37. self._first_try = True
  38. self._data = b""
  39. self._obj = zlib.decompressobj()
  40. def __getattr__(self, name):
  41. return getattr(self._obj, name)
  42. def decompress(self, data):
  43. if not data:
  44. return data
  45. if not self._first_try:
  46. return self._obj.decompress(data)
  47. self._data += data
  48. try:
  49. decompressed = self._obj.decompress(data)
  50. if decompressed:
  51. self._first_try = False
  52. self._data = None
  53. return decompressed
  54. except zlib.error:
  55. self._first_try = False
  56. self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
  57. try:
  58. return self.decompress(self._data)
  59. finally:
  60. self._data = None
  61. class GzipDecoderState(object):
  62. FIRST_MEMBER = 0
  63. OTHER_MEMBERS = 1
  64. SWALLOW_DATA = 2
  65. class GzipDecoder(object):
  66. def __init__(self):
  67. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  68. self._state = GzipDecoderState.FIRST_MEMBER
  69. def __getattr__(self, name):
  70. return getattr(self._obj, name)
  71. def decompress(self, data):
  72. ret = bytearray()
  73. if self._state == GzipDecoderState.SWALLOW_DATA or not data:
  74. return bytes(ret)
  75. while True:
  76. try:
  77. ret += self._obj.decompress(data)
  78. except zlib.error:
  79. previous_state = self._state
  80. # Ignore data after the first error
  81. self._state = GzipDecoderState.SWALLOW_DATA
  82. if previous_state == GzipDecoderState.OTHER_MEMBERS:
  83. # Allow trailing garbage acceptable in other gzip clients
  84. return bytes(ret)
  85. raise
  86. data = self._obj.unused_data
  87. if not data:
  88. return bytes(ret)
  89. self._state = GzipDecoderState.OTHER_MEMBERS
  90. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  91. if brotli is not None:
  92. class BrotliDecoder(object):
  93. # Supports both 'brotlipy' and 'Brotli' packages
  94. # since they share an import name. The top branches
  95. # are for 'brotlipy' and bottom branches for 'Brotli'
  96. def __init__(self):
  97. self._obj = brotli.Decompressor()
  98. if hasattr(self._obj, "decompress"):
  99. self.decompress = self._obj.decompress
  100. else:
  101. self.decompress = self._obj.process
  102. def flush(self):
  103. if hasattr(self._obj, "flush"):
  104. return self._obj.flush()
  105. return b""
  106. class MultiDecoder(object):
  107. """
  108. From RFC7231:
  109. If one or more encodings have been applied to a representation, the
  110. sender that applied the encodings MUST generate a Content-Encoding
  111. header field that lists the content codings in the order in which
  112. they were applied.
  113. """
  114. def __init__(self, modes):
  115. self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]
  116. def flush(self):
  117. return self._decoders[0].flush()
  118. def decompress(self, data):
  119. for d in reversed(self._decoders):
  120. data = d.decompress(data)
  121. return data
  122. def _get_decoder(mode):
  123. if "," in mode:
  124. return MultiDecoder(mode)
  125. if mode == "gzip":
  126. return GzipDecoder()
  127. if brotli is not None and mode == "br":
  128. return BrotliDecoder()
  129. return DeflateDecoder()
  130. class HTTPResponse(io.IOBase):
  131. """
  132. HTTP Response container.
  133. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is
  134. loaded and decoded on-demand when the ``data`` property is accessed. This
  135. class is also compatible with the Python standard library's :mod:`io`
  136. module, and can hence be treated as a readable object in the context of that
  137. framework.
  138. Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:
  139. :param preload_content:
  140. If True, the response's body will be preloaded during construction.
  141. :param decode_content:
  142. If True, will attempt to decode the body based on the
  143. 'content-encoding' header.
  144. :param original_response:
  145. When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`
  146. object, it's convenient to include the original for debug purposes. It's
  147. otherwise unused.
  148. :param retries:
  149. The retries contains the last :class:`~urllib3.util.retry.Retry` that
  150. was used during the request.
  151. :param enforce_content_length:
  152. Enforce content length checking. Body returned by server must match
  153. value of Content-Length header, if present. Otherwise, raise error.
  154. """
  155. CONTENT_DECODERS = ["gzip", "deflate"]
  156. if brotli is not None:
  157. CONTENT_DECODERS += ["br"]
  158. REDIRECT_STATUSES = [301, 302, 303, 307, 308]
  159. def __init__(
  160. self,
  161. body="",
  162. headers=None,
  163. status=0,
  164. version=0,
  165. reason=None,
  166. strict=0,
  167. preload_content=True,
  168. decode_content=True,
  169. original_response=None,
  170. pool=None,
  171. connection=None,
  172. msg=None,
  173. retries=None,
  174. enforce_content_length=False,
  175. request_method=None,
  176. request_url=None,
  177. auto_close=True,
  178. ):
  179. if isinstance(headers, HTTPHeaderDict):
  180. self.headers = headers
  181. else:
  182. self.headers = HTTPHeaderDict(headers)
  183. self.status = status
  184. self.version = version
  185. self.reason = reason
  186. self.strict = strict
  187. self.decode_content = decode_content
  188. self.retries = retries
  189. self.enforce_content_length = enforce_content_length
  190. self.auto_close = auto_close
  191. self._decoder = None
  192. self._body = None
  193. self._fp = None
  194. self._original_response = original_response
  195. self._fp_bytes_read = 0
  196. self.msg = msg
  197. self._request_url = request_url
  198. if body and isinstance(body, (six.string_types, bytes)):
  199. self._body = body
  200. self._pool = pool
  201. self._connection = connection
  202. if hasattr(body, "read"):
  203. self._fp = body
  204. # Are we using the chunked-style of transfer encoding?
  205. self.chunked = False
  206. self.chunk_left = None
  207. tr_enc = self.headers.get("transfer-encoding", "").lower()
  208. # Don't incur the penalty of creating a list and then discarding it
  209. encodings = (enc.strip() for enc in tr_enc.split(","))
  210. if "chunked" in encodings:
  211. self.chunked = True
  212. # Determine length of response
  213. self.length_remaining = self._init_length(request_method)
  214. # If requested, preload the body.
  215. if preload_content and not self._body:
  216. self._body = self.read(decode_content=decode_content)
  217. def get_redirect_location(self):
  218. """
  219. Should we redirect and where to?
  220. :returns: Truthy redirect location string if we got a redirect status
  221. code and valid location. ``None`` if redirect status and no
  222. location. ``False`` if not a redirect status code.
  223. """
  224. if self.status in self.REDIRECT_STATUSES:
  225. return self.headers.get("location")
  226. return False
  227. def release_conn(self):
  228. if not self._pool or not self._connection:
  229. return
  230. self._pool._put_conn(self._connection)
  231. self._connection = None
  232. def drain_conn(self):
  233. """
  234. Read and discard any remaining HTTP response data in the response connection.
  235. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
  236. """
  237. try:
  238. self.read()
  239. except (HTTPError, SocketError, BaseSSLError, HTTPException):
  240. pass
  241. @property
  242. def data(self):
  243. # For backwards-compat with earlier urllib3 0.4 and earlier.
  244. if self._body:
  245. return self._body
  246. if self._fp:
  247. return self.read(cache_content=True)
  248. @property
  249. def connection(self):
  250. return self._connection
  251. def isclosed(self):
  252. return is_fp_closed(self._fp)
  253. def tell(self):
  254. """
  255. Obtain the number of bytes pulled over the wire so far. May differ from
  256. the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
  257. if bytes are encoded on the wire (e.g, compressed).
  258. """
  259. return self._fp_bytes_read
  260. def _init_length(self, request_method):
  261. """
  262. Set initial length value for Response content if available.
  263. """
  264. length = self.headers.get("content-length")
  265. if length is not None:
  266. if self.chunked:
  267. # This Response will fail with an IncompleteRead if it can't be
  268. # received as chunked. This method falls back to attempt reading
  269. # the response before raising an exception.
  270. log.warning(
  271. "Received response with both Content-Length and "
  272. "Transfer-Encoding set. This is expressly forbidden "
  273. "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
  274. "attempting to process response as Transfer-Encoding: "
  275. "chunked."
  276. )
  277. return None
  278. try:
  279. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  280. # be sent in a single Content-Length header
  281. # (e.g. Content-Length: 42, 42). This line ensures the values
  282. # are all valid ints and that as long as the `set` length is 1,
  283. # all values are the same. Otherwise, the header is invalid.
  284. lengths = set([int(val) for val in length.split(",")])
  285. if len(lengths) > 1:
  286. raise InvalidHeader(
  287. "Content-Length contained multiple "
  288. "unmatching values (%s)" % length
  289. )
  290. length = lengths.pop()
  291. except ValueError:
  292. length = None
  293. else:
  294. if length < 0:
  295. length = None
  296. # Convert status to int for comparison
  297. # In some cases, httplib returns a status of "_UNKNOWN"
  298. try:
  299. status = int(self.status)
  300. except ValueError:
  301. status = 0
  302. # Check for responses that shouldn't include a body
  303. if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
  304. length = 0
  305. return length
  306. def _init_decoder(self):
  307. """
  308. Set-up the _decoder attribute if necessary.
  309. """
  310. # Note: content-encoding value should be case-insensitive, per RFC 7230
  311. # Section 3.2
  312. content_encoding = self.headers.get("content-encoding", "").lower()
  313. if self._decoder is None:
  314. if content_encoding in self.CONTENT_DECODERS:
  315. self._decoder = _get_decoder(content_encoding)
  316. elif "," in content_encoding:
  317. encodings = [
  318. e.strip()
  319. for e in content_encoding.split(",")
  320. if e.strip() in self.CONTENT_DECODERS
  321. ]
  322. if len(encodings):
  323. self._decoder = _get_decoder(content_encoding)
  324. DECODER_ERROR_CLASSES = (IOError, zlib.error)
  325. if brotli is not None:
  326. DECODER_ERROR_CLASSES += (brotli.error,)
  327. def _decode(self, data, decode_content, flush_decoder):
  328. """
  329. Decode the data passed in and potentially flush the decoder.
  330. """
  331. if not decode_content:
  332. return data
  333. try:
  334. if self._decoder:
  335. data = self._decoder.decompress(data)
  336. except self.DECODER_ERROR_CLASSES as e:
  337. content_encoding = self.headers.get("content-encoding", "").lower()
  338. raise DecodeError(
  339. "Received response with content-encoding: %s, but "
  340. "failed to decode it." % content_encoding,
  341. e,
  342. )
  343. if flush_decoder:
  344. data += self._flush_decoder()
  345. return data
  346. def _flush_decoder(self):
  347. """
  348. Flushes the decoder. Should only be called if the decoder is actually
  349. being used.
  350. """
  351. if self._decoder:
  352. buf = self._decoder.decompress(b"")
  353. return buf + self._decoder.flush()
  354. return b""
  355. @contextmanager
  356. def _error_catcher(self):
  357. """
  358. Catch low-level python exceptions, instead re-raising urllib3
  359. variants, so that low-level exceptions are not leaked in the
  360. high-level api.
  361. On exit, release the connection back to the pool.
  362. """
  363. clean_exit = False
  364. try:
  365. try:
  366. yield
  367. except SocketTimeout:
  368. # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
  369. # there is yet no clean way to get at it from this context.
  370. raise ReadTimeoutError(self._pool, None, "Read timed out.")
  371. except BaseSSLError as e:
  372. # FIXME: Is there a better way to differentiate between SSLErrors?
  373. if "read operation timed out" not in str(e):
  374. # SSL errors related to framing/MAC get wrapped and reraised here
  375. raise SSLError(e)
  376. raise ReadTimeoutError(self._pool, None, "Read timed out.")
  377. except (HTTPException, SocketError) as e:
  378. # This includes IncompleteRead.
  379. raise ProtocolError("Connection broken: %r" % e, e)
  380. # If no exception is thrown, we should avoid cleaning up
  381. # unnecessarily.
  382. clean_exit = True
  383. finally:
  384. # If we didn't terminate cleanly, we need to throw away our
  385. # connection.
  386. if not clean_exit:
  387. # The response may not be closed but we're not going to use it
  388. # anymore so close it now to ensure that the connection is
  389. # released back to the pool.
  390. if self._original_response:
  391. self._original_response.close()
  392. # Closing the response may not actually be sufficient to close
  393. # everything, so if we have a hold of the connection close that
  394. # too.
  395. if self._connection:
  396. self._connection.close()
  397. # If we hold the original response but it's closed now, we should
  398. # return the connection back to the pool.
  399. if self._original_response and self._original_response.isclosed():
  400. self.release_conn()
  401. def _fp_read(self, amt):
  402. """
  403. Read a response with the thought that reading the number of bytes
  404. larger than can fit in a 32-bit int at a time via SSL in some
  405. known cases leads to an overflow error that has to be prevented
  406. if `amt` or `self.length_remaining` indicate that a problem may
  407. happen.
  408. The known cases:
  409. * 3.8 <= CPython < 3.9.7 because of a bug
  410. https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.
  411. * urllib3 injected with pyOpenSSL-backed SSL-support.
  412. * CPython < 3.10 only when `amt` does not fit 32-bit int.
  413. """
  414. assert self._fp
  415. c_int_max = 2 ** 31 - 1
  416. if (
  417. (
  418. (amt and amt > c_int_max)
  419. or (self.length_remaining and self.length_remaining > c_int_max)
  420. )
  421. and not util.IS_SECURETRANSPORT
  422. and (util.IS_PYOPENSSL or sys.version_info < (3, 10))
  423. ):
  424. buffer = io.BytesIO()
  425. # Besides `max_chunk_amt` being a maximum chunk size, it
  426. # affects memory overhead of reading a response by this
  427. # method in CPython.
  428. # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum
  429. # chunk size that does not lead to an overflow error, but
  430. # 256 MiB is a compromise.
  431. max_chunk_amt = 2 ** 28
  432. while amt is None or amt != 0:
  433. if amt is not None:
  434. chunk_amt = min(amt, max_chunk_amt)
  435. amt -= chunk_amt
  436. else:
  437. chunk_amt = max_chunk_amt
  438. data = self._fp.read(chunk_amt)
  439. if not data:
  440. break
  441. buffer.write(data)
  442. del data # to reduce peak memory usage by `max_chunk_amt`.
  443. return buffer.getvalue()
  444. else:
  445. # StringIO doesn't like amt=None
  446. return self._fp.read(amt) if amt is not None else self._fp.read()
  447. def read(self, amt=None, decode_content=None, cache_content=False):
  448. """
  449. Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
  450. parameters: ``decode_content`` and ``cache_content``.
  451. :param amt:
  452. How much of the content to read. If specified, caching is skipped
  453. because it doesn't make sense to cache partial content as the full
  454. response.
  455. :param decode_content:
  456. If True, will attempt to decode the body based on the
  457. 'content-encoding' header.
  458. :param cache_content:
  459. If True, will save the returned data such that the same result is
  460. returned despite of the state of the underlying file object. This
  461. is useful if you want the ``.data`` property to continue working
  462. after having ``.read()`` the file object. (Overridden if ``amt`` is
  463. set.)
  464. """
  465. self._init_decoder()
  466. if decode_content is None:
  467. decode_content = self.decode_content
  468. if self._fp is None:
  469. return
  470. flush_decoder = False
  471. fp_closed = getattr(self._fp, "closed", False)
  472. with self._error_catcher():
  473. data = self._fp_read(amt) if not fp_closed else b""
  474. if amt is None:
  475. flush_decoder = True
  476. else:
  477. cache_content = False
  478. if (
  479. amt != 0 and not data
  480. ): # Platform-specific: Buggy versions of Python.
  481. # Close the connection when no data is returned
  482. #
  483. # This is redundant to what httplib/http.client _should_
  484. # already do. However, versions of python released before
  485. # December 15, 2012 (http://bugs.python.org/issue16298) do
  486. # not properly close the connection in all cases. There is
  487. # no harm in redundantly calling close.
  488. self._fp.close()
  489. flush_decoder = True
  490. if self.enforce_content_length and self.length_remaining not in (
  491. 0,
  492. None,
  493. ):
  494. # This is an edge case that httplib failed to cover due
  495. # to concerns of backward compatibility. We're
  496. # addressing it here to make sure IncompleteRead is
  497. # raised during streaming, so all calls with incorrect
  498. # Content-Length are caught.
  499. raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  500. if data:
  501. self._fp_bytes_read += len(data)
  502. if self.length_remaining is not None:
  503. self.length_remaining -= len(data)
  504. data = self._decode(data, decode_content, flush_decoder)
  505. if cache_content:
  506. self._body = data
  507. return data
  508. def stream(self, amt=2 ** 16, decode_content=None):
  509. """
  510. A generator wrapper for the read() method. A call will block until
  511. ``amt`` bytes have been read from the connection or until the
  512. connection is closed.
  513. :param amt:
  514. How much of the content to read. The generator will return up to
  515. much data per iteration, but may return less. This is particularly
  516. likely when using compressed data. However, the empty string will
  517. never be returned.
  518. :param decode_content:
  519. If True, will attempt to decode the body based on the
  520. 'content-encoding' header.
  521. """
  522. if self.chunked and self.supports_chunked_reads():
  523. for line in self.read_chunked(amt, decode_content=decode_content):
  524. yield line
  525. else:
  526. while not is_fp_closed(self._fp):
  527. data = self.read(amt=amt, decode_content=decode_content)
  528. if data:
  529. yield data
  530. @classmethod
  531. def from_httplib(ResponseCls, r, **response_kw):
  532. """
  533. Given an :class:`http.client.HTTPResponse` instance ``r``, return a
  534. corresponding :class:`urllib3.response.HTTPResponse` object.
  535. Remaining parameters are passed to the HTTPResponse constructor, along
  536. with ``original_response=r``.
  537. """
  538. headers = r.msg
  539. if not isinstance(headers, HTTPHeaderDict):
  540. if six.PY2:
  541. # Python 2.7
  542. headers = HTTPHeaderDict.from_httplib(headers)
  543. else:
  544. headers = HTTPHeaderDict(headers.items())
  545. # HTTPResponse objects in Python 3 don't have a .strict attribute
  546. strict = getattr(r, "strict", 0)
  547. resp = ResponseCls(
  548. body=r,
  549. headers=headers,
  550. status=r.status,
  551. version=r.version,
  552. reason=r.reason,
  553. strict=strict,
  554. original_response=r,
  555. **response_kw
  556. )
  557. return resp
  558. # Backwards-compatibility methods for http.client.HTTPResponse
  559. def getheaders(self):
  560. warnings.warn(
  561. "HTTPResponse.getheaders() is deprecated and will be removed "
  562. "in urllib3 v2.1.0. Instead access HTTPResponse.headers directly.",
  563. category=DeprecationWarning,
  564. stacklevel=2,
  565. )
  566. return self.headers
  567. def getheader(self, name, default=None):
  568. warnings.warn(
  569. "HTTPResponse.getheader() is deprecated and will be removed "
  570. "in urllib3 v2.1.0. Instead use HTTPResponse.headers.get(name, default).",
  571. category=DeprecationWarning,
  572. stacklevel=2,
  573. )
  574. return self.headers.get(name, default)
  575. # Backwards compatibility for http.cookiejar
  576. def info(self):
  577. return self.headers
  578. # Overrides from io.IOBase
  579. def close(self):
  580. if not self.closed:
  581. self._fp.close()
  582. if self._connection:
  583. self._connection.close()
  584. if not self.auto_close:
  585. io.IOBase.close(self)
  586. @property
  587. def closed(self):
  588. if not self.auto_close:
  589. return io.IOBase.closed.__get__(self)
  590. elif self._fp is None:
  591. return True
  592. elif hasattr(self._fp, "isclosed"):
  593. return self._fp.isclosed()
  594. elif hasattr(self._fp, "closed"):
  595. return self._fp.closed
  596. else:
  597. return True
  598. def fileno(self):
  599. if self._fp is None:
  600. raise IOError("HTTPResponse has no file to get a fileno from")
  601. elif hasattr(self._fp, "fileno"):
  602. return self._fp.fileno()
  603. else:
  604. raise IOError(
  605. "The file-like object this HTTPResponse is wrapped "
  606. "around has no file descriptor"
  607. )
  608. def flush(self):
  609. if (
  610. self._fp is not None
  611. and hasattr(self._fp, "flush")
  612. and not getattr(self._fp, "closed", False)
  613. ):
  614. return self._fp.flush()
  615. def readable(self):
  616. # This method is required for `io` module compatibility.
  617. return True
  618. def readinto(self, b):
  619. # This method is required for `io` module compatibility.
  620. temp = self.read(len(b))
  621. if len(temp) == 0:
  622. return 0
  623. else:
  624. b[: len(temp)] = temp
  625. return len(temp)
  626. def supports_chunked_reads(self):
  627. """
  628. Checks if the underlying file-like object looks like a
  629. :class:`http.client.HTTPResponse` object. We do this by testing for
  630. the fp attribute. If it is present we assume it returns raw chunks as
  631. processed by read_chunked().
  632. """
  633. return hasattr(self._fp, "fp")
  634. def _update_chunk_length(self):
  635. # First, we'll figure out length of a chunk and then
  636. # we'll try to read it from socket.
  637. if self.chunk_left is not None:
  638. return
  639. line = self._fp.fp.readline()
  640. line = line.split(b";", 1)[0]
  641. try:
  642. self.chunk_left = int(line, 16)
  643. except ValueError:
  644. # Invalid chunked protocol response, abort.
  645. self.close()
  646. raise InvalidChunkLength(self, line)
  647. def _handle_chunk(self, amt):
  648. returned_chunk = None
  649. if amt is None:
  650. chunk = self._fp._safe_read(self.chunk_left)
  651. returned_chunk = chunk
  652. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  653. self.chunk_left = None
  654. elif amt < self.chunk_left:
  655. value = self._fp._safe_read(amt)
  656. self.chunk_left = self.chunk_left - amt
  657. returned_chunk = value
  658. elif amt == self.chunk_left:
  659. value = self._fp._safe_read(amt)
  660. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  661. self.chunk_left = None
  662. returned_chunk = value
  663. else: # amt > self.chunk_left
  664. returned_chunk = self._fp._safe_read(self.chunk_left)
  665. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  666. self.chunk_left = None
  667. return returned_chunk
  668. def read_chunked(self, amt=None, decode_content=None):
  669. """
  670. Similar to :meth:`HTTPResponse.read`, but with an additional
  671. parameter: ``decode_content``.
  672. :param amt:
  673. How much of the content to read. If specified, caching is skipped
  674. because it doesn't make sense to cache partial content as the full
  675. response.
  676. :param decode_content:
  677. If True, will attempt to decode the body based on the
  678. 'content-encoding' header.
  679. """
  680. self._init_decoder()
  681. # FIXME: Rewrite this method and make it a class with a better structured logic.
  682. if not self.chunked:
  683. raise ResponseNotChunked(
  684. "Response is not chunked. "
  685. "Header 'transfer-encoding: chunked' is missing."
  686. )
  687. if not self.supports_chunked_reads():
  688. raise BodyNotHttplibCompatible(
  689. "Body should be http.client.HTTPResponse like. "
  690. "It should have have an fp attribute which returns raw chunks."
  691. )
  692. with self._error_catcher():
  693. # Don't bother reading the body of a HEAD request.
  694. if self._original_response and is_response_to_head(self._original_response):
  695. self._original_response.close()
  696. return
  697. # If a response is already read and closed
  698. # then return immediately.
  699. if self._fp.fp is None:
  700. return
  701. while True:
  702. self._update_chunk_length()
  703. if self.chunk_left == 0:
  704. break
  705. chunk = self._handle_chunk(amt)
  706. decoded = self._decode(
  707. chunk, decode_content=decode_content, flush_decoder=False
  708. )
  709. if decoded:
  710. yield decoded
  711. if decode_content:
  712. # On CPython and PyPy, we should never need to flush the
  713. # decoder. However, on Jython we *might* need to, so
  714. # lets defensively do it anyway.
  715. decoded = self._flush_decoder()
  716. if decoded: # Platform-specific: Jython.
  717. yield decoded
  718. # Chunk content ends with \r\n: discard it.
  719. while True:
  720. line = self._fp.fp.readline()
  721. if not line:
  722. # Some sites may not end with '\r\n'.
  723. break
  724. if line == b"\r\n":
  725. break
  726. # We read everything; close the "file".
  727. if self._original_response:
  728. self._original_response.close()
  729. def geturl(self):
  730. """
  731. Returns the URL that was the source of this response.
  732. If the request that generated this response redirected, this method
  733. will return the final redirect location.
  734. """
  735. if self.retries is not None and len(self.retries.history):
  736. return self.retries.history[-1].redirect_location
  737. else:
  738. return self._request_url
  739. def __iter__(self):
  740. buffer = []
  741. for chunk in self.stream(decode_content=True):
  742. if b"\n" in chunk:
  743. chunk = chunk.split(b"\n")
  744. yield b"".join(buffer) + chunk[0] + b"\n"
  745. for x in chunk[1:-1]:
  746. yield x + b"\n"
  747. if chunk[-1]:
  748. buffer = [chunk[-1]]
  749. else:
  750. buffer = []
  751. else:
  752. buffer.append(chunk)
  753. if buffer:
  754. yield b"".join(buffer)