adapters.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.adapters
  4. ~~~~~~~~~~~~~~~~~
  5. This module contains the transport adapters that Requests uses to define
  6. and maintain connections.
  7. """
  8. import os.path
  9. import socket
  10. from pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url
  11. from pip._vendor.urllib3.response import HTTPResponse
  12. from pip._vendor.urllib3.util import Timeout as TimeoutSauce
  13. from pip._vendor.urllib3.util.retry import Retry
  14. from pip._vendor.urllib3.exceptions import ClosedPoolError
  15. from pip._vendor.urllib3.exceptions import ConnectTimeoutError
  16. from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError
  17. from pip._vendor.urllib3.exceptions import MaxRetryError
  18. from pip._vendor.urllib3.exceptions import NewConnectionError
  19. from pip._vendor.urllib3.exceptions import ProxyError as _ProxyError
  20. from pip._vendor.urllib3.exceptions import ProtocolError
  21. from pip._vendor.urllib3.exceptions import ReadTimeoutError
  22. from pip._vendor.urllib3.exceptions import SSLError as _SSLError
  23. from pip._vendor.urllib3.exceptions import ResponseError
  24. from .models import Response
  25. from .compat import urlparse, basestring
  26. from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
  27. prepend_scheme_if_needed, get_auth_from_url, urldefragauth,
  28. select_proxy)
  29. from .structures import CaseInsensitiveDict
  30. from .cookies import extract_cookies_to_jar
  31. from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
  32. ProxyError, RetryError, InvalidSchema)
  33. from .auth import _basic_auth_str
  34. try:
  35. from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager
  36. except ImportError:
  37. def SOCKSProxyManager(*args, **kwargs):
  38. raise InvalidSchema("Missing dependencies for SOCKS support.")
  39. DEFAULT_POOLBLOCK = False
  40. DEFAULT_POOLSIZE = 10
  41. DEFAULT_RETRIES = 0
  42. DEFAULT_POOL_TIMEOUT = None
  43. class BaseAdapter(object):
  44. """The Base Transport Adapter"""
  45. def __init__(self):
  46. super(BaseAdapter, self).__init__()
  47. def send(self, request, stream=False, timeout=None, verify=True,
  48. cert=None, proxies=None):
  49. """Sends PreparedRequest object. Returns Response object.
  50. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  51. :param stream: (optional) Whether to stream the request content.
  52. :param timeout: (optional) How long to wait for the server to send
  53. data before giving up, as a float, or a :ref:`(connect timeout,
  54. read timeout) <timeouts>` tuple.
  55. :type timeout: float or tuple
  56. :param verify: (optional) Either a boolean, in which case it controls whether we verify
  57. the server's TLS certificate, or a string, in which case it must be a path
  58. to a CA bundle to use
  59. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  60. :param proxies: (optional) The proxies dictionary to apply to the request.
  61. """
  62. raise NotImplementedError
  63. def close(self):
  64. """Cleans up adapter specific items."""
  65. raise NotImplementedError
  66. class HTTPAdapter(BaseAdapter):
  67. """The built-in HTTP Adapter for urllib3.
  68. Provides a general-case interface for Requests sessions to contact HTTP and
  69. HTTPS urls by implementing the Transport Adapter interface. This class will
  70. usually be created by the :class:`Session <Session>` class under the
  71. covers.
  72. :param pool_connections: The number of urllib3 connection pools to cache.
  73. :param pool_maxsize: The maximum number of connections to save in the pool.
  74. :param max_retries: The maximum number of retries each connection
  75. should attempt. Note, this applies only to failed DNS lookups, socket
  76. connections and connection timeouts, never to requests where data has
  77. made it to the server. By default, Requests does not retry failed
  78. connections. If you need granular control over the conditions under
  79. which we retry a request, import urllib3's ``Retry`` class and pass
  80. that instead.
  81. :param pool_block: Whether the connection pool should block for connections.
  82. Usage::
  83. >>> import requests
  84. >>> s = requests.Session()
  85. >>> a = requests.adapters.HTTPAdapter(max_retries=3)
  86. >>> s.mount('http://', a)
  87. """
  88. __attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
  89. '_pool_block']
  90. def __init__(self, pool_connections=DEFAULT_POOLSIZE,
  91. pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
  92. pool_block=DEFAULT_POOLBLOCK):
  93. if max_retries == DEFAULT_RETRIES:
  94. self.max_retries = Retry(0, read=False)
  95. else:
  96. self.max_retries = Retry.from_int(max_retries)
  97. self.config = {}
  98. self.proxy_manager = {}
  99. super(HTTPAdapter, self).__init__()
  100. self._pool_connections = pool_connections
  101. self._pool_maxsize = pool_maxsize
  102. self._pool_block = pool_block
  103. self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
  104. def __getstate__(self):
  105. return dict((attr, getattr(self, attr, None)) for attr in
  106. self.__attrs__)
  107. def __setstate__(self, state):
  108. # Can't handle by adding 'proxy_manager' to self.__attrs__ because
  109. # self.poolmanager uses a lambda function, which isn't pickleable.
  110. self.proxy_manager = {}
  111. self.config = {}
  112. for attr, value in state.items():
  113. setattr(self, attr, value)
  114. self.init_poolmanager(self._pool_connections, self._pool_maxsize,
  115. block=self._pool_block)
  116. def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
  117. """Initializes a urllib3 PoolManager.
  118. This method should not be called from user code, and is only
  119. exposed for use when subclassing the
  120. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  121. :param connections: The number of urllib3 connection pools to cache.
  122. :param maxsize: The maximum number of connections to save in the pool.
  123. :param block: Block when no free connections are available.
  124. :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
  125. """
  126. # save these values for pickling
  127. self._pool_connections = connections
  128. self._pool_maxsize = maxsize
  129. self._pool_block = block
  130. self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
  131. block=block, strict=True, **pool_kwargs)
  132. def proxy_manager_for(self, proxy, **proxy_kwargs):
  133. """Return urllib3 ProxyManager for the given proxy.
  134. This method should not be called from user code, and is only
  135. exposed for use when subclassing the
  136. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  137. :param proxy: The proxy to return a urllib3 ProxyManager for.
  138. :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
  139. :returns: ProxyManager
  140. :rtype: urllib3.ProxyManager
  141. """
  142. if proxy in self.proxy_manager:
  143. manager = self.proxy_manager[proxy]
  144. elif proxy.lower().startswith('socks'):
  145. username, password = get_auth_from_url(proxy)
  146. manager = self.proxy_manager[proxy] = SOCKSProxyManager(
  147. proxy,
  148. username=username,
  149. password=password,
  150. num_pools=self._pool_connections,
  151. maxsize=self._pool_maxsize,
  152. block=self._pool_block,
  153. **proxy_kwargs
  154. )
  155. else:
  156. proxy_headers = self.proxy_headers(proxy)
  157. manager = self.proxy_manager[proxy] = proxy_from_url(
  158. proxy,
  159. proxy_headers=proxy_headers,
  160. num_pools=self._pool_connections,
  161. maxsize=self._pool_maxsize,
  162. block=self._pool_block,
  163. **proxy_kwargs)
  164. return manager
  165. def cert_verify(self, conn, url, verify, cert):
  166. """Verify a SSL certificate. This method should not be called from user
  167. code, and is only exposed for use when subclassing the
  168. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  169. :param conn: The urllib3 connection object associated with the cert.
  170. :param url: The requested URL.
  171. :param verify: Either a boolean, in which case it controls whether we verify
  172. the server's TLS certificate, or a string, in which case it must be a path
  173. to a CA bundle to use
  174. :param cert: The SSL certificate to verify.
  175. """
  176. if url.lower().startswith('https') and verify:
  177. cert_loc = None
  178. # Allow self-specified cert location.
  179. if verify is not True:
  180. cert_loc = verify
  181. if not cert_loc:
  182. cert_loc = DEFAULT_CA_BUNDLE_PATH
  183. if not cert_loc or not os.path.exists(cert_loc):
  184. raise IOError("Could not find a suitable TLS CA certificate bundle, "
  185. "invalid path: {0}".format(cert_loc))
  186. conn.cert_reqs = 'CERT_REQUIRED'
  187. if not os.path.isdir(cert_loc):
  188. conn.ca_certs = cert_loc
  189. else:
  190. conn.ca_cert_dir = cert_loc
  191. else:
  192. conn.cert_reqs = 'CERT_NONE'
  193. conn.ca_certs = None
  194. conn.ca_cert_dir = None
  195. if cert:
  196. if not isinstance(cert, basestring):
  197. conn.cert_file = cert[0]
  198. conn.key_file = cert[1]
  199. else:
  200. conn.cert_file = cert
  201. conn.key_file = None
  202. if conn.cert_file and not os.path.exists(conn.cert_file):
  203. raise IOError("Could not find the TLS certificate file, "
  204. "invalid path: {0}".format(conn.cert_file))
  205. if conn.key_file and not os.path.exists(conn.key_file):
  206. raise IOError("Could not find the TLS key file, "
  207. "invalid path: {0}".format(conn.key_file))
  208. def build_response(self, req, resp):
  209. """Builds a :class:`Response <requests.Response>` object from a urllib3
  210. response. This should not be called from user code, and is only exposed
  211. for use when subclassing the
  212. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
  213. :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
  214. :param resp: The urllib3 response object.
  215. :rtype: requests.Response
  216. """
  217. response = Response()
  218. # Fallback to None if there's no status_code, for whatever reason.
  219. response.status_code = getattr(resp, 'status', None)
  220. # Make headers case-insensitive.
  221. response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
  222. # Set encoding.
  223. response.encoding = get_encoding_from_headers(response.headers)
  224. response.raw = resp
  225. response.reason = response.raw.reason
  226. if isinstance(req.url, bytes):
  227. response.url = req.url.decode('utf-8')
  228. else:
  229. response.url = req.url
  230. # Add new cookies from the server.
  231. extract_cookies_to_jar(response.cookies, req, resp)
  232. # Give the Response some context.
  233. response.request = req
  234. response.connection = self
  235. return response
  236. def get_connection(self, url, proxies=None):
  237. """Returns a urllib3 connection for the given URL. This should not be
  238. called from user code, and is only exposed for use when subclassing the
  239. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  240. :param url: The URL to connect to.
  241. :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
  242. :rtype: urllib3.ConnectionPool
  243. """
  244. proxy = select_proxy(url, proxies)
  245. if proxy:
  246. proxy = prepend_scheme_if_needed(proxy, 'http')
  247. proxy_manager = self.proxy_manager_for(proxy)
  248. conn = proxy_manager.connection_from_url(url)
  249. else:
  250. # Only scheme should be lower case
  251. parsed = urlparse(url)
  252. url = parsed.geturl()
  253. conn = self.poolmanager.connection_from_url(url)
  254. return conn
  255. def close(self):
  256. """Disposes of any internal state.
  257. Currently, this closes the PoolManager and any active ProxyManager,
  258. which closes any pooled connections.
  259. """
  260. self.poolmanager.clear()
  261. for proxy in self.proxy_manager.values():
  262. proxy.clear()
  263. def request_url(self, request, proxies):
  264. """Obtain the url to use when making the final request.
  265. If the message is being sent through a HTTP proxy, the full URL has to
  266. be used. Otherwise, we should only use the path portion of the URL.
  267. This should not be called from user code, and is only exposed for use
  268. when subclassing the
  269. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  270. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  271. :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
  272. :rtype: str
  273. """
  274. proxy = select_proxy(request.url, proxies)
  275. scheme = urlparse(request.url).scheme
  276. is_proxied_http_request = (proxy and scheme != 'https')
  277. using_socks_proxy = False
  278. if proxy:
  279. proxy_scheme = urlparse(proxy).scheme.lower()
  280. using_socks_proxy = proxy_scheme.startswith('socks')
  281. url = request.path_url
  282. if is_proxied_http_request and not using_socks_proxy:
  283. url = urldefragauth(request.url)
  284. return url
  285. def add_headers(self, request, **kwargs):
  286. """Add any headers needed by the connection. As of v2.0 this does
  287. nothing by default, but is left for overriding by users that subclass
  288. the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  289. This should not be called from user code, and is only exposed for use
  290. when subclassing the
  291. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  292. :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
  293. :param kwargs: The keyword arguments from the call to send().
  294. """
  295. pass
  296. def proxy_headers(self, proxy):
  297. """Returns a dictionary of the headers to add to any request sent
  298. through a proxy. This works with urllib3 magic to ensure that they are
  299. correctly sent to the proxy, rather than in a tunnelled request if
  300. CONNECT is being used.
  301. This should not be called from user code, and is only exposed for use
  302. when subclassing the
  303. :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
  304. :param proxies: The url of the proxy being used for this request.
  305. :rtype: dict
  306. """
  307. headers = {}
  308. username, password = get_auth_from_url(proxy)
  309. if username:
  310. headers['Proxy-Authorization'] = _basic_auth_str(username,
  311. password)
  312. return headers
  313. def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
  314. """Sends PreparedRequest object. Returns Response object.
  315. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
  316. :param stream: (optional) Whether to stream the request content.
  317. :param timeout: (optional) How long to wait for the server to send
  318. data before giving up, as a float, or a :ref:`(connect timeout,
  319. read timeout) <timeouts>` tuple.
  320. :type timeout: float or tuple or urllib3 Timeout object
  321. :param verify: (optional) Either a boolean, in which case it controls whether
  322. we verify the server's TLS certificate, or a string, in which case it
  323. must be a path to a CA bundle to use
  324. :param cert: (optional) Any user-provided SSL certificate to be trusted.
  325. :param proxies: (optional) The proxies dictionary to apply to the request.
  326. :rtype: requests.Response
  327. """
  328. conn = self.get_connection(request.url, proxies)
  329. self.cert_verify(conn, request.url, verify, cert)
  330. url = self.request_url(request, proxies)
  331. self.add_headers(request)
  332. chunked = not (request.body is None or 'Content-Length' in request.headers)
  333. if isinstance(timeout, tuple):
  334. try:
  335. connect, read = timeout
  336. timeout = TimeoutSauce(connect=connect, read=read)
  337. except ValueError as e:
  338. # this may raise a string formatting error.
  339. err = ("Invalid timeout {0}. Pass a (connect, read) "
  340. "timeout tuple, or a single float to set "
  341. "both timeouts to the same value".format(timeout))
  342. raise ValueError(err)
  343. elif isinstance(timeout, TimeoutSauce):
  344. pass
  345. else:
  346. timeout = TimeoutSauce(connect=timeout, read=timeout)
  347. try:
  348. if not chunked:
  349. resp = conn.urlopen(
  350. method=request.method,
  351. url=url,
  352. body=request.body,
  353. headers=request.headers,
  354. redirect=False,
  355. assert_same_host=False,
  356. preload_content=False,
  357. decode_content=False,
  358. retries=self.max_retries,
  359. timeout=timeout
  360. )
  361. # Send the request.
  362. else:
  363. if hasattr(conn, 'proxy_pool'):
  364. conn = conn.proxy_pool
  365. low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
  366. try:
  367. low_conn.putrequest(request.method,
  368. url,
  369. skip_accept_encoding=True)
  370. for header, value in request.headers.items():
  371. low_conn.putheader(header, value)
  372. low_conn.endheaders()
  373. for i in request.body:
  374. low_conn.send(hex(len(i))[2:].encode('utf-8'))
  375. low_conn.send(b'\r\n')
  376. low_conn.send(i)
  377. low_conn.send(b'\r\n')
  378. low_conn.send(b'0\r\n\r\n')
  379. # Receive the response from the server
  380. try:
  381. # For Python 2.7+ versions, use buffering of HTTP
  382. # responses
  383. r = low_conn.getresponse(buffering=True)
  384. except TypeError:
  385. # For compatibility with Python 2.6 versions and back
  386. r = low_conn.getresponse()
  387. resp = HTTPResponse.from_httplib(
  388. r,
  389. pool=conn,
  390. connection=low_conn,
  391. preload_content=False,
  392. decode_content=False
  393. )
  394. except:
  395. # If we hit any problems here, clean up the connection.
  396. # Then, reraise so that we can handle the actual exception.
  397. low_conn.close()
  398. raise
  399. except (ProtocolError, socket.error) as err:
  400. raise ConnectionError(err, request=request)
  401. except MaxRetryError as e:
  402. if isinstance(e.reason, ConnectTimeoutError):
  403. # TODO: Remove this in 3.0.0: see #2811
  404. if not isinstance(e.reason, NewConnectionError):
  405. raise ConnectTimeout(e, request=request)
  406. if isinstance(e.reason, ResponseError):
  407. raise RetryError(e, request=request)
  408. if isinstance(e.reason, _ProxyError):
  409. raise ProxyError(e, request=request)
  410. if isinstance(e.reason, _SSLError):
  411. # This branch is for urllib3 v1.22 and later.
  412. raise SSLError(e, request=request)
  413. raise ConnectionError(e, request=request)
  414. except ClosedPoolError as e:
  415. raise ConnectionError(e, request=request)
  416. except _ProxyError as e:
  417. raise ProxyError(e)
  418. except (_SSLError, _HTTPError) as e:
  419. if isinstance(e, _SSLError):
  420. # This branch is for urllib3 versions earlier than v1.22
  421. raise SSLError(e, request=request)
  422. elif isinstance(e, ReadTimeoutError):
  423. raise ReadTimeout(e, request=request)
  424. else:
  425. raise
  426. return self.build_response(request, resp)