response.py 53 KB

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