response.py 52 KB

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