response.py 44 KB

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