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.
 
 
 
 

1308 line
45 KiB

  1. from __future__ import annotations
  2. import collections
  3. import io
  4. import json as _json
  5. import logging
  6. import re
  7. import socket
  8. import sys
  9. import typing
  10. import warnings
  11. import zlib
  12. from contextlib import contextmanager
  13. from http.client import HTTPMessage as _HttplibHTTPMessage
  14. from http.client import HTTPResponse as _HttplibHTTPResponse
  15. from socket import timeout as SocketTimeout
  16. if typing.TYPE_CHECKING:
  17. from ._base_connection import BaseHTTPConnection
  18. try:
  19. try:
  20. import brotlicffi as brotli # type: ignore[import-not-found]
  21. except ImportError:
  22. import brotli # type: ignore[import-not-found]
  23. except ImportError:
  24. brotli = None
  25. from . import util
  26. from ._base_connection import _TYPE_BODY
  27. from ._collections import HTTPHeaderDict
  28. from .connection import BaseSSLError, HTTPConnection, HTTPException
  29. from .exceptions import (
  30. BodyNotHttplibCompatible,
  31. DecodeError,
  32. HTTPError,
  33. IncompleteRead,
  34. InvalidChunkLength,
  35. InvalidHeader,
  36. ProtocolError,
  37. ReadTimeoutError,
  38. ResponseNotChunked,
  39. SSLError,
  40. )
  41. from .util.response import is_fp_closed, is_response_to_head
  42. from .util.retry import Retry
  43. if typing.TYPE_CHECKING:
  44. from .connectionpool import HTTPConnectionPool
  45. log = logging.getLogger(__name__)
  46. class ContentDecoder:
  47. def decompress(self, data: bytes) -> bytes:
  48. raise NotImplementedError()
  49. def flush(self) -> bytes:
  50. raise NotImplementedError()
  51. class DeflateDecoder(ContentDecoder):
  52. def __init__(self) -> None:
  53. self._first_try = True
  54. self._data = b""
  55. self._obj = zlib.decompressobj()
  56. def decompress(self, data: bytes) -> bytes:
  57. if not data:
  58. return data
  59. if not self._first_try:
  60. return self._obj.decompress(data)
  61. self._data += data
  62. try:
  63. decompressed = self._obj.decompress(data)
  64. if decompressed:
  65. self._first_try = False
  66. self._data = None # type: ignore[assignment]
  67. return decompressed
  68. except zlib.error:
  69. self._first_try = False
  70. self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
  71. try:
  72. return self.decompress(self._data)
  73. finally:
  74. self._data = None # type: ignore[assignment]
  75. def flush(self) -> bytes:
  76. return self._obj.flush()
  77. class GzipDecoderState:
  78. FIRST_MEMBER = 0
  79. OTHER_MEMBERS = 1
  80. SWALLOW_DATA = 2
  81. class GzipDecoder(ContentDecoder):
  82. def __init__(self) -> None:
  83. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  84. self._state = GzipDecoderState.FIRST_MEMBER
  85. def decompress(self, data: bytes) -> bytes:
  86. ret = bytearray()
  87. if self._state == GzipDecoderState.SWALLOW_DATA or not data:
  88. return bytes(ret)
  89. while True:
  90. try:
  91. ret += self._obj.decompress(data)
  92. except zlib.error:
  93. previous_state = self._state
  94. # Ignore data after the first error
  95. self._state = GzipDecoderState.SWALLOW_DATA
  96. if previous_state == GzipDecoderState.OTHER_MEMBERS:
  97. # Allow trailing garbage acceptable in other gzip clients
  98. return bytes(ret)
  99. raise
  100. data = self._obj.unused_data
  101. if not data:
  102. return bytes(ret)
  103. self._state = GzipDecoderState.OTHER_MEMBERS
  104. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  105. def flush(self) -> bytes:
  106. return self._obj.flush()
  107. if brotli is not None:
  108. class BrotliDecoder(ContentDecoder):
  109. # Supports both 'brotlipy' and 'Brotli' packages
  110. # since they share an import name. The top branches
  111. # are for 'brotlipy' and bottom branches for 'Brotli'
  112. def __init__(self) -> None:
  113. self._obj = brotli.Decompressor()
  114. if hasattr(self._obj, "decompress"):
  115. setattr(self, "decompress", self._obj.decompress)
  116. else:
  117. setattr(self, "decompress", self._obj.process)
  118. def flush(self) -> bytes:
  119. if hasattr(self._obj, "flush"):
  120. return self._obj.flush() # type: ignore[no-any-return]
  121. return b""
  122. try:
  123. # Python 3.14+
  124. from compression import zstd # type: ignore[import-not-found] # noqa: F401
  125. HAS_ZSTD = True
  126. class ZstdDecoder(ContentDecoder):
  127. def __init__(self) -> None:
  128. self._obj = zstd.ZstdDecompressor()
  129. def decompress(self, data: bytes) -> bytes:
  130. if not data:
  131. return b""
  132. data_parts = [self._obj.decompress(data)]
  133. while self._obj.eof and self._obj.unused_data:
  134. unused_data = self._obj.unused_data
  135. self._obj = zstd.ZstdDecompressor()
  136. data_parts.append(self._obj.decompress(unused_data))
  137. return b"".join(data_parts)
  138. def flush(self) -> bytes:
  139. if not self._obj.eof:
  140. raise DecodeError("Zstandard data is incomplete")
  141. return b""
  142. except ImportError:
  143. try:
  144. # Python 3.13 and earlier require the 'zstandard' module.
  145. import zstandard as zstd
  146. # The package 'zstandard' added the 'eof' property starting
  147. # in v0.18.0 which we require to ensure a complete and
  148. # valid zstd stream was fed into the ZstdDecoder.
  149. # See: https://github.com/urllib3/urllib3/pull/2624
  150. _zstd_version = tuple(
  151. map(int, re.search(r"^([0-9]+)\.([0-9]+)", zstd.__version__).groups()) # type: ignore[union-attr]
  152. )
  153. if _zstd_version < (0, 18): # Defensive:
  154. raise ImportError("zstandard module doesn't have eof")
  155. except (AttributeError, ImportError, ValueError): # Defensive:
  156. HAS_ZSTD = False
  157. else:
  158. HAS_ZSTD = True
  159. class ZstdDecoder(ContentDecoder): # type: ignore[no-redef]
  160. def __init__(self) -> None:
  161. self._obj = zstd.ZstdDecompressor().decompressobj()
  162. def decompress(self, data: bytes) -> bytes:
  163. if not data:
  164. return b""
  165. data_parts = [self._obj.decompress(data)]
  166. while self._obj.eof and self._obj.unused_data:
  167. unused_data = self._obj.unused_data
  168. self._obj = zstd.ZstdDecompressor().decompressobj()
  169. data_parts.append(self._obj.decompress(unused_data))
  170. return b"".join(data_parts)
  171. def flush(self) -> bytes:
  172. ret = self._obj.flush() # note: this is a no-op
  173. if not self._obj.eof:
  174. raise DecodeError("Zstandard data is incomplete")
  175. return ret # type: ignore[no-any-return]
  176. class MultiDecoder(ContentDecoder):
  177. """
  178. From RFC7231:
  179. If one or more encodings have been applied to a representation, the
  180. sender that applied the encodings MUST generate a Content-Encoding
  181. header field that lists the content codings in the order in which
  182. they were applied.
  183. """
  184. def __init__(self, modes: str) -> None:
  185. self._decoders = [_get_decoder(m.strip()) for m in modes.split(",")]
  186. def flush(self) -> bytes:
  187. return self._decoders[0].flush()
  188. def decompress(self, data: bytes) -> bytes:
  189. for d in reversed(self._decoders):
  190. data = d.decompress(data)
  191. return data
  192. def _get_decoder(mode: str) -> ContentDecoder:
  193. if "," in mode:
  194. return MultiDecoder(mode)
  195. # According to RFC 9110 section 8.4.1.3, recipients should
  196. # consider x-gzip equivalent to gzip
  197. if mode in ("gzip", "x-gzip"):
  198. return GzipDecoder()
  199. if brotli is not None and mode == "br":
  200. return BrotliDecoder()
  201. if HAS_ZSTD and mode == "zstd":
  202. return ZstdDecoder()
  203. return DeflateDecoder()
  204. class BytesQueueBuffer:
  205. """Memory-efficient bytes buffer
  206. To return decoded data in read() and still follow the BufferedIOBase API, we need a
  207. buffer to always return the correct amount of bytes.
  208. This buffer should be filled using calls to put()
  209. Our maximum memory usage is determined by the sum of the size of:
  210. * self.buffer, which contains the full data
  211. * the largest chunk that we will copy in get()
  212. The worst case scenario is a single chunk, in which case we'll make a full copy of
  213. the data inside get().
  214. """
  215. def __init__(self) -> None:
  216. self.buffer: typing.Deque[bytes] = collections.deque()
  217. self._size: int = 0
  218. def __len__(self) -> int:
  219. return self._size
  220. def put(self, data: bytes) -> None:
  221. self.buffer.append(data)
  222. self._size += len(data)
  223. def get(self, n: int) -> bytes:
  224. if n == 0:
  225. return b""
  226. elif not self.buffer:
  227. raise RuntimeError("buffer is empty")
  228. elif n < 0:
  229. raise ValueError("n should be > 0")
  230. fetched = 0
  231. ret = io.BytesIO()
  232. while fetched < n:
  233. remaining = n - fetched
  234. chunk = self.buffer.popleft()
  235. chunk_length = len(chunk)
  236. if remaining < chunk_length:
  237. left_chunk, right_chunk = chunk[:remaining], chunk[remaining:]
  238. ret.write(left_chunk)
  239. self.buffer.appendleft(right_chunk)
  240. self._size -= remaining
  241. break
  242. else:
  243. ret.write(chunk)
  244. self._size -= chunk_length
  245. fetched += chunk_length
  246. if not self.buffer:
  247. break
  248. return ret.getvalue()
  249. def get_all(self) -> bytes:
  250. buffer = self.buffer
  251. if not buffer:
  252. assert self._size == 0
  253. return b""
  254. if len(buffer) == 1:
  255. result = buffer.pop()
  256. else:
  257. ret = io.BytesIO()
  258. ret.writelines(buffer.popleft() for _ in range(len(buffer)))
  259. result = ret.getvalue()
  260. self._size = 0
  261. return result
  262. class BaseHTTPResponse(io.IOBase):
  263. CONTENT_DECODERS = ["gzip", "x-gzip", "deflate"]
  264. if brotli is not None:
  265. CONTENT_DECODERS += ["br"]
  266. if HAS_ZSTD:
  267. CONTENT_DECODERS += ["zstd"]
  268. REDIRECT_STATUSES = [301, 302, 303, 307, 308]
  269. DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (IOError, zlib.error)
  270. if brotli is not None:
  271. DECODER_ERROR_CLASSES += (brotli.error,)
  272. if HAS_ZSTD:
  273. DECODER_ERROR_CLASSES += (zstd.ZstdError,)
  274. def __init__(
  275. self,
  276. *,
  277. headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,
  278. status: int,
  279. version: int,
  280. version_string: str,
  281. reason: str | None,
  282. decode_content: bool,
  283. request_url: str | None,
  284. retries: Retry | None = None,
  285. ) -> None:
  286. if isinstance(headers, HTTPHeaderDict):
  287. self.headers = headers
  288. else:
  289. self.headers = HTTPHeaderDict(headers) # type: ignore[arg-type]
  290. self.status = status
  291. self.version = version
  292. self.version_string = version_string
  293. self.reason = reason
  294. self.decode_content = decode_content
  295. self._has_decoded_content = False
  296. self._request_url: str | None = request_url
  297. self.retries = retries
  298. self.chunked = False
  299. tr_enc = self.headers.get("transfer-encoding", "").lower()
  300. # Don't incur the penalty of creating a list and then discarding it
  301. encodings = (enc.strip() for enc in tr_enc.split(","))
  302. if "chunked" in encodings:
  303. self.chunked = True
  304. self._decoder: ContentDecoder | None = None
  305. self.length_remaining: int | None
  306. def get_redirect_location(self) -> str | None | typing.Literal[False]:
  307. """
  308. Should we redirect and where to?
  309. :returns: Truthy redirect location string if we got a redirect status
  310. code and valid location. ``None`` if redirect status and no
  311. location. ``False`` if not a redirect status code.
  312. """
  313. if self.status in self.REDIRECT_STATUSES:
  314. return self.headers.get("location")
  315. return False
  316. @property
  317. def data(self) -> bytes:
  318. raise NotImplementedError()
  319. def json(self) -> typing.Any:
  320. """
  321. Deserializes the body of the HTTP response as a Python object.
  322. The body of the HTTP response must be encoded using UTF-8, as per
  323. `RFC 8529 Section 8.1 <https://www.rfc-editor.org/rfc/rfc8259#section-8.1>`_.
  324. To use a custom JSON decoder pass the result of :attr:`HTTPResponse.data` to
  325. your custom decoder instead.
  326. If the body of the HTTP response is not decodable to UTF-8, a
  327. `UnicodeDecodeError` will be raised. If the body of the HTTP response is not a
  328. valid JSON document, a `json.JSONDecodeError` will be raised.
  329. Read more :ref:`here <json_content>`.
  330. :returns: The body of the HTTP response as a Python object.
  331. """
  332. data = self.data.decode("utf-8")
  333. return _json.loads(data)
  334. @property
  335. def url(self) -> str | None:
  336. raise NotImplementedError()
  337. @url.setter
  338. def url(self, url: str | None) -> None:
  339. raise NotImplementedError()
  340. @property
  341. def connection(self) -> BaseHTTPConnection | None:
  342. raise NotImplementedError()
  343. @property
  344. def retries(self) -> Retry | None:
  345. return self._retries
  346. @retries.setter
  347. def retries(self, retries: Retry | None) -> None:
  348. # Override the request_url if retries has a redirect location.
  349. if retries is not None and retries.history:
  350. self.url = retries.history[-1].redirect_location
  351. self._retries = retries
  352. def stream(
  353. self, amt: int | None = 2**16, decode_content: bool | None = None
  354. ) -> typing.Iterator[bytes]:
  355. raise NotImplementedError()
  356. def read(
  357. self,
  358. amt: int | None = None,
  359. decode_content: bool | None = None,
  360. cache_content: bool = False,
  361. ) -> bytes:
  362. raise NotImplementedError()
  363. def read1(
  364. self,
  365. amt: int | None = None,
  366. decode_content: bool | None = None,
  367. ) -> bytes:
  368. raise NotImplementedError()
  369. def read_chunked(
  370. self,
  371. amt: int | None = None,
  372. decode_content: bool | None = None,
  373. ) -> typing.Iterator[bytes]:
  374. raise NotImplementedError()
  375. def release_conn(self) -> None:
  376. raise NotImplementedError()
  377. def drain_conn(self) -> None:
  378. raise NotImplementedError()
  379. def shutdown(self) -> None:
  380. raise NotImplementedError()
  381. def close(self) -> None:
  382. raise NotImplementedError()
  383. def _init_decoder(self) -> None:
  384. """
  385. Set-up the _decoder attribute if necessary.
  386. """
  387. # Note: content-encoding value should be case-insensitive, per RFC 7230
  388. # Section 3.2
  389. content_encoding = self.headers.get("content-encoding", "").lower()
  390. if self._decoder is None:
  391. if content_encoding in self.CONTENT_DECODERS:
  392. self._decoder = _get_decoder(content_encoding)
  393. elif "," in content_encoding:
  394. encodings = [
  395. e.strip()
  396. for e in content_encoding.split(",")
  397. if e.strip() in self.CONTENT_DECODERS
  398. ]
  399. if encodings:
  400. self._decoder = _get_decoder(content_encoding)
  401. def _decode(
  402. self, data: bytes, decode_content: bool | None, flush_decoder: bool
  403. ) -> bytes:
  404. """
  405. Decode the data passed in and potentially flush the decoder.
  406. """
  407. if not decode_content:
  408. if self._has_decoded_content:
  409. raise RuntimeError(
  410. "Calling read(decode_content=False) is not supported after "
  411. "read(decode_content=True) was called."
  412. )
  413. return data
  414. try:
  415. if self._decoder:
  416. data = self._decoder.decompress(data)
  417. self._has_decoded_content = True
  418. except self.DECODER_ERROR_CLASSES as e:
  419. content_encoding = self.headers.get("content-encoding", "").lower()
  420. raise DecodeError(
  421. "Received response with content-encoding: %s, but "
  422. "failed to decode it." % content_encoding,
  423. e,
  424. ) from e
  425. if flush_decoder:
  426. data += self._flush_decoder()
  427. return data
  428. def _flush_decoder(self) -> bytes:
  429. """
  430. Flushes the decoder. Should only be called if the decoder is actually
  431. being used.
  432. """
  433. if self._decoder:
  434. return self._decoder.decompress(b"") + self._decoder.flush()
  435. return b""
  436. # Compatibility methods for `io` module
  437. def readinto(self, b: bytearray) -> int:
  438. temp = self.read(len(b))
  439. if len(temp) == 0:
  440. return 0
  441. else:
  442. b[: len(temp)] = temp
  443. return len(temp)
  444. # Compatibility methods for http.client.HTTPResponse
  445. def getheaders(self) -> HTTPHeaderDict:
  446. warnings.warn(
  447. "HTTPResponse.getheaders() is deprecated and will be removed "
  448. "in urllib3 v2.6.0. Instead access HTTPResponse.headers directly.",
  449. category=DeprecationWarning,
  450. stacklevel=2,
  451. )
  452. return self.headers
  453. def getheader(self, name: str, default: str | None = None) -> str | None:
  454. warnings.warn(
  455. "HTTPResponse.getheader() is deprecated and will be removed "
  456. "in urllib3 v2.6.0. Instead use HTTPResponse.headers.get(name, default).",
  457. category=DeprecationWarning,
  458. stacklevel=2,
  459. )
  460. return self.headers.get(name, default)
  461. # Compatibility method for http.cookiejar
  462. def info(self) -> HTTPHeaderDict:
  463. return self.headers
  464. def geturl(self) -> str | None:
  465. return self.url
  466. class HTTPResponse(BaseHTTPResponse):
  467. """
  468. HTTP Response container.
  469. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is
  470. loaded and decoded on-demand when the ``data`` property is accessed. This
  471. class is also compatible with the Python standard library's :mod:`io`
  472. module, and can hence be treated as a readable object in the context of that
  473. framework.
  474. Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:
  475. :param preload_content:
  476. If True, the response's body will be preloaded during construction.
  477. :param decode_content:
  478. If True, will attempt to decode the body based on the
  479. 'content-encoding' header.
  480. :param original_response:
  481. When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`
  482. object, it's convenient to include the original for debug purposes. It's
  483. otherwise unused.
  484. :param retries:
  485. The retries contains the last :class:`~urllib3.util.retry.Retry` that
  486. was used during the request.
  487. :param enforce_content_length:
  488. Enforce content length checking. Body returned by server must match
  489. value of Content-Length header, if present. Otherwise, raise error.
  490. """
  491. def __init__(
  492. self,
  493. body: _TYPE_BODY = "",
  494. headers: typing.Mapping[str, str] | typing.Mapping[bytes, bytes] | None = None,
  495. status: int = 0,
  496. version: int = 0,
  497. version_string: str = "HTTP/?",
  498. reason: str | None = None,
  499. preload_content: bool = True,
  500. decode_content: bool = True,
  501. original_response: _HttplibHTTPResponse | None = None,
  502. pool: HTTPConnectionPool | None = None,
  503. connection: HTTPConnection | None = None,
  504. msg: _HttplibHTTPMessage | None = None,
  505. retries: Retry | None = None,
  506. enforce_content_length: bool = True,
  507. request_method: str | None = None,
  508. request_url: str | None = None,
  509. auto_close: bool = True,
  510. sock_shutdown: typing.Callable[[int], None] | None = None,
  511. ) -> None:
  512. super().__init__(
  513. headers=headers,
  514. status=status,
  515. version=version,
  516. version_string=version_string,
  517. reason=reason,
  518. decode_content=decode_content,
  519. request_url=request_url,
  520. retries=retries,
  521. )
  522. self.enforce_content_length = enforce_content_length
  523. self.auto_close = auto_close
  524. self._body = None
  525. self._fp: _HttplibHTTPResponse | None = None
  526. self._original_response = original_response
  527. self._fp_bytes_read = 0
  528. self.msg = msg
  529. if body and isinstance(body, (str, bytes)):
  530. self._body = body
  531. self._pool = pool
  532. self._connection = connection
  533. if hasattr(body, "read"):
  534. self._fp = body # type: ignore[assignment]
  535. self._sock_shutdown = sock_shutdown
  536. # Are we using the chunked-style of transfer encoding?
  537. self.chunk_left: int | None = None
  538. # Determine length of response
  539. self.length_remaining = self._init_length(request_method)
  540. # Used to return the correct amount of bytes for partial read()s
  541. self._decoded_buffer = BytesQueueBuffer()
  542. # If requested, preload the body.
  543. if preload_content and not self._body:
  544. self._body = self.read(decode_content=decode_content)
  545. def release_conn(self) -> None:
  546. if not self._pool or not self._connection:
  547. return None
  548. self._pool._put_conn(self._connection)
  549. self._connection = None
  550. def drain_conn(self) -> None:
  551. """
  552. Read and discard any remaining HTTP response data in the response connection.
  553. Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
  554. """
  555. try:
  556. self.read()
  557. except (HTTPError, OSError, BaseSSLError, HTTPException):
  558. pass
  559. @property
  560. def data(self) -> bytes:
  561. # For backwards-compat with earlier urllib3 0.4 and earlier.
  562. if self._body:
  563. return self._body # type: ignore[return-value]
  564. if self._fp:
  565. return self.read(cache_content=True)
  566. return None # type: ignore[return-value]
  567. @property
  568. def connection(self) -> HTTPConnection | None:
  569. return self._connection
  570. def isclosed(self) -> bool:
  571. return is_fp_closed(self._fp)
  572. def tell(self) -> int:
  573. """
  574. Obtain the number of bytes pulled over the wire so far. May differ from
  575. the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
  576. if bytes are encoded on the wire (e.g, compressed).
  577. """
  578. return self._fp_bytes_read
  579. def _init_length(self, request_method: str | None) -> int | None:
  580. """
  581. Set initial length value for Response content if available.
  582. """
  583. length: int | None
  584. content_length: str | None = self.headers.get("content-length")
  585. if content_length is not None:
  586. if self.chunked:
  587. # This Response will fail with an IncompleteRead if it can't be
  588. # received as chunked. This method falls back to attempt reading
  589. # the response before raising an exception.
  590. log.warning(
  591. "Received response with both Content-Length and "
  592. "Transfer-Encoding set. This is expressly forbidden "
  593. "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
  594. "attempting to process response as Transfer-Encoding: "
  595. "chunked."
  596. )
  597. return None
  598. try:
  599. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  600. # be sent in a single Content-Length header
  601. # (e.g. Content-Length: 42, 42). This line ensures the values
  602. # are all valid ints and that as long as the `set` length is 1,
  603. # all values are the same. Otherwise, the header is invalid.
  604. lengths = {int(val) for val in content_length.split(",")}
  605. if len(lengths) > 1:
  606. raise InvalidHeader(
  607. "Content-Length contained multiple "
  608. "unmatching values (%s)" % content_length
  609. )
  610. length = lengths.pop()
  611. except ValueError:
  612. length = None
  613. else:
  614. if length < 0:
  615. length = None
  616. else: # if content_length is None
  617. length = None
  618. # Convert status to int for comparison
  619. # In some cases, httplib returns a status of "_UNKNOWN"
  620. try:
  621. status = int(self.status)
  622. except ValueError:
  623. status = 0
  624. # Check for responses that shouldn't include a body
  625. if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
  626. length = 0
  627. return length
  628. @contextmanager
  629. def _error_catcher(self) -> typing.Generator[None]:
  630. """
  631. Catch low-level python exceptions, instead re-raising urllib3
  632. variants, so that low-level exceptions are not leaked in the
  633. high-level api.
  634. On exit, release the connection back to the pool.
  635. """
  636. clean_exit = False
  637. try:
  638. try:
  639. yield
  640. except SocketTimeout as e:
  641. # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
  642. # there is yet no clean way to get at it from this context.
  643. raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type]
  644. except BaseSSLError as e:
  645. # FIXME: Is there a better way to differentiate between SSLErrors?
  646. if "read operation timed out" not in str(e):
  647. # SSL errors related to framing/MAC get wrapped and reraised here
  648. raise SSLError(e) from e
  649. raise ReadTimeoutError(self._pool, None, "Read timed out.") from e # type: ignore[arg-type]
  650. except IncompleteRead as e:
  651. if (
  652. e.expected is not None
  653. and e.partial is not None
  654. and e.expected == -e.partial
  655. ):
  656. arg = "Response may not contain content."
  657. else:
  658. arg = f"Connection broken: {e!r}"
  659. raise ProtocolError(arg, e) from e
  660. except (HTTPException, OSError) as e:
  661. raise ProtocolError(f"Connection broken: {e!r}", e) from e
  662. # If no exception is thrown, we should avoid cleaning up
  663. # unnecessarily.
  664. clean_exit = True
  665. finally:
  666. # If we didn't terminate cleanly, we need to throw away our
  667. # connection.
  668. if not clean_exit:
  669. # The response may not be closed but we're not going to use it
  670. # anymore so close it now to ensure that the connection is
  671. # released back to the pool.
  672. if self._original_response:
  673. self._original_response.close()
  674. # Closing the response may not actually be sufficient to close
  675. # everything, so if we have a hold of the connection close that
  676. # too.
  677. if self._connection:
  678. self._connection.close()
  679. # If we hold the original response but it's closed now, we should
  680. # return the connection back to the pool.
  681. if self._original_response and self._original_response.isclosed():
  682. self.release_conn()
  683. def _fp_read(
  684. self,
  685. amt: int | None = None,
  686. *,
  687. read1: bool = False,
  688. ) -> bytes:
  689. """
  690. Read a response with the thought that reading the number of bytes
  691. larger than can fit in a 32-bit int at a time via SSL in some
  692. known cases leads to an overflow error that has to be prevented
  693. if `amt` or `self.length_remaining` indicate that a problem may
  694. happen.
  695. The known cases:
  696. * CPython < 3.9.7 because of a bug
  697. https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.
  698. * urllib3 injected with pyOpenSSL-backed SSL-support.
  699. * CPython < 3.10 only when `amt` does not fit 32-bit int.
  700. """
  701. assert self._fp
  702. c_int_max = 2**31 - 1
  703. if (
  704. (amt and amt > c_int_max)
  705. or (
  706. amt is None
  707. and self.length_remaining
  708. and self.length_remaining > c_int_max
  709. )
  710. ) and (util.IS_PYOPENSSL or sys.version_info < (3, 10)):
  711. if read1:
  712. return self._fp.read1(c_int_max)
  713. buffer = io.BytesIO()
  714. # Besides `max_chunk_amt` being a maximum chunk size, it
  715. # affects memory overhead of reading a response by this
  716. # method in CPython.
  717. # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum
  718. # chunk size that does not lead to an overflow error, but
  719. # 256 MiB is a compromise.
  720. max_chunk_amt = 2**28
  721. while amt is None or amt != 0:
  722. if amt is not None:
  723. chunk_amt = min(amt, max_chunk_amt)
  724. amt -= chunk_amt
  725. else:
  726. chunk_amt = max_chunk_amt
  727. data = self._fp.read(chunk_amt)
  728. if not data:
  729. break
  730. buffer.write(data)
  731. del data # to reduce peak memory usage by `max_chunk_amt`.
  732. return buffer.getvalue()
  733. elif read1:
  734. return self._fp.read1(amt) if amt is not None else self._fp.read1()
  735. else:
  736. # StringIO doesn't like amt=None
  737. return self._fp.read(amt) if amt is not None else self._fp.read()
  738. def _raw_read(
  739. self,
  740. amt: int | None = None,
  741. *,
  742. read1: bool = False,
  743. ) -> bytes:
  744. """
  745. Reads `amt` of bytes from the socket.
  746. """
  747. if self._fp is None:
  748. return None # type: ignore[return-value]
  749. fp_closed = getattr(self._fp, "closed", False)
  750. with self._error_catcher():
  751. data = self._fp_read(amt, read1=read1) if not fp_closed else b""
  752. if amt is not None and amt != 0 and not data:
  753. # Platform-specific: Buggy versions of Python.
  754. # Close the connection when no data is returned
  755. #
  756. # This is redundant to what httplib/http.client _should_
  757. # already do. However, versions of python released before
  758. # December 15, 2012 (http://bugs.python.org/issue16298) do
  759. # not properly close the connection in all cases. There is
  760. # no harm in redundantly calling close.
  761. self._fp.close()
  762. if (
  763. self.enforce_content_length
  764. and self.length_remaining is not None
  765. and self.length_remaining != 0
  766. ):
  767. # This is an edge case that httplib failed to cover due
  768. # to concerns of backward compatibility. We're
  769. # addressing it here to make sure IncompleteRead is
  770. # raised during streaming, so all calls with incorrect
  771. # Content-Length are caught.
  772. raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  773. elif read1 and (
  774. (amt != 0 and not data) or self.length_remaining == len(data)
  775. ):
  776. # All data has been read, but `self._fp.read1` in
  777. # CPython 3.12 and older doesn't always close
  778. # `http.client.HTTPResponse`, so we close it here.
  779. # See https://github.com/python/cpython/issues/113199
  780. self._fp.close()
  781. if data:
  782. self._fp_bytes_read += len(data)
  783. if self.length_remaining is not None:
  784. self.length_remaining -= len(data)
  785. return data
  786. def read(
  787. self,
  788. amt: int | None = None,
  789. decode_content: bool | None = None,
  790. cache_content: bool = False,
  791. ) -> bytes:
  792. """
  793. Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
  794. parameters: ``decode_content`` and ``cache_content``.
  795. :param amt:
  796. How much of the content to read. If specified, caching is skipped
  797. because it doesn't make sense to cache partial content as the full
  798. response.
  799. :param decode_content:
  800. If True, will attempt to decode the body based on the
  801. 'content-encoding' header.
  802. :param cache_content:
  803. If True, will save the returned data such that the same result is
  804. returned despite of the state of the underlying file object. This
  805. is useful if you want the ``.data`` property to continue working
  806. after having ``.read()`` the file object. (Overridden if ``amt`` is
  807. set.)
  808. """
  809. self._init_decoder()
  810. if decode_content is None:
  811. decode_content = self.decode_content
  812. if amt and amt < 0:
  813. # Negative numbers and `None` should be treated the same.
  814. amt = None
  815. elif amt is not None:
  816. cache_content = False
  817. if len(self._decoded_buffer) >= amt:
  818. return self._decoded_buffer.get(amt)
  819. data = self._raw_read(amt)
  820. flush_decoder = amt is None or (amt != 0 and not data)
  821. if not data and len(self._decoded_buffer) == 0:
  822. return data
  823. if amt is None:
  824. data = self._decode(data, decode_content, flush_decoder)
  825. if cache_content:
  826. self._body = data
  827. else:
  828. # do not waste memory on buffer when not decoding
  829. if not decode_content:
  830. if self._has_decoded_content:
  831. raise RuntimeError(
  832. "Calling read(decode_content=False) is not supported after "
  833. "read(decode_content=True) was called."
  834. )
  835. return data
  836. decoded_data = self._decode(data, decode_content, flush_decoder)
  837. self._decoded_buffer.put(decoded_data)
  838. while len(self._decoded_buffer) < amt and data:
  839. # TODO make sure to initially read enough data to get past the headers
  840. # For example, the GZ file header takes 10 bytes, we don't want to read
  841. # it one byte at a time
  842. data = self._raw_read(amt)
  843. decoded_data = self._decode(data, decode_content, flush_decoder)
  844. self._decoded_buffer.put(decoded_data)
  845. data = self._decoded_buffer.get(amt)
  846. return data
  847. def read1(
  848. self,
  849. amt: int | None = None,
  850. decode_content: bool | None = None,
  851. ) -> bytes:
  852. """
  853. Similar to ``http.client.HTTPResponse.read1`` and documented
  854. in :meth:`io.BufferedReader.read1`, but with an additional parameter:
  855. ``decode_content``.
  856. :param amt:
  857. How much of the content to read.
  858. :param decode_content:
  859. If True, will attempt to decode the body based on the
  860. 'content-encoding' header.
  861. """
  862. if decode_content is None:
  863. decode_content = self.decode_content
  864. if amt and amt < 0:
  865. # Negative numbers and `None` should be treated the same.
  866. amt = None
  867. # try and respond without going to the network
  868. if self._has_decoded_content:
  869. if not decode_content:
  870. raise RuntimeError(
  871. "Calling read1(decode_content=False) is not supported after "
  872. "read1(decode_content=True) was called."
  873. )
  874. if len(self._decoded_buffer) > 0:
  875. if amt is None:
  876. return self._decoded_buffer.get_all()
  877. return self._decoded_buffer.get(amt)
  878. if amt == 0:
  879. return b""
  880. # FIXME, this method's type doesn't say returning None is possible
  881. data = self._raw_read(amt, read1=True)
  882. if not decode_content or data is None:
  883. return data
  884. self._init_decoder()
  885. while True:
  886. flush_decoder = not data
  887. decoded_data = self._decode(data, decode_content, flush_decoder)
  888. self._decoded_buffer.put(decoded_data)
  889. if decoded_data or flush_decoder:
  890. break
  891. data = self._raw_read(8192, read1=True)
  892. if amt is None:
  893. return self._decoded_buffer.get_all()
  894. return self._decoded_buffer.get(amt)
  895. def stream(
  896. self, amt: int | None = 2**16, decode_content: bool | None = None
  897. ) -> typing.Generator[bytes]:
  898. """
  899. A generator wrapper for the read() method. A call will block until
  900. ``amt`` bytes have been read from the connection or until the
  901. connection is closed.
  902. :param amt:
  903. How much of the content to read. The generator will return up to
  904. much data per iteration, but may return less. This is particularly
  905. likely when using compressed data. However, the empty string will
  906. never be returned.
  907. :param decode_content:
  908. If True, will attempt to decode the body based on the
  909. 'content-encoding' header.
  910. """
  911. if self.chunked and self.supports_chunked_reads():
  912. yield from self.read_chunked(amt, decode_content=decode_content)
  913. else:
  914. while not is_fp_closed(self._fp) or len(self._decoded_buffer) > 0:
  915. data = self.read(amt=amt, decode_content=decode_content)
  916. if data:
  917. yield data
  918. # Overrides from io.IOBase
  919. def readable(self) -> bool:
  920. return True
  921. def shutdown(self) -> None:
  922. if not self._sock_shutdown:
  923. raise ValueError("Cannot shutdown socket as self._sock_shutdown is not set")
  924. if self._connection is None:
  925. raise RuntimeError(
  926. "Cannot shutdown as connection has already been released to the pool"
  927. )
  928. self._sock_shutdown(socket.SHUT_RD)
  929. def close(self) -> None:
  930. self._sock_shutdown = None
  931. if not self.closed and self._fp:
  932. self._fp.close()
  933. if self._connection:
  934. self._connection.close()
  935. if not self.auto_close:
  936. io.IOBase.close(self)
  937. @property
  938. def closed(self) -> bool:
  939. if not self.auto_close:
  940. return io.IOBase.closed.__get__(self) # type: ignore[no-any-return]
  941. elif self._fp is None:
  942. return True
  943. elif hasattr(self._fp, "isclosed"):
  944. return self._fp.isclosed()
  945. elif hasattr(self._fp, "closed"):
  946. return self._fp.closed
  947. else:
  948. return True
  949. def fileno(self) -> int:
  950. if self._fp is None:
  951. raise OSError("HTTPResponse has no file to get a fileno from")
  952. elif hasattr(self._fp, "fileno"):
  953. return self._fp.fileno()
  954. else:
  955. raise OSError(
  956. "The file-like object this HTTPResponse is wrapped "
  957. "around has no file descriptor"
  958. )
  959. def flush(self) -> None:
  960. if (
  961. self._fp is not None
  962. and hasattr(self._fp, "flush")
  963. and not getattr(self._fp, "closed", False)
  964. ):
  965. return self._fp.flush()
  966. def supports_chunked_reads(self) -> bool:
  967. """
  968. Checks if the underlying file-like object looks like a
  969. :class:`http.client.HTTPResponse` object. We do this by testing for
  970. the fp attribute. If it is present we assume it returns raw chunks as
  971. processed by read_chunked().
  972. """
  973. return hasattr(self._fp, "fp")
  974. def _update_chunk_length(self) -> None:
  975. # First, we'll figure out length of a chunk and then
  976. # we'll try to read it from socket.
  977. if self.chunk_left is not None:
  978. return None
  979. line = self._fp.fp.readline() # type: ignore[union-attr]
  980. line = line.split(b";", 1)[0]
  981. try:
  982. self.chunk_left = int(line, 16)
  983. except ValueError:
  984. self.close()
  985. if line:
  986. # Invalid chunked protocol response, abort.
  987. raise InvalidChunkLength(self, line) from None
  988. else:
  989. # Truncated at start of next chunk
  990. raise ProtocolError("Response ended prematurely") from None
  991. def _handle_chunk(self, amt: int | None) -> bytes:
  992. returned_chunk = None
  993. if amt is None:
  994. chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr]
  995. returned_chunk = chunk
  996. self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
  997. self.chunk_left = None
  998. elif self.chunk_left is not None and amt < self.chunk_left:
  999. value = self._fp._safe_read(amt) # type: ignore[union-attr]
  1000. self.chunk_left = self.chunk_left - amt
  1001. returned_chunk = value
  1002. elif amt == self.chunk_left:
  1003. value = self._fp._safe_read(amt) # type: ignore[union-attr]
  1004. self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
  1005. self.chunk_left = None
  1006. returned_chunk = value
  1007. else: # amt > self.chunk_left
  1008. returned_chunk = self._fp._safe_read(self.chunk_left) # type: ignore[union-attr]
  1009. self._fp._safe_read(2) # type: ignore[union-attr] # Toss the CRLF at the end of the chunk.
  1010. self.chunk_left = None
  1011. return returned_chunk # type: ignore[no-any-return]
  1012. def read_chunked(
  1013. self, amt: int | None = None, decode_content: bool | None = None
  1014. ) -> typing.Generator[bytes]:
  1015. """
  1016. Similar to :meth:`HTTPResponse.read`, but with an additional
  1017. parameter: ``decode_content``.
  1018. :param amt:
  1019. How much of the content to read. If specified, caching is skipped
  1020. because it doesn't make sense to cache partial content as the full
  1021. response.
  1022. :param decode_content:
  1023. If True, will attempt to decode the body based on the
  1024. 'content-encoding' header.
  1025. """
  1026. self._init_decoder()
  1027. # FIXME: Rewrite this method and make it a class with a better structured logic.
  1028. if not self.chunked:
  1029. raise ResponseNotChunked(
  1030. "Response is not chunked. "
  1031. "Header 'transfer-encoding: chunked' is missing."
  1032. )
  1033. if not self.supports_chunked_reads():
  1034. raise BodyNotHttplibCompatible(
  1035. "Body should be http.client.HTTPResponse like. "
  1036. "It should have have an fp attribute which returns raw chunks."
  1037. )
  1038. with self._error_catcher():
  1039. # Don't bother reading the body of a HEAD request.
  1040. if self._original_response and is_response_to_head(self._original_response):
  1041. self._original_response.close()
  1042. return None
  1043. # If a response is already read and closed
  1044. # then return immediately.
  1045. if self._fp.fp is None: # type: ignore[union-attr]
  1046. return None
  1047. if amt and amt < 0:
  1048. # Negative numbers and `None` should be treated the same,
  1049. # but httplib handles only `None` correctly.
  1050. amt = None
  1051. while True:
  1052. self._update_chunk_length()
  1053. if self.chunk_left == 0:
  1054. break
  1055. chunk = self._handle_chunk(amt)
  1056. decoded = self._decode(
  1057. chunk, decode_content=decode_content, flush_decoder=False
  1058. )
  1059. if decoded:
  1060. yield decoded
  1061. if decode_content:
  1062. # On CPython and PyPy, we should never need to flush the
  1063. # decoder. However, on Jython we *might* need to, so
  1064. # lets defensively do it anyway.
  1065. decoded = self._flush_decoder()
  1066. if decoded: # Platform-specific: Jython.
  1067. yield decoded
  1068. # Chunk content ends with \r\n: discard it.
  1069. while self._fp is not None:
  1070. line = self._fp.fp.readline()
  1071. if not line:
  1072. # Some sites may not end with '\r\n'.
  1073. break
  1074. if line == b"\r\n":
  1075. break
  1076. # We read everything; close the "file".
  1077. if self._original_response:
  1078. self._original_response.close()
  1079. @property
  1080. def url(self) -> str | None:
  1081. """
  1082. Returns the URL that was the source of this response.
  1083. If the request that generated this response redirected, this method
  1084. will return the final redirect location.
  1085. """
  1086. return self._request_url
  1087. @url.setter
  1088. def url(self, url: str) -> None:
  1089. self._request_url = url
  1090. def __iter__(self) -> typing.Iterator[bytes]:
  1091. buffer: list[bytes] = []
  1092. for chunk in self.stream(decode_content=True):
  1093. if b"\n" in chunk:
  1094. chunks = chunk.split(b"\n")
  1095. yield b"".join(buffer) + chunks[0] + b"\n"
  1096. for x in chunks[1:-1]:
  1097. yield x + b"\n"
  1098. if chunks[-1]:
  1099. buffer = [chunks[-1]]
  1100. else:
  1101. buffer = []
  1102. else:
  1103. buffer.append(chunk)
  1104. if buffer:
  1105. yield b"".join(buffer)