poolmanager.py 22 KB

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