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.

705 lines
25 KiB

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