response.py 39 KB

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