poolmanager.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. from __future__ import absolute_import
  2. import collections
  3. import functools
  4. import logging
  5. from ._collections import RecentlyUsedContainer
  6. from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme
  7. from .exceptions import (
  8. LocationValueError,
  9. MaxRetryError,
  10. ProxySchemeUnknown,
  11. ProxySchemeUnsupported,
  12. URLSchemeUnknown,
  13. )
  14. from .packages import six
  15. from .packages.six.moves.urllib.parse import urljoin
  16. from .request import RequestMethods
  17. from .util.proxy import connection_requires_http_tunnel
  18. from .util.retry import Retry
  19. from .util.url import parse_url
  20. __all__ = ["PoolManager", "ProxyManager", "proxy_from_url"]
  21. log = logging.getLogger(__name__)
  22. SSL_KEYWORDS = (
  23. "key_file",
  24. "cert_file",
  25. "cert_reqs",
  26. "ca_certs",
  27. "ssl_version",
  28. "ca_cert_dir",
  29. "ssl_context",
  30. "key_password",
  31. "server_hostname",
  32. )
  33. # All known keyword arguments that could be provided to the pool manager, its
  34. # pools, or the underlying connections. This is used to construct a pool key.
  35. _key_fields = (
  36. "key_scheme", # str
  37. "key_host", # str
  38. "key_port", # int
  39. "key_timeout", # int or float or Timeout
  40. "key_retries", # int or Retry
  41. "key_strict", # bool
  42. "key_block", # bool
  43. "key_source_address", # str
  44. "key_key_file", # str
  45. "key_key_password", # str
  46. "key_cert_file", # str
  47. "key_cert_reqs", # str
  48. "key_ca_certs", # str
  49. "key_ssl_version", # str
  50. "key_ca_cert_dir", # str
  51. "key_ssl_context", # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext
  52. "key_maxsize", # int
  53. "key_headers", # dict
  54. "key__proxy", # parsed proxy url
  55. "key__proxy_headers", # dict
  56. "key__proxy_config", # class
  57. "key_socket_options", # list of (level (int), optname (int), value (int or str)) tuples
  58. "key__socks_options", # dict
  59. "key_assert_hostname", # bool or string
  60. "key_assert_fingerprint", # str
  61. "key_server_hostname", # str
  62. )
  63. #: The namedtuple class used to construct keys for the connection pool.
  64. #: All custom key schemes should include the fields in this key at a minimum.
  65. PoolKey = collections.namedtuple("PoolKey", _key_fields)
  66. _proxy_config_fields = ("ssl_context", "use_forwarding_for_https")
  67. ProxyConfig = collections.namedtuple("ProxyConfig", _proxy_config_fields)
  68. def _default_key_normalizer(key_class, request_context):
  69. """
  70. Create a pool key out of a request context dictionary.
  71. According to RFC 3986, both the scheme and host are case-insensitive.
  72. Therefore, this function normalizes both before constructing the pool
  73. key for an HTTPS request. If you wish to change this behaviour, provide
  74. alternate callables to ``key_fn_by_scheme``.
  75. :param key_class:
  76. The class to use when constructing the key. This should be a namedtuple
  77. with the ``scheme`` and ``host`` keys at a minimum.
  78. :type key_class: namedtuple
  79. :param request_context:
  80. A dictionary-like object that contain the context for a request.
  81. :type request_context: dict
  82. :return: A namedtuple that can be used as a connection pool key.
  83. :rtype: PoolKey
  84. """
  85. # Since we mutate the dictionary, make a copy first
  86. context = request_context.copy()
  87. context["scheme"] = context["scheme"].lower()
  88. context["host"] = context["host"].lower()
  89. # These are both dictionaries and need to be transformed into frozensets
  90. for key in ("headers", "_proxy_headers", "_socks_options"):
  91. if key in context and context[key] is not None:
  92. context[key] = frozenset(context[key].items())
  93. # The socket_options key may be a list and needs to be transformed into a
  94. # tuple.
  95. socket_opts = context.get("socket_options")
  96. if socket_opts is not None:
  97. context["socket_options"] = tuple(socket_opts)
  98. # Map the kwargs to the names in the namedtuple - this is necessary since
  99. # namedtuples can't have fields starting with '_'.
  100. for key in list(context.keys()):
  101. context["key_" + key] = context.pop(key)
  102. # Default to ``None`` for keys missing from the context
  103. for field in key_class._fields:
  104. if field not in context:
  105. context[field] = None
  106. return key_class(**context)
  107. #: A dictionary that maps a scheme to a callable that creates a pool key.
  108. #: This can be used to alter the way pool keys are constructed, if desired.
  109. #: Each PoolManager makes a copy of this dictionary so they can be configured
  110. #: globally here, or individually on the instance.
  111. key_fn_by_scheme = {
  112. "http": functools.partial(_default_key_normalizer, PoolKey),
  113. "https": functools.partial(_default_key_normalizer, PoolKey),
  114. }
  115. pool_classes_by_scheme = {"http": HTTPConnectionPool, "https": HTTPSConnectionPool}
  116. class PoolManager(RequestMethods):
  117. """
  118. Allows for arbitrary requests while transparently keeping track of
  119. necessary connection pools for you.
  120. :param num_pools:
  121. Number of connection pools to cache before discarding the least
  122. recently used pool.
  123. :param headers:
  124. Headers to include with all requests, unless other headers are given
  125. explicitly.
  126. :param \\**connection_pool_kw:
  127. Additional parameters are used to create fresh
  128. :class:`urllib3.connectionpool.ConnectionPool` instances.
  129. Example::
  130. >>> manager = PoolManager(num_pools=2)
  131. >>> r = manager.request('GET', 'http://google.com/')
  132. >>> r = manager.request('GET', 'http://google.com/mail')
  133. >>> r = manager.request('GET', 'http://yahoo.com/')
  134. >>> len(manager.pools)
  135. 2
  136. """
  137. proxy = None
  138. proxy_config = None
  139. def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
  140. RequestMethods.__init__(self, headers)
  141. self.connection_pool_kw = connection_pool_kw
  142. self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close())
  143. # Locally set the pool classes and keys so other PoolManagers can
  144. # override them.
  145. self.pool_classes_by_scheme = pool_classes_by_scheme
  146. self.key_fn_by_scheme = key_fn_by_scheme.copy()
  147. def __enter__(self):
  148. return self
  149. def __exit__(self, exc_type, exc_val, exc_tb):
  150. self.clear()
  151. # Return False to re-raise any potential exceptions
  152. return False
  153. def _new_pool(self, scheme, host, port, request_context=None):
  154. """
  155. Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and
  156. any additional pool keyword arguments.
  157. If ``request_context`` is provided, it is provided as keyword arguments
  158. to the pool class used. This method is used to actually create the
  159. connection pools handed out by :meth:`connection_from_url` and
  160. companion methods. It is intended to be overridden for customization.
  161. """
  162. pool_cls = self.pool_classes_by_scheme[scheme]
  163. if request_context is None:
  164. request_context = self.connection_pool_kw.copy()
  165. # Although the context has everything necessary to create the pool,
  166. # this function has historically only used the scheme, host, and port
  167. # in the positional args. When an API change is acceptable these can
  168. # be removed.
  169. for key in ("scheme", "host", "port"):
  170. request_context.pop(key, None)
  171. if scheme == "http":
  172. for kw in SSL_KEYWORDS:
  173. request_context.pop(kw, None)
  174. return pool_cls(host, port, **request_context)
  175. def clear(self):
  176. """
  177. Empty our store of pools and direct them all to close.
  178. This will not affect in-flight connections, but they will not be
  179. re-used after completion.
  180. """
  181. self.pools.clear()
  182. def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None):
  183. """
  184. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.
  185. If ``port`` isn't given, it will be derived from the ``scheme`` using
  186. ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
  187. provided, it is merged with the instance's ``connection_pool_kw``
  188. variable and used to create the new connection pool, if one is
  189. needed.
  190. """
  191. if not host:
  192. raise LocationValueError("No host specified.")
  193. request_context = self._merge_pool_kwargs(pool_kwargs)
  194. request_context["scheme"] = scheme or "http"
  195. if not port:
  196. port = port_by_scheme.get(request_context["scheme"].lower(), 80)
  197. request_context["port"] = port
  198. request_context["host"] = host
  199. return self.connection_from_context(request_context)
  200. def connection_from_context(self, request_context):
  201. """
  202. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.
  203. ``request_context`` must at least contain the ``scheme`` key and its
  204. value must be a key in ``key_fn_by_scheme`` instance variable.
  205. """
  206. scheme = request_context["scheme"].lower()
  207. pool_key_constructor = self.key_fn_by_scheme.get(scheme)
  208. if not pool_key_constructor:
  209. raise URLSchemeUnknown(scheme)
  210. pool_key = pool_key_constructor(request_context)
  211. return self.connection_from_pool_key(pool_key, request_context=request_context)
  212. def connection_from_pool_key(self, pool_key, request_context=None):
  213. """
  214. Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.
  215. ``pool_key`` should be a namedtuple that only contains immutable
  216. objects. At a minimum it must have the ``scheme``, ``host``, and
  217. ``port`` fields.
  218. """
  219. with self.pools.lock:
  220. # If the scheme, host, or port doesn't match existing open
  221. # connections, open a new ConnectionPool.
  222. pool = self.pools.get(pool_key)
  223. if pool:
  224. return pool
  225. # Make a fresh ConnectionPool of the desired type
  226. scheme = request_context["scheme"]
  227. host = request_context["host"]
  228. port = request_context["port"]
  229. pool = self._new_pool(scheme, host, port, request_context=request_context)
  230. self.pools[pool_key] = pool
  231. return pool
  232. def connection_from_url(self, url, pool_kwargs=None):
  233. """
  234. Similar to :func:`urllib3.connectionpool.connection_from_url`.
  235. If ``pool_kwargs`` is not provided and a new pool needs to be
  236. constructed, ``self.connection_pool_kw`` is used to initialize
  237. the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
  238. is provided, it is used instead. Note that if a new pool does not
  239. need to be created for the request, the provided ``pool_kwargs`` are
  240. not used.
  241. """
  242. u = parse_url(url)
  243. return self.connection_from_host(
  244. u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs
  245. )
  246. def _merge_pool_kwargs(self, override):
  247. """
  248. Merge a dictionary of override values for self.connection_pool_kw.
  249. This does not modify self.connection_pool_kw and returns a new dict.
  250. Any keys in the override dictionary with a value of ``None`` are
  251. removed from the merged dictionary.
  252. """
  253. base_pool_kwargs = self.connection_pool_kw.copy()
  254. if override:
  255. for key, value in override.items():
  256. if value is None:
  257. try:
  258. del base_pool_kwargs[key]
  259. except KeyError:
  260. pass
  261. else:
  262. base_pool_kwargs[key] = value
  263. return base_pool_kwargs
  264. def _proxy_requires_url_absolute_form(self, parsed_url):
  265. """
  266. Indicates if the proxy requires the complete destination URL in the
  267. request. Normally this is only needed when not using an HTTP CONNECT
  268. tunnel.
  269. """
  270. if self.proxy is None:
  271. return False
  272. return not connection_requires_http_tunnel(
  273. self.proxy, self.proxy_config, parsed_url.scheme
  274. )
  275. def _validate_proxy_scheme_url_selection(self, url_scheme):
  276. """
  277. Validates that were not attempting to do TLS in TLS connections on
  278. Python2 or with unsupported SSL implementations.
  279. """
  280. if self.proxy is None or url_scheme != "https":
  281. return
  282. if self.proxy.scheme != "https":
  283. return
  284. if six.PY2 and not self.proxy_config.use_forwarding_for_https:
  285. raise ProxySchemeUnsupported(
  286. "Contacting HTTPS destinations through HTTPS proxies "
  287. "'via CONNECT tunnels' is not supported in Python 2"
  288. )
  289. def urlopen(self, method, url, redirect=True, **kw):
  290. """
  291. Same as :meth:`urllib3.HTTPConnectionPool.urlopen`
  292. with custom cross-host redirect logic and only sends the request-uri
  293. portion of the ``url``.
  294. The given ``url`` parameter must be absolute, such that an appropriate
  295. :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
  296. """
  297. u = parse_url(url)
  298. self._validate_proxy_scheme_url_selection(u.scheme)
  299. conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
  300. kw["assert_same_host"] = False
  301. kw["redirect"] = False
  302. if "headers" not in kw:
  303. kw["headers"] = self.headers.copy()
  304. if self._proxy_requires_url_absolute_form(u):
  305. response = conn.urlopen(method, url, **kw)
  306. else:
  307. response = conn.urlopen(method, u.request_uri, **kw)
  308. redirect_location = redirect and response.get_redirect_location()
  309. if not redirect_location:
  310. return response
  311. # Support relative URLs for redirecting.
  312. redirect_location = urljoin(url, redirect_location)
  313. # RFC 7231, Section 6.4.4
  314. if response.status == 303:
  315. method = "GET"
  316. retries = kw.get("retries")
  317. if not isinstance(retries, Retry):
  318. retries = Retry.from_int(retries, redirect=redirect)
  319. # Strip headers marked as unsafe to forward to the redirected location.
  320. # Check remove_headers_on_redirect to avoid a potential network call within
  321. # conn.is_same_host() which may use socket.gethostbyname() in the future.
  322. if retries.remove_headers_on_redirect and not conn.is_same_host(
  323. redirect_location
  324. ):
  325. headers = list(six.iterkeys(kw["headers"]))
  326. for header in headers:
  327. if header.lower() in retries.remove_headers_on_redirect:
  328. kw["headers"].pop(header, None)
  329. try:
  330. retries = retries.increment(method, url, response=response, _pool=conn)
  331. except MaxRetryError:
  332. if retries.raise_on_redirect:
  333. response.drain_conn()
  334. raise
  335. return response
  336. kw["retries"] = retries
  337. kw["redirect"] = redirect
  338. log.info("Redirecting %s -> %s", url, redirect_location)
  339. response.drain_conn()
  340. return self.urlopen(method, redirect_location, **kw)
  341. class ProxyManager(PoolManager):
  342. """
  343. Behaves just like :class:`PoolManager`, but sends all requests through
  344. the defined proxy, using the CONNECT method for HTTPS URLs.
  345. :param proxy_url:
  346. The URL of the proxy to be used.
  347. :param proxy_headers:
  348. A dictionary containing headers that will be sent to the proxy. In case
  349. of HTTP they are being sent with each request, while in the
  350. HTTPS/CONNECT case they are sent only once. Could be used for proxy
  351. authentication.
  352. :param proxy_ssl_context:
  353. The proxy SSL context is used to establish the TLS connection to the
  354. proxy when using HTTPS proxies.
  355. :param use_forwarding_for_https:
  356. (Defaults to False) If set to True will forward requests to the HTTPS
  357. proxy to be made on behalf of the client instead of creating a TLS
  358. tunnel via the CONNECT method. **Enabling this flag means that request
  359. and response headers and content will be visible from the HTTPS proxy**
  360. whereas tunneling keeps request and response headers and content
  361. private. IP address, target hostname, SNI, and port are always visible
  362. to an HTTPS proxy even when this flag is disabled.
  363. Example:
  364. >>> proxy = urllib3.ProxyManager('http://localhost:3128/')
  365. >>> r1 = proxy.request('GET', 'http://google.com/')
  366. >>> r2 = proxy.request('GET', 'http://httpbin.org/')
  367. >>> len(proxy.pools)
  368. 1
  369. >>> r3 = proxy.request('GET', 'https://httpbin.org/')
  370. >>> r4 = proxy.request('GET', 'https://twitter.com/')
  371. >>> len(proxy.pools)
  372. 3
  373. """
  374. def __init__(
  375. self,
  376. proxy_url,
  377. num_pools=10,
  378. headers=None,
  379. proxy_headers=None,
  380. proxy_ssl_context=None,
  381. use_forwarding_for_https=False,
  382. **connection_pool_kw
  383. ):
  384. if isinstance(proxy_url, HTTPConnectionPool):
  385. proxy_url = "%s://%s:%i" % (
  386. proxy_url.scheme,
  387. proxy_url.host,
  388. proxy_url.port,
  389. )
  390. proxy = parse_url(proxy_url)
  391. if proxy.scheme not in ("http", "https"):
  392. raise ProxySchemeUnknown(proxy.scheme)
  393. if not proxy.port:
  394. port = port_by_scheme.get(proxy.scheme, 80)
  395. proxy = proxy._replace(port=port)
  396. self.proxy = proxy
  397. self.proxy_headers = proxy_headers or {}
  398. self.proxy_ssl_context = proxy_ssl_context
  399. self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https)
  400. connection_pool_kw["_proxy"] = self.proxy
  401. connection_pool_kw["_proxy_headers"] = self.proxy_headers
  402. connection_pool_kw["_proxy_config"] = self.proxy_config
  403. super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw)
  404. def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None):
  405. if scheme == "https":
  406. return super(ProxyManager, self).connection_from_host(
  407. host, port, scheme, pool_kwargs=pool_kwargs
  408. )
  409. return super(ProxyManager, self).connection_from_host(
  410. self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs
  411. )
  412. def _set_proxy_headers(self, url, headers=None):
  413. """
  414. Sets headers needed by proxies: specifically, the Accept and Host
  415. headers. Only sets headers not provided by the user.
  416. """
  417. headers_ = {"Accept": "*/*"}
  418. netloc = parse_url(url).netloc
  419. if netloc:
  420. headers_["Host"] = netloc
  421. if headers:
  422. headers_.update(headers)
  423. return headers_
  424. def urlopen(self, method, url, redirect=True, **kw):
  425. "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
  426. u = parse_url(url)
  427. if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):
  428. # For connections using HTTP CONNECT, httplib sets the necessary
  429. # headers on the CONNECT to the proxy. If we're not using CONNECT,
  430. # we'll definitely need to set 'Host' at the very least.
  431. headers = kw.get("headers", self.headers)
  432. kw["headers"] = self._set_proxy_headers(url, headers)
  433. return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
  434. def proxy_from_url(url, **kw):
  435. return ProxyManager(proxy_url=url, **kw)