response.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. # SPDX-License-Identifier: MIT
  2. from __future__ import absolute_import
  3. from contextlib import contextmanager
  4. import zlib
  5. import io
  6. import logging
  7. from socket import timeout as SocketTimeout
  8. from socket import error as SocketError
  9. from ._collections import HTTPHeaderDict
  10. from .exceptions import (
  11. BodyNotHttplibCompatible, ProtocolError, DecodeError, ReadTimeoutError,
  12. ResponseNotChunked, IncompleteRead, InvalidHeader
  13. )
  14. from .packages.six import string_types as basestring, binary_type, PY3
  15. from .packages.six.moves import http_client as httplib
  16. from .connection import HTTPException, BaseSSLError
  17. from .util.response import is_fp_closed, is_response_to_head
  18. log = logging.getLogger(__name__)
  19. class DeflateDecoder(object):
  20. def __init__(self):
  21. self._first_try = True
  22. self._data = binary_type()
  23. self._obj = zlib.decompressobj()
  24. def __getattr__(self, name):
  25. return getattr(self._obj, name)
  26. def decompress(self, data):
  27. if not data:
  28. return data
  29. if not self._first_try:
  30. return self._obj.decompress(data)
  31. self._data += data
  32. try:
  33. decompressed = self._obj.decompress(data)
  34. if decompressed:
  35. self._first_try = False
  36. self._data = None
  37. return decompressed
  38. except zlib.error:
  39. self._first_try = False
  40. self._obj = zlib.decompressobj(-zlib.MAX_WBITS)
  41. try:
  42. return self.decompress(self._data)
  43. finally:
  44. self._data = None
  45. class GzipDecoder(object):
  46. def __init__(self):
  47. self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)
  48. def __getattr__(self, name):
  49. return getattr(self._obj, name)
  50. def decompress(self, data):
  51. if not data:
  52. return data
  53. return self._obj.decompress(data)
  54. def _get_decoder(mode):
  55. if mode == 'gzip':
  56. return GzipDecoder()
  57. return DeflateDecoder()
  58. class HTTPResponse(io.IOBase):
  59. """
  60. HTTP Response container.
  61. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is
  62. loaded and decoded on-demand when the ``data`` property is accessed. This
  63. class is also compatible with the Python standard library's :mod:`io`
  64. module, and can hence be treated as a readable object in the context of that
  65. framework.
  66. Extra parameters for behaviour not present in httplib.HTTPResponse:
  67. :param preload_content:
  68. If True, the response's body will be preloaded during construction.
  69. :param decode_content:
  70. If True, attempts to decode specific content-encoding's based on headers
  71. (like 'gzip' and 'deflate') will be skipped and raw data will be used
  72. instead.
  73. :param original_response:
  74. When this HTTPResponse wrapper is generated from an httplib.HTTPResponse
  75. object, it's convenient to include the original for debug purposes. It's
  76. otherwise unused.
  77. :param retries:
  78. The retries contains the last :class:`~urllib3.util.retry.Retry` that
  79. was used during the request.
  80. :param enforce_content_length:
  81. Enforce content length checking. Body returned by server must match
  82. value of Content-Length header, if present. Otherwise, raise error.
  83. """
  84. CONTENT_DECODERS = ['gzip', 'deflate']
  85. REDIRECT_STATUSES = [301, 302, 303, 307, 308]
  86. def __init__(self, body='', headers=None, status=0, version=0, reason=None,
  87. strict=0, preload_content=True, decode_content=True,
  88. original_response=None, pool=None, connection=None,
  89. retries=None, enforce_content_length=False, request_method=None):
  90. if isinstance(headers, HTTPHeaderDict):
  91. self.headers = headers
  92. else:
  93. self.headers = HTTPHeaderDict(headers)
  94. self.status = status
  95. self.version = version
  96. self.reason = reason
  97. self.strict = strict
  98. self.decode_content = decode_content
  99. self.retries = retries
  100. self.enforce_content_length = enforce_content_length
  101. self._decoder = None
  102. self._body = None
  103. self._fp = None
  104. self._original_response = original_response
  105. self._fp_bytes_read = 0
  106. if body and isinstance(body, (basestring, binary_type)):
  107. self._body = body
  108. self._pool = pool
  109. self._connection = connection
  110. if hasattr(body, 'read'):
  111. self._fp = body
  112. # Are we using the chunked-style of transfer encoding?
  113. self.chunked = False
  114. self.chunk_left = None
  115. tr_enc = self.headers.get('transfer-encoding', '').lower()
  116. # Don't incur the penalty of creating a list and then discarding it
  117. encodings = (enc.strip() for enc in tr_enc.split(","))
  118. if "chunked" in encodings:
  119. self.chunked = True
  120. # Determine length of response
  121. self.length_remaining = self._init_length(request_method)
  122. # If requested, preload the body.
  123. if preload_content and not self._body:
  124. self._body = self.read(decode_content=decode_content)
  125. def get_redirect_location(self):
  126. """
  127. Should we redirect and where to?
  128. :returns: Truthy redirect location string if we got a redirect status
  129. code and valid location. ``None`` if redirect status and no
  130. location. ``False`` if not a redirect status code.
  131. """
  132. if self.status in self.REDIRECT_STATUSES:
  133. return self.headers.get('location')
  134. return False
  135. def release_conn(self):
  136. if not self._pool or not self._connection:
  137. return
  138. self._pool._put_conn(self._connection)
  139. self._connection = None
  140. @property
  141. def data(self):
  142. # For backwords-compat with earlier urllib3 0.4 and earlier.
  143. if self._body:
  144. return self._body
  145. if self._fp:
  146. return self.read(cache_content=True)
  147. @property
  148. def connection(self):
  149. return self._connection
  150. def tell(self):
  151. """
  152. Obtain the number of bytes pulled over the wire so far. May differ from
  153. the amount of content returned by :meth:``HTTPResponse.read`` if bytes
  154. are encoded on the wire (e.g, compressed).
  155. """
  156. return self._fp_bytes_read
  157. def _init_length(self, request_method):
  158. """
  159. Set initial length value for Response content if available.
  160. """
  161. length = self.headers.get('content-length')
  162. if length is not None and self.chunked:
  163. # This Response will fail with an IncompleteRead if it can't be
  164. # received as chunked. This method falls back to attempt reading
  165. # the response before raising an exception.
  166. log.warning("Received response with both Content-Length and "
  167. "Transfer-Encoding set. This is expressly forbidden "
  168. "by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
  169. "attempting to process response as Transfer-Encoding: "
  170. "chunked.")
  171. return None
  172. elif length is not None:
  173. try:
  174. # RFC 7230 section 3.3.2 specifies multiple content lengths can
  175. # be sent in a single Content-Length header
  176. # (e.g. Content-Length: 42, 42). This line ensures the values
  177. # are all valid ints and that as long as the `set` length is 1,
  178. # all values are the same. Otherwise, the header is invalid.
  179. lengths = set([int(val) for val in length.split(',')])
  180. if len(lengths) > 1:
  181. raise InvalidHeader("Content-Length contained multiple "
  182. "unmatching values (%s)" % length)
  183. length = lengths.pop()
  184. except ValueError:
  185. length = None
  186. else:
  187. if length < 0:
  188. length = None
  189. # Convert status to int for comparison
  190. # In some cases, httplib returns a status of "_UNKNOWN"
  191. try:
  192. status = int(self.status)
  193. except ValueError:
  194. status = 0
  195. # Check for responses that shouldn't include a body
  196. if status in (204, 304) or 100 <= status < 200 or request_method == 'HEAD':
  197. length = 0
  198. return length
  199. def _init_decoder(self):
  200. """
  201. Set-up the _decoder attribute if necessary.
  202. """
  203. # Note: content-encoding value should be case-insensitive, per RFC 7230
  204. # Section 3.2
  205. content_encoding = self.headers.get('content-encoding', '').lower()
  206. if self._decoder is None and content_encoding in self.CONTENT_DECODERS:
  207. self._decoder = _get_decoder(content_encoding)
  208. def _decode(self, data, decode_content, flush_decoder):
  209. """
  210. Decode the data passed in and potentially flush the decoder.
  211. """
  212. try:
  213. if decode_content and self._decoder:
  214. data = self._decoder.decompress(data)
  215. except (IOError, zlib.error) as e:
  216. content_encoding = self.headers.get('content-encoding', '').lower()
  217. raise DecodeError(
  218. "Received response with content-encoding: %s, but "
  219. "failed to decode it." % content_encoding, e)
  220. if flush_decoder and decode_content:
  221. data += self._flush_decoder()
  222. return data
  223. def _flush_decoder(self):
  224. """
  225. Flushes the decoder. Should only be called if the decoder is actually
  226. being used.
  227. """
  228. if self._decoder:
  229. buf = self._decoder.decompress(b'')
  230. return buf + self._decoder.flush()
  231. return b''
  232. @contextmanager
  233. def _error_catcher(self):
  234. """
  235. Catch low-level python exceptions, instead re-raising urllib3
  236. variants, so that low-level exceptions are not leaked in the
  237. high-level api.
  238. On exit, release the connection back to the pool.
  239. """
  240. clean_exit = False
  241. try:
  242. try:
  243. yield
  244. except SocketTimeout:
  245. # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
  246. # there is yet no clean way to get at it from this context.
  247. raise ReadTimeoutError(self._pool, None, 'Read timed out.')
  248. except BaseSSLError as e:
  249. # FIXME: Is there a better way to differentiate between SSLErrors?
  250. if 'read operation timed out' not in str(e): # Defensive:
  251. # This shouldn't happen but just in case we're missing an edge
  252. # case, let's avoid swallowing SSL errors.
  253. raise
  254. raise ReadTimeoutError(self._pool, None, 'Read timed out.')
  255. except (HTTPException, SocketError) as e:
  256. # This includes IncompleteRead.
  257. raise ProtocolError('Connection broken: %r' % e, e)
  258. # If no exception is thrown, we should avoid cleaning up
  259. # unnecessarily.
  260. clean_exit = True
  261. finally:
  262. # If we didn't terminate cleanly, we need to throw away our
  263. # connection.
  264. if not clean_exit:
  265. # The response may not be closed but we're not going to use it
  266. # anymore so close it now to ensure that the connection is
  267. # released back to the pool.
  268. if self._original_response:
  269. self._original_response.close()
  270. # Closing the response may not actually be sufficient to close
  271. # everything, so if we have a hold of the connection close that
  272. # too.
  273. if self._connection:
  274. self._connection.close()
  275. # If we hold the original response but it's closed now, we should
  276. # return the connection back to the pool.
  277. if self._original_response and self._original_response.isclosed():
  278. self.release_conn()
  279. def read(self, amt=None, decode_content=None, cache_content=False):
  280. """
  281. Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
  282. parameters: ``decode_content`` and ``cache_content``.
  283. :param amt:
  284. How much of the content to read. If specified, caching is skipped
  285. because it doesn't make sense to cache partial content as the full
  286. response.
  287. :param decode_content:
  288. If True, will attempt to decode the body based on the
  289. 'content-encoding' header.
  290. :param cache_content:
  291. If True, will save the returned data such that the same result is
  292. returned despite of the state of the underlying file object. This
  293. is useful if you want the ``.data`` property to continue working
  294. after having ``.read()`` the file object. (Overridden if ``amt`` is
  295. set.)
  296. """
  297. self._init_decoder()
  298. if decode_content is None:
  299. decode_content = self.decode_content
  300. if self._fp is None:
  301. return
  302. flush_decoder = False
  303. data = None
  304. with self._error_catcher():
  305. if amt is None:
  306. # cStringIO doesn't like amt=None
  307. data = self._fp.read()
  308. flush_decoder = True
  309. else:
  310. cache_content = False
  311. data = self._fp.read(amt)
  312. if amt != 0 and not data: # Platform-specific: Buggy versions of Python.
  313. # Close the connection when no data is returned
  314. #
  315. # This is redundant to what httplib/http.client _should_
  316. # already do. However, versions of python released before
  317. # December 15, 2012 (http://bugs.python.org/issue16298) do
  318. # not properly close the connection in all cases. There is
  319. # no harm in redundantly calling close.
  320. self._fp.close()
  321. flush_decoder = True
  322. if self.enforce_content_length and self.length_remaining not in (0, None):
  323. # This is an edge case that httplib failed to cover due
  324. # to concerns of backward compatibility. We're
  325. # addressing it here to make sure IncompleteRead is
  326. # raised during streaming, so all calls with incorrect
  327. # Content-Length are caught.
  328. raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
  329. if data:
  330. self._fp_bytes_read += len(data)
  331. if self.length_remaining is not None:
  332. self.length_remaining -= len(data)
  333. data = self._decode(data, decode_content, flush_decoder)
  334. if cache_content:
  335. self._body = data
  336. return data
  337. def stream(self, amt=2**16, decode_content=None):
  338. """
  339. A generator wrapper for the read() method. A call will block until
  340. ``amt`` bytes have been read from the connection or until the
  341. connection is closed.
  342. :param amt:
  343. How much of the content to read. The generator will return up to
  344. much data per iteration, but may return less. This is particularly
  345. likely when using compressed data. However, the empty string will
  346. never be returned.
  347. :param decode_content:
  348. If True, will attempt to decode the body based on the
  349. 'content-encoding' header.
  350. """
  351. if self.chunked and self.supports_chunked_reads():
  352. for line in self.read_chunked(amt, decode_content=decode_content):
  353. yield line
  354. else:
  355. while not is_fp_closed(self._fp):
  356. data = self.read(amt=amt, decode_content=decode_content)
  357. if data:
  358. yield data
  359. @classmethod
  360. def from_httplib(ResponseCls, r, **response_kw):
  361. """
  362. Given an :class:`httplib.HTTPResponse` instance ``r``, return a
  363. corresponding :class:`urllib3.response.HTTPResponse` object.
  364. Remaining parameters are passed to the HTTPResponse constructor, along
  365. with ``original_response=r``.
  366. """
  367. headers = r.msg
  368. if not isinstance(headers, HTTPHeaderDict):
  369. if PY3: # Python 3
  370. headers = HTTPHeaderDict(headers.items())
  371. else: # Python 2
  372. headers = HTTPHeaderDict.from_httplib(headers)
  373. # HTTPResponse objects in Python 3 don't have a .strict attribute
  374. strict = getattr(r, 'strict', 0)
  375. resp = ResponseCls(body=r,
  376. headers=headers,
  377. status=r.status,
  378. version=r.version,
  379. reason=r.reason,
  380. strict=strict,
  381. original_response=r,
  382. **response_kw)
  383. return resp
  384. # Backwards-compatibility methods for httplib.HTTPResponse
  385. def getheaders(self):
  386. return self.headers
  387. def getheader(self, name, default=None):
  388. return self.headers.get(name, default)
  389. # Overrides from io.IOBase
  390. def close(self):
  391. if not self.closed:
  392. self._fp.close()
  393. if self._connection:
  394. self._connection.close()
  395. @property
  396. def closed(self):
  397. if self._fp is None:
  398. return True
  399. elif hasattr(self._fp, 'isclosed'):
  400. return self._fp.isclosed()
  401. elif hasattr(self._fp, 'closed'):
  402. return self._fp.closed
  403. else:
  404. return True
  405. def fileno(self):
  406. if self._fp is None:
  407. raise IOError("HTTPResponse has no file to get a fileno from")
  408. elif hasattr(self._fp, "fileno"):
  409. return self._fp.fileno()
  410. else:
  411. raise IOError("The file-like object this HTTPResponse is wrapped "
  412. "around has no file descriptor")
  413. def flush(self):
  414. if self._fp is not None and hasattr(self._fp, 'flush'):
  415. return self._fp.flush()
  416. def readable(self):
  417. # This method is required for `io` module compatibility.
  418. return True
  419. def readinto(self, b):
  420. # This method is required for `io` module compatibility.
  421. temp = self.read(len(b))
  422. if len(temp) == 0:
  423. return 0
  424. else:
  425. b[:len(temp)] = temp
  426. return len(temp)
  427. def supports_chunked_reads(self):
  428. """
  429. Checks if the underlying file-like object looks like a
  430. httplib.HTTPResponse object. We do this by testing for the fp
  431. attribute. If it is present we assume it returns raw chunks as
  432. processed by read_chunked().
  433. """
  434. return hasattr(self._fp, 'fp')
  435. def _update_chunk_length(self):
  436. # First, we'll figure out length of a chunk and then
  437. # we'll try to read it from socket.
  438. if self.chunk_left is not None:
  439. return
  440. line = self._fp.fp.readline()
  441. line = line.split(b';', 1)[0]
  442. try:
  443. self.chunk_left = int(line, 16)
  444. except ValueError:
  445. # Invalid chunked protocol response, abort.
  446. self.close()
  447. raise httplib.IncompleteRead(line)
  448. def _handle_chunk(self, amt):
  449. returned_chunk = None
  450. if amt is None:
  451. chunk = self._fp._safe_read(self.chunk_left)
  452. returned_chunk = chunk
  453. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  454. self.chunk_left = None
  455. elif amt < self.chunk_left:
  456. value = self._fp._safe_read(amt)
  457. self.chunk_left = self.chunk_left - amt
  458. returned_chunk = value
  459. elif amt == self.chunk_left:
  460. value = self._fp._safe_read(amt)
  461. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  462. self.chunk_left = None
  463. returned_chunk = value
  464. else: # amt > self.chunk_left
  465. returned_chunk = self._fp._safe_read(self.chunk_left)
  466. self._fp._safe_read(2) # Toss the CRLF at the end of the chunk.
  467. self.chunk_left = None
  468. return returned_chunk
  469. def read_chunked(self, amt=None, decode_content=None):
  470. """
  471. Similar to :meth:`HTTPResponse.read`, but with an additional
  472. parameter: ``decode_content``.
  473. :param decode_content:
  474. If True, will attempt to decode the body based on the
  475. 'content-encoding' header.
  476. """
  477. self._init_decoder()
  478. # FIXME: Rewrite this method and make it a class with a better structured logic.
  479. if not self.chunked:
  480. raise ResponseNotChunked(
  481. "Response is not chunked. "
  482. "Header 'transfer-encoding: chunked' is missing.")
  483. if not self.supports_chunked_reads():
  484. raise BodyNotHttplibCompatible(
  485. "Body should be httplib.HTTPResponse like. "
  486. "It should have have an fp attribute which returns raw chunks.")
  487. # Don't bother reading the body of a HEAD request.
  488. if self._original_response and is_response_to_head(self._original_response):
  489. self._original_response.close()
  490. return
  491. with self._error_catcher():
  492. while True:
  493. self._update_chunk_length()
  494. if self.chunk_left == 0:
  495. break
  496. chunk = self._handle_chunk(amt)
  497. decoded = self._decode(chunk, decode_content=decode_content,
  498. flush_decoder=False)
  499. if decoded:
  500. yield decoded
  501. if decode_content:
  502. # On CPython and PyPy, we should never need to flush the
  503. # decoder. However, on Jython we *might* need to, so
  504. # lets defensively do it anyway.
  505. decoded = self._flush_decoder()
  506. if decoded: # Platform-specific: Jython.
  507. yield decoded
  508. # Chunk content ends with \r\n: discard it.
  509. while True:
  510. line = self._fp.fp.readline()
  511. if not line:
  512. # Some sites may not end with '\r\n'.
  513. break
  514. if line == b'\r\n':
  515. break
  516. # We read everything; close the "file".
  517. if self._original_response:
  518. self._original_response.close()