response.py 44 KB

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