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 22KB

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