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.

450 lines
16 KiB

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