PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/site-packages/pip/_vendor/urllib3/poolmanager.py

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