Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

response.py 39KB

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