connectionpool.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. from __future__ import annotations
  2. import errno
  3. import logging
  4. import queue
  5. import sys
  6. import typing
  7. import warnings
  8. import weakref
  9. from socket import timeout as SocketTimeout
  10. from types import TracebackType
  11. from ._base_connection import _TYPE_BODY
  12. from ._collections import HTTPHeaderDict
  13. from ._request_methods import RequestMethods
  14. from .connection import (
  15. BaseSSLError,
  16. BrokenPipeError,
  17. DummyConnection,
  18. HTTPConnection,
  19. HTTPException,
  20. HTTPSConnection,
  21. ProxyConfig,
  22. _wrap_proxy_error,
  23. )
  24. from .connection import port_by_scheme as port_by_scheme
  25. from .exceptions import (
  26. ClosedPoolError,
  27. EmptyPoolError,
  28. FullPoolError,
  29. HostChangedError,
  30. InsecureRequestWarning,
  31. LocationValueError,
  32. MaxRetryError,
  33. NewConnectionError,
  34. ProtocolError,
  35. ProxyError,
  36. ReadTimeoutError,
  37. SSLError,
  38. TimeoutError,
  39. )
  40. from .response import BaseHTTPResponse
  41. from .util.connection import is_connection_dropped
  42. from .util.proxy import connection_requires_http_tunnel
  43. from .util.request import _TYPE_BODY_POSITION, set_file_position
  44. from .util.retry import Retry
  45. from .util.ssl_match_hostname import CertificateError
  46. from .util.timeout import _DEFAULT_TIMEOUT, _TYPE_DEFAULT, Timeout
  47. from .util.url import Url, _encode_target
  48. from .util.url import _normalize_host as normalize_host
  49. from .util.url import parse_url
  50. from .util.util import to_str
  51. if typing.TYPE_CHECKING:
  52. import ssl
  53. from typing import Literal
  54. from ._base_connection import BaseHTTPConnection, BaseHTTPSConnection
  55. log = logging.getLogger(__name__)
  56. _TYPE_TIMEOUT = typing.Union[Timeout, float, _TYPE_DEFAULT, None]
  57. _SelfT = typing.TypeVar("_SelfT")
  58. # Pool objects
  59. class ConnectionPool:
  60. """
  61. Base class for all connection pools, such as
  62. :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
  63. .. note::
  64. ConnectionPool.urlopen() does not normalize or percent-encode target URIs
  65. which is useful if your target server doesn't support percent-encoded
  66. target URIs.
  67. """
  68. scheme: str | None = None
  69. QueueCls = queue.LifoQueue
  70. def __init__(self, host: str, port: int | None = None) -> None:
  71. if not host:
  72. raise LocationValueError("No host specified.")
  73. self.host = _normalize_host(host, scheme=self.scheme)
  74. self.port = port
  75. # This property uses 'normalize_host()' (not '_normalize_host()')
  76. # to avoid removing square braces around IPv6 addresses.
  77. # This value is sent to `HTTPConnection.set_tunnel()` if called
  78. # because square braces are required for HTTP CONNECT tunneling.
  79. self._tunnel_host = normalize_host(host, scheme=self.scheme).lower()
  80. def __str__(self) -> str:
  81. return f"{type(self).__name__}(host={self.host!r}, port={self.port!r})"
  82. def __enter__(self: _SelfT) -> _SelfT:
  83. return self
  84. def __exit__(
  85. self,
  86. exc_type: type[BaseException] | None,
  87. exc_val: BaseException | None,
  88. exc_tb: TracebackType | None,
  89. ) -> Literal[False]:
  90. self.close()
  91. # Return False to re-raise any potential exceptions
  92. return False
  93. def close(self) -> None:
  94. """
  95. Close all pooled connections and disable the pool.
  96. """
  97. # This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
  98. _blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}
  99. class HTTPConnectionPool(ConnectionPool, RequestMethods):
  100. """
  101. Thread-safe connection pool for one host.
  102. :param host:
  103. Host used for this HTTP Connection (e.g. "localhost"), passed into
  104. :class:`http.client.HTTPConnection`.
  105. :param port:
  106. Port used for this HTTP Connection (None is equivalent to 80), passed
  107. into :class:`http.client.HTTPConnection`.
  108. :param timeout:
  109. Socket timeout in seconds for each individual connection. This can
  110. be a float or integer, which sets the timeout for the HTTP request,
  111. or an instance of :class:`urllib3.util.Timeout` which gives you more
  112. fine-grained control over request timeouts. After the constructor has
  113. been parsed, this is always a `urllib3.util.Timeout` object.
  114. :param maxsize:
  115. Number of connections to save that can be reused. More than 1 is useful
  116. in multithreaded situations. If ``block`` is set to False, more
  117. connections will be created but they will not be saved once they've
  118. been used.
  119. :param block:
  120. If set to True, no more than ``maxsize`` connections will be used at
  121. a time. When no free connections are available, the call will block
  122. until a connection has been released. This is a useful side effect for
  123. particular multithreaded situations where one does not want to use more
  124. than maxsize connections per host to prevent flooding.
  125. :param headers:
  126. Headers to include with all requests, unless other headers are given
  127. explicitly.
  128. :param retries:
  129. Retry configuration to use by default with requests in this pool.
  130. :param _proxy:
  131. Parsed proxy URL, should not be used directly, instead, see
  132. :class:`urllib3.ProxyManager`
  133. :param _proxy_headers:
  134. A dictionary with proxy headers, should not be used directly,
  135. instead, see :class:`urllib3.ProxyManager`
  136. :param \\**conn_kw:
  137. Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
  138. :class:`urllib3.connection.HTTPSConnection` instances.
  139. """
  140. scheme = "http"
  141. ConnectionCls: (
  142. type[BaseHTTPConnection] | type[BaseHTTPSConnection]
  143. ) = HTTPConnection
  144. def __init__(
  145. self,
  146. host: str,
  147. port: int | None = None,
  148. timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,
  149. maxsize: int = 1,
  150. block: bool = False,
  151. headers: typing.Mapping[str, str] | None = None,
  152. retries: Retry | bool | int | None = None,
  153. _proxy: Url | None = None,
  154. _proxy_headers: typing.Mapping[str, str] | None = None,
  155. _proxy_config: ProxyConfig | None = None,
  156. **conn_kw: typing.Any,
  157. ):
  158. ConnectionPool.__init__(self, host, port)
  159. RequestMethods.__init__(self, headers)
  160. if not isinstance(timeout, Timeout):
  161. timeout = Timeout.from_float(timeout)
  162. if retries is None:
  163. retries = Retry.DEFAULT
  164. self.timeout = timeout
  165. self.retries = retries
  166. self.pool: queue.LifoQueue[typing.Any] | None = self.QueueCls(maxsize)
  167. self.block = block
  168. self.proxy = _proxy
  169. self.proxy_headers = _proxy_headers or {}
  170. self.proxy_config = _proxy_config
  171. # Fill the queue up so that doing get() on it will block properly
  172. for _ in range(maxsize):
  173. self.pool.put(None)
  174. # These are mostly for testing and debugging purposes.
  175. self.num_connections = 0
  176. self.num_requests = 0
  177. self.conn_kw = conn_kw
  178. if self.proxy:
  179. # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
  180. # We cannot know if the user has added default socket options, so we cannot replace the
  181. # list.
  182. self.conn_kw.setdefault("socket_options", [])
  183. self.conn_kw["proxy"] = self.proxy
  184. self.conn_kw["proxy_config"] = self.proxy_config
  185. # Do not pass 'self' as callback to 'finalize'.
  186. # Then the 'finalize' would keep an endless living (leak) to self.
  187. # By just passing a reference to the pool allows the garbage collector
  188. # to free self if nobody else has a reference to it.
  189. pool = self.pool
  190. # Close all the HTTPConnections in the pool before the
  191. # HTTPConnectionPool object is garbage collected.
  192. weakref.finalize(self, _close_pool_connections, pool)
  193. def _new_conn(self) -> BaseHTTPConnection:
  194. """
  195. Return a fresh :class:`HTTPConnection`.
  196. """
  197. self.num_connections += 1
  198. log.debug(
  199. "Starting new HTTP connection (%d): %s:%s",
  200. self.num_connections,
  201. self.host,
  202. self.port or "80",
  203. )
  204. conn = self.ConnectionCls(
  205. host=self.host,
  206. port=self.port,
  207. timeout=self.timeout.connect_timeout,
  208. **self.conn_kw,
  209. )
  210. return conn
  211. def _get_conn(self, timeout: float | None = None) -> BaseHTTPConnection:
  212. """
  213. Get a connection. Will return a pooled connection if one is available.
  214. If no connections are available and :prop:`.block` is ``False``, then a
  215. fresh connection is returned.
  216. :param timeout:
  217. Seconds to wait before giving up and raising
  218. :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
  219. :prop:`.block` is ``True``.
  220. """
  221. conn = None
  222. if self.pool is None:
  223. raise ClosedPoolError(self, "Pool is closed.")
  224. try:
  225. conn = self.pool.get(block=self.block, timeout=timeout)
  226. except AttributeError: # self.pool is None
  227. raise ClosedPoolError(self, "Pool is closed.") from None # Defensive:
  228. except queue.Empty:
  229. if self.block:
  230. raise EmptyPoolError(
  231. self,
  232. "Pool is empty and a new connection can't be opened due to blocking mode.",
  233. ) from None
  234. pass # Oh well, we'll create a new connection then
  235. # If this is a persistent connection, check if it got disconnected
  236. if conn and is_connection_dropped(conn):
  237. log.debug("Resetting dropped connection: %s", self.host)
  238. conn.close()
  239. return conn or self._new_conn()
  240. def _put_conn(self, conn: BaseHTTPConnection | None) -> None:
  241. """
  242. Put a connection back into the pool.
  243. :param conn:
  244. Connection object for the current host and port as returned by
  245. :meth:`._new_conn` or :meth:`._get_conn`.
  246. If the pool is already full, the connection is closed and discarded
  247. because we exceeded maxsize. If connections are discarded frequently,
  248. then maxsize should be increased.
  249. If the pool is closed, then the connection will be closed and discarded.
  250. """
  251. if self.pool is not None:
  252. try:
  253. self.pool.put(conn, block=False)
  254. return # Everything is dandy, done.
  255. except AttributeError:
  256. # self.pool is None.
  257. pass
  258. except queue.Full:
  259. # Connection never got put back into the pool, close it.
  260. if conn:
  261. conn.close()
  262. if self.block:
  263. # This should never happen if you got the conn from self._get_conn
  264. raise FullPoolError(
  265. self,
  266. "Pool reached maximum size and no more connections are allowed.",
  267. ) from None
  268. log.warning(
  269. "Connection pool is full, discarding connection: %s. Connection pool size: %s",
  270. self.host,
  271. self.pool.qsize(),
  272. )
  273. # Connection never got put back into the pool, close it.
  274. if conn:
  275. conn.close()
  276. def _validate_conn(self, conn: BaseHTTPConnection) -> None:
  277. """
  278. Called right before a request is made, after the socket is created.
  279. """
  280. def _prepare_proxy(self, conn: BaseHTTPConnection) -> None:
  281. # Nothing to do for HTTP connections.
  282. pass
  283. def _get_timeout(self, timeout: _TYPE_TIMEOUT) -> Timeout:
  284. """Helper that always returns a :class:`urllib3.util.Timeout`"""
  285. if timeout is _DEFAULT_TIMEOUT:
  286. return self.timeout.clone()
  287. if isinstance(timeout, Timeout):
  288. return timeout.clone()
  289. else:
  290. # User passed us an int/float. This is for backwards compatibility,
  291. # can be removed later
  292. return Timeout.from_float(timeout)
  293. def _raise_timeout(
  294. self,
  295. err: BaseSSLError | OSError | SocketTimeout,
  296. url: str,
  297. timeout_value: _TYPE_TIMEOUT | None,
  298. ) -> None:
  299. """Is the error actually a timeout? Will raise a ReadTimeout or pass"""
  300. if isinstance(err, SocketTimeout):
  301. raise ReadTimeoutError(
  302. self, url, f"Read timed out. (read timeout={timeout_value})"
  303. ) from err
  304. # See the above comment about EAGAIN in Python 3.
  305. if hasattr(err, "errno") and err.errno in _blocking_errnos:
  306. raise ReadTimeoutError(
  307. self, url, f"Read timed out. (read timeout={timeout_value})"
  308. ) from err
  309. def _make_request(
  310. self,
  311. conn: BaseHTTPConnection,
  312. method: str,
  313. url: str,
  314. body: _TYPE_BODY | None = None,
  315. headers: typing.Mapping[str, str] | None = None,
  316. retries: Retry | None = None,
  317. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  318. chunked: bool = False,
  319. response_conn: BaseHTTPConnection | None = None,
  320. preload_content: bool = True,
  321. decode_content: bool = True,
  322. enforce_content_length: bool = True,
  323. ) -> BaseHTTPResponse:
  324. """
  325. Perform a request on a given urllib connection object taken from our
  326. pool.
  327. :param conn:
  328. a connection from one of our connection pools
  329. :param method:
  330. HTTP request method (such as GET, POST, PUT, etc.)
  331. :param url:
  332. The URL to perform the request on.
  333. :param body:
  334. Data to send in the request body, either :class:`str`, :class:`bytes`,
  335. an iterable of :class:`str`/:class:`bytes`, or a file-like object.
  336. :param headers:
  337. Dictionary of custom headers to send, such as User-Agent,
  338. If-None-Match, etc. If None, pool headers are used. If provided,
  339. these headers completely replace any pool-specific headers.
  340. :param retries:
  341. Configure the number of retries to allow before raising a
  342. :class:`~urllib3.exceptions.MaxRetryError` exception.
  343. Pass ``None`` to retry until you receive a response. Pass a
  344. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  345. over different types of retries.
  346. Pass an integer number to retry connection errors that many times,
  347. but no other types of errors. Pass zero to never retry.
  348. If ``False``, then retries are disabled and any exception is raised
  349. immediately. Also, instead of raising a MaxRetryError on redirects,
  350. the redirect response will be returned.
  351. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  352. :param timeout:
  353. If specified, overrides the default timeout for this one
  354. request. It may be a float (in seconds) or an instance of
  355. :class:`urllib3.util.Timeout`.
  356. :param chunked:
  357. If True, urllib3 will send the body using chunked transfer
  358. encoding. Otherwise, urllib3 will send the body using the standard
  359. content-length form. Defaults to False.
  360. :param response_conn:
  361. Set this to ``None`` if you will handle releasing the connection or
  362. set the connection to have the response release it.
  363. :param preload_content:
  364. If True, the response's body will be preloaded during construction.
  365. :param decode_content:
  366. If True, will attempt to decode the body based on the
  367. 'content-encoding' header.
  368. :param enforce_content_length:
  369. Enforce content length checking. Body returned by server must match
  370. value of Content-Length header, if present. Otherwise, raise error.
  371. """
  372. self.num_requests += 1
  373. timeout_obj = self._get_timeout(timeout)
  374. timeout_obj.start_connect()
  375. conn.timeout = Timeout.resolve_default_timeout(timeout_obj.connect_timeout)
  376. try:
  377. # Trigger any extra validation we need to do.
  378. try:
  379. self._validate_conn(conn)
  380. except (SocketTimeout, BaseSSLError) as e:
  381. self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
  382. raise
  383. # _validate_conn() starts the connection to an HTTPS proxy
  384. # so we need to wrap errors with 'ProxyError' here too.
  385. except (
  386. OSError,
  387. NewConnectionError,
  388. TimeoutError,
  389. BaseSSLError,
  390. CertificateError,
  391. SSLError,
  392. ) as e:
  393. new_e: Exception = e
  394. if isinstance(e, (BaseSSLError, CertificateError)):
  395. new_e = SSLError(e)
  396. # If the connection didn't successfully connect to it's proxy
  397. # then there
  398. if isinstance(
  399. new_e, (OSError, NewConnectionError, TimeoutError, SSLError)
  400. ) and (conn and conn.proxy and not conn.has_connected_to_proxy):
  401. new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
  402. raise new_e
  403. # conn.request() calls http.client.*.request, not the method in
  404. # urllib3.request. It also calls makefile (recv) on the socket.
  405. try:
  406. conn.request(
  407. method,
  408. url,
  409. body=body,
  410. headers=headers,
  411. chunked=chunked,
  412. preload_content=preload_content,
  413. decode_content=decode_content,
  414. enforce_content_length=enforce_content_length,
  415. )
  416. # We are swallowing BrokenPipeError (errno.EPIPE) since the server is
  417. # legitimately able to close the connection after sending a valid response.
  418. # With this behaviour, the received response is still readable.
  419. except BrokenPipeError:
  420. pass
  421. except OSError as e:
  422. # MacOS/Linux
  423. # EPROTOTYPE is needed on macOS
  424. # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/
  425. if e.errno != errno.EPROTOTYPE:
  426. raise
  427. # Reset the timeout for the recv() on the socket
  428. read_timeout = timeout_obj.read_timeout
  429. if not conn.is_closed:
  430. # In Python 3 socket.py will catch EAGAIN and return None when you
  431. # try and read into the file pointer created by http.client, which
  432. # instead raises a BadStatusLine exception. Instead of catching
  433. # the exception and assuming all BadStatusLine exceptions are read
  434. # timeouts, check for a zero timeout before making the request.
  435. if read_timeout == 0:
  436. raise ReadTimeoutError(
  437. self, url, f"Read timed out. (read timeout={read_timeout})"
  438. )
  439. conn.timeout = read_timeout
  440. # Receive the response from the server
  441. try:
  442. response = conn.getresponse()
  443. except (BaseSSLError, OSError) as e:
  444. self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  445. raise
  446. # Set properties that are used by the pooling layer.
  447. response.retries = retries
  448. response._connection = response_conn # type: ignore[attr-defined]
  449. response._pool = self # type: ignore[attr-defined]
  450. log.debug(
  451. '%s://%s:%s "%s %s %s" %s %s',
  452. self.scheme,
  453. self.host,
  454. self.port,
  455. method,
  456. url,
  457. # HTTP version
  458. conn._http_vsn_str, # type: ignore[attr-defined]
  459. response.status,
  460. response.length_remaining, # type: ignore[attr-defined]
  461. )
  462. return response
  463. def close(self) -> None:
  464. """
  465. Close all pooled connections and disable the pool.
  466. """
  467. if self.pool is None:
  468. return
  469. # Disable access to the pool
  470. old_pool, self.pool = self.pool, None
  471. # Close all the HTTPConnections in the pool.
  472. _close_pool_connections(old_pool)
  473. def is_same_host(self, url: str) -> bool:
  474. """
  475. Check if the given ``url`` is a member of the same host as this
  476. connection pool.
  477. """
  478. if url.startswith("/"):
  479. return True
  480. # TODO: Add optional support for socket.gethostbyname checking.
  481. scheme, _, host, port, *_ = parse_url(url)
  482. scheme = scheme or "http"
  483. if host is not None:
  484. host = _normalize_host(host, scheme=scheme)
  485. # Use explicit default port for comparison when none is given
  486. if self.port and not port:
  487. port = port_by_scheme.get(scheme)
  488. elif not self.port and port == port_by_scheme.get(scheme):
  489. port = None
  490. return (scheme, host, port) == (self.scheme, self.host, self.port)
  491. def urlopen( # type: ignore[override]
  492. self,
  493. method: str,
  494. url: str,
  495. body: _TYPE_BODY | None = None,
  496. headers: typing.Mapping[str, str] | None = None,
  497. retries: Retry | bool | int | None = None,
  498. redirect: bool = True,
  499. assert_same_host: bool = True,
  500. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  501. pool_timeout: int | None = None,
  502. release_conn: bool | None = None,
  503. chunked: bool = False,
  504. body_pos: _TYPE_BODY_POSITION | None = None,
  505. preload_content: bool = True,
  506. decode_content: bool = True,
  507. **response_kw: typing.Any,
  508. ) -> BaseHTTPResponse:
  509. """
  510. Get a connection from the pool and perform an HTTP request. This is the
  511. lowest level call for making a request, so you'll need to specify all
  512. the raw details.
  513. .. note::
  514. More commonly, it's appropriate to use a convenience method
  515. such as :meth:`request`.
  516. .. note::
  517. `release_conn` will only behave as expected if
  518. `preload_content=False` because we want to make
  519. `preload_content=False` the default behaviour someday soon without
  520. breaking backwards compatibility.
  521. :param method:
  522. HTTP request method (such as GET, POST, PUT, etc.)
  523. :param url:
  524. The URL to perform the request on.
  525. :param body:
  526. Data to send in the request body, either :class:`str`, :class:`bytes`,
  527. an iterable of :class:`str`/:class:`bytes`, or a file-like object.
  528. :param headers:
  529. Dictionary of custom headers to send, such as User-Agent,
  530. If-None-Match, etc. If None, pool headers are used. If provided,
  531. these headers completely replace any pool-specific headers.
  532. :param retries:
  533. Configure the number of retries to allow before raising a
  534. :class:`~urllib3.exceptions.MaxRetryError` exception.
  535. Pass ``None`` to retry until you receive a response. Pass a
  536. :class:`~urllib3.util.retry.Retry` object for fine-grained control
  537. over different types of retries.
  538. Pass an integer number to retry connection errors that many times,
  539. but no other types of errors. Pass zero to never retry.
  540. If ``False``, then retries are disabled and any exception is raised
  541. immediately. Also, instead of raising a MaxRetryError on redirects,
  542. the redirect response will be returned.
  543. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
  544. :param redirect:
  545. If True, automatically handle redirects (status codes 301, 302,
  546. 303, 307, 308). Each redirect counts as a retry. Disabling retries
  547. will disable redirect, too.
  548. :param assert_same_host:
  549. If ``True``, will make sure that the host of the pool requests is
  550. consistent else will raise HostChangedError. When ``False``, you can
  551. use the pool on an HTTP proxy and request foreign hosts.
  552. :param timeout:
  553. If specified, overrides the default timeout for this one
  554. request. It may be a float (in seconds) or an instance of
  555. :class:`urllib3.util.Timeout`.
  556. :param pool_timeout:
  557. If set and the pool is set to block=True, then this method will
  558. block for ``pool_timeout`` seconds and raise EmptyPoolError if no
  559. connection is available within the time period.
  560. :param bool preload_content:
  561. If True, the response's body will be preloaded into memory.
  562. :param bool decode_content:
  563. If True, will attempt to decode the body based on the
  564. 'content-encoding' header.
  565. :param release_conn:
  566. If False, then the urlopen call will not release the connection
  567. back into the pool once a response is received (but will release if
  568. you read the entire contents of the response such as when
  569. `preload_content=True`). This is useful if you're not preloading
  570. the response's content immediately. You will need to call
  571. ``r.release_conn()`` on the response ``r`` to return the connection
  572. back into the pool. If None, it takes the value of ``preload_content``
  573. which defaults to ``True``.
  574. :param bool chunked:
  575. If True, urllib3 will send the body using chunked transfer
  576. encoding. Otherwise, urllib3 will send the body using the standard
  577. content-length form. Defaults to False.
  578. :param int body_pos:
  579. Position to seek to in file-like body in the event of a retry or
  580. redirect. Typically this won't need to be set because urllib3 will
  581. auto-populate the value when needed.
  582. """
  583. parsed_url = parse_url(url)
  584. destination_scheme = parsed_url.scheme
  585. if headers is None:
  586. headers = self.headers
  587. if not isinstance(retries, Retry):
  588. retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
  589. if release_conn is None:
  590. release_conn = preload_content
  591. # Check host
  592. if assert_same_host and not self.is_same_host(url):
  593. raise HostChangedError(self, url, retries)
  594. # Ensure that the URL we're connecting to is properly encoded
  595. if url.startswith("/"):
  596. url = to_str(_encode_target(url))
  597. else:
  598. url = to_str(parsed_url.url)
  599. conn = None
  600. # Track whether `conn` needs to be released before
  601. # returning/raising/recursing. Update this variable if necessary, and
  602. # leave `release_conn` constant throughout the function. That way, if
  603. # the function recurses, the original value of `release_conn` will be
  604. # passed down into the recursive call, and its value will be respected.
  605. #
  606. # See issue #651 [1] for details.
  607. #
  608. # [1] <https://github.com/urllib3/urllib3/issues/651>
  609. release_this_conn = release_conn
  610. http_tunnel_required = connection_requires_http_tunnel(
  611. self.proxy, self.proxy_config, destination_scheme
  612. )
  613. # Merge the proxy headers. Only done when not using HTTP CONNECT. We
  614. # have to copy the headers dict so we can safely change it without those
  615. # changes being reflected in anyone else's copy.
  616. if not http_tunnel_required:
  617. headers = headers.copy() # type: ignore[attr-defined]
  618. headers.update(self.proxy_headers) # type: ignore[union-attr]
  619. # Must keep the exception bound to a separate variable or else Python 3
  620. # complains about UnboundLocalError.
  621. err = None
  622. # Keep track of whether we cleanly exited the except block. This
  623. # ensures we do proper cleanup in finally.
  624. clean_exit = False
  625. # Rewind body position, if needed. Record current position
  626. # for future rewinds in the event of a redirect/retry.
  627. body_pos = set_file_position(body, body_pos)
  628. try:
  629. # Request a connection from the queue.
  630. timeout_obj = self._get_timeout(timeout)
  631. conn = self._get_conn(timeout=pool_timeout)
  632. conn.timeout = timeout_obj.connect_timeout # type: ignore[assignment]
  633. # Is this a closed/new connection that requires CONNECT tunnelling?
  634. if self.proxy is not None and http_tunnel_required and conn.is_closed:
  635. try:
  636. self._prepare_proxy(conn)
  637. except (BaseSSLError, OSError, SocketTimeout) as e:
  638. self._raise_timeout(
  639. err=e, url=self.proxy.url, timeout_value=conn.timeout
  640. )
  641. raise
  642. # If we're going to release the connection in ``finally:``, then
  643. # the response doesn't need to know about the connection. Otherwise
  644. # it will also try to release it and we'll have a double-release
  645. # mess.
  646. response_conn = conn if not release_conn else None
  647. # Make the request on the HTTPConnection object
  648. response = self._make_request(
  649. conn,
  650. method,
  651. url,
  652. timeout=timeout_obj,
  653. body=body,
  654. headers=headers,
  655. chunked=chunked,
  656. retries=retries,
  657. response_conn=response_conn,
  658. preload_content=preload_content,
  659. decode_content=decode_content,
  660. **response_kw,
  661. )
  662. # Everything went great!
  663. clean_exit = True
  664. except EmptyPoolError:
  665. # Didn't get a connection from the pool, no need to clean up
  666. clean_exit = True
  667. release_this_conn = False
  668. raise
  669. except (
  670. TimeoutError,
  671. HTTPException,
  672. OSError,
  673. ProtocolError,
  674. BaseSSLError,
  675. SSLError,
  676. CertificateError,
  677. ProxyError,
  678. ) as e:
  679. # Discard the connection for these exceptions. It will be
  680. # replaced during the next _get_conn() call.
  681. clean_exit = False
  682. new_e: Exception = e
  683. if isinstance(e, (BaseSSLError, CertificateError)):
  684. new_e = SSLError(e)
  685. if isinstance(
  686. new_e,
  687. (
  688. OSError,
  689. NewConnectionError,
  690. TimeoutError,
  691. SSLError,
  692. HTTPException,
  693. ),
  694. ) and (conn and conn.proxy and not conn.has_connected_to_proxy):
  695. new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
  696. elif isinstance(new_e, (OSError, HTTPException)):
  697. new_e = ProtocolError("Connection aborted.", new_e)
  698. retries = retries.increment(
  699. method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
  700. )
  701. retries.sleep()
  702. # Keep track of the error for the retry warning.
  703. err = e
  704. finally:
  705. if not clean_exit:
  706. # We hit some kind of exception, handled or otherwise. We need
  707. # to throw the connection away unless explicitly told not to.
  708. # Close the connection, set the variable to None, and make sure
  709. # we put the None back in the pool to avoid leaking it.
  710. if conn:
  711. conn.close()
  712. conn = None
  713. release_this_conn = True
  714. if release_this_conn:
  715. # Put the connection back to be reused. If the connection is
  716. # expired then it will be None, which will get replaced with a
  717. # fresh connection during _get_conn.
  718. self._put_conn(conn)
  719. if not conn:
  720. # Try again
  721. log.warning(
  722. "Retrying (%r) after connection broken by '%r': %s", retries, err, url
  723. )
  724. return self.urlopen(
  725. method,
  726. url,
  727. body,
  728. headers,
  729. retries,
  730. redirect,
  731. assert_same_host,
  732. timeout=timeout,
  733. pool_timeout=pool_timeout,
  734. release_conn=release_conn,
  735. chunked=chunked,
  736. body_pos=body_pos,
  737. preload_content=preload_content,
  738. decode_content=decode_content,
  739. **response_kw,
  740. )
  741. # Handle redirect?
  742. redirect_location = redirect and response.get_redirect_location()
  743. if redirect_location:
  744. if response.status == 303:
  745. # Change the method according to RFC 9110, Section 15.4.4.
  746. method = "GET"
  747. # And lose the body not to transfer anything sensitive.
  748. body = None
  749. headers = HTTPHeaderDict(headers)._prepare_for_method_change()
  750. try:
  751. retries = retries.increment(method, url, response=response, _pool=self)
  752. except MaxRetryError:
  753. if retries.raise_on_redirect:
  754. response.drain_conn()
  755. raise
  756. return response
  757. response.drain_conn()
  758. retries.sleep_for_retry(response)
  759. log.debug("Redirecting %s -> %s", url, redirect_location)
  760. return self.urlopen(
  761. method,
  762. redirect_location,
  763. body,
  764. headers,
  765. retries=retries,
  766. redirect=redirect,
  767. assert_same_host=assert_same_host,
  768. timeout=timeout,
  769. pool_timeout=pool_timeout,
  770. release_conn=release_conn,
  771. chunked=chunked,
  772. body_pos=body_pos,
  773. preload_content=preload_content,
  774. decode_content=decode_content,
  775. **response_kw,
  776. )
  777. # Check if we should retry the HTTP response.
  778. has_retry_after = bool(response.headers.get("Retry-After"))
  779. if retries.is_retry(method, response.status, has_retry_after):
  780. try:
  781. retries = retries.increment(method, url, response=response, _pool=self)
  782. except MaxRetryError:
  783. if retries.raise_on_status:
  784. response.drain_conn()
  785. raise
  786. return response
  787. response.drain_conn()
  788. retries.sleep(response)
  789. log.debug("Retry: %s", url)
  790. return self.urlopen(
  791. method,
  792. url,
  793. body,
  794. headers,
  795. retries=retries,
  796. redirect=redirect,
  797. assert_same_host=assert_same_host,
  798. timeout=timeout,
  799. pool_timeout=pool_timeout,
  800. release_conn=release_conn,
  801. chunked=chunked,
  802. body_pos=body_pos,
  803. preload_content=preload_content,
  804. decode_content=decode_content,
  805. **response_kw,
  806. )
  807. return response
  808. class HTTPSConnectionPool(HTTPConnectionPool):
  809. """
  810. Same as :class:`.HTTPConnectionPool`, but HTTPS.
  811. :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,
  812. ``assert_hostname`` and ``host`` in this order to verify connections.
  813. If ``assert_hostname`` is False, no verification is done.
  814. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,
  815. ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`
  816. is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade
  817. the connection socket into an SSL socket.
  818. """
  819. scheme = "https"
  820. ConnectionCls: type[BaseHTTPSConnection] = HTTPSConnection
  821. def __init__(
  822. self,
  823. host: str,
  824. port: int | None = None,
  825. timeout: _TYPE_TIMEOUT | None = _DEFAULT_TIMEOUT,
  826. maxsize: int = 1,
  827. block: bool = False,
  828. headers: typing.Mapping[str, str] | None = None,
  829. retries: Retry | bool | int | None = None,
  830. _proxy: Url | None = None,
  831. _proxy_headers: typing.Mapping[str, str] | None = None,
  832. key_file: str | None = None,
  833. cert_file: str | None = None,
  834. cert_reqs: int | str | None = None,
  835. key_password: str | None = None,
  836. ca_certs: str | None = None,
  837. ssl_version: int | str | None = None,
  838. ssl_minimum_version: ssl.TLSVersion | None = None,
  839. ssl_maximum_version: ssl.TLSVersion | None = None,
  840. assert_hostname: str | Literal[False] | None = None,
  841. assert_fingerprint: str | None = None,
  842. ca_cert_dir: str | None = None,
  843. **conn_kw: typing.Any,
  844. ) -> None:
  845. super().__init__(
  846. host,
  847. port,
  848. timeout,
  849. maxsize,
  850. block,
  851. headers,
  852. retries,
  853. _proxy,
  854. _proxy_headers,
  855. **conn_kw,
  856. )
  857. self.key_file = key_file
  858. self.cert_file = cert_file
  859. self.cert_reqs = cert_reqs
  860. self.key_password = key_password
  861. self.ca_certs = ca_certs
  862. self.ca_cert_dir = ca_cert_dir
  863. self.ssl_version = ssl_version
  864. self.ssl_minimum_version = ssl_minimum_version
  865. self.ssl_maximum_version = ssl_maximum_version
  866. self.assert_hostname = assert_hostname
  867. self.assert_fingerprint = assert_fingerprint
  868. def _prepare_proxy(self, conn: HTTPSConnection) -> None: # type: ignore[override]
  869. """Establishes a tunnel connection through HTTP CONNECT."""
  870. if self.proxy and self.proxy.scheme == "https":
  871. tunnel_scheme = "https"
  872. else:
  873. tunnel_scheme = "http"
  874. conn.set_tunnel(
  875. scheme=tunnel_scheme,
  876. host=self._tunnel_host,
  877. port=self.port,
  878. headers=self.proxy_headers,
  879. )
  880. conn.connect()
  881. def _new_conn(self) -> BaseHTTPSConnection:
  882. """
  883. Return a fresh :class:`urllib3.connection.HTTPConnection`.
  884. """
  885. self.num_connections += 1
  886. log.debug(
  887. "Starting new HTTPS connection (%d): %s:%s",
  888. self.num_connections,
  889. self.host,
  890. self.port or "443",
  891. )
  892. if not self.ConnectionCls or self.ConnectionCls is DummyConnection: # type: ignore[comparison-overlap]
  893. raise ImportError(
  894. "Can't connect to HTTPS URL because the SSL module is not available."
  895. )
  896. actual_host: str = self.host
  897. actual_port = self.port
  898. if self.proxy is not None and self.proxy.host is not None:
  899. actual_host = self.proxy.host
  900. actual_port = self.proxy.port
  901. return self.ConnectionCls(
  902. host=actual_host,
  903. port=actual_port,
  904. timeout=self.timeout.connect_timeout,
  905. cert_file=self.cert_file,
  906. key_file=self.key_file,
  907. key_password=self.key_password,
  908. cert_reqs=self.cert_reqs,
  909. ca_certs=self.ca_certs,
  910. ca_cert_dir=self.ca_cert_dir,
  911. assert_hostname=self.assert_hostname,
  912. assert_fingerprint=self.assert_fingerprint,
  913. ssl_version=self.ssl_version,
  914. ssl_minimum_version=self.ssl_minimum_version,
  915. ssl_maximum_version=self.ssl_maximum_version,
  916. **self.conn_kw,
  917. )
  918. def _validate_conn(self, conn: BaseHTTPConnection) -> None:
  919. """
  920. Called right before a request is made, after the socket is created.
  921. """
  922. super()._validate_conn(conn)
  923. # Force connect early to allow us to validate the connection.
  924. if conn.is_closed:
  925. conn.connect()
  926. if not conn.is_verified:
  927. warnings.warn(
  928. (
  929. f"Unverified HTTPS request is being made to host '{conn.host}'. "
  930. "Adding certificate verification is strongly advised. See: "
  931. "https://urllib3.readthedocs.io/en/latest/advanced-usage.html"
  932. "#tls-warnings"
  933. ),
  934. InsecureRequestWarning,
  935. )
  936. def connection_from_url(url: str, **kw: typing.Any) -> HTTPConnectionPool:
  937. """
  938. Given a url, return an :class:`.ConnectionPool` instance of its host.
  939. This is a shortcut for not having to parse out the scheme, host, and port
  940. of the url before creating an :class:`.ConnectionPool` instance.
  941. :param url:
  942. Absolute URL string that must include the scheme. Port is optional.
  943. :param \\**kw:
  944. Passes additional parameters to the constructor of the appropriate
  945. :class:`.ConnectionPool`. Useful for specifying things like
  946. timeout, maxsize, headers, etc.
  947. Example::
  948. >>> conn = connection_from_url('http://google.com/')
  949. >>> r = conn.request('GET', '/')
  950. """
  951. scheme, _, host, port, *_ = parse_url(url)
  952. scheme = scheme or "http"
  953. port = port or port_by_scheme.get(scheme, 80)
  954. if scheme == "https":
  955. return HTTPSConnectionPool(host, port=port, **kw) # type: ignore[arg-type]
  956. else:
  957. return HTTPConnectionPool(host, port=port, **kw) # type: ignore[arg-type]
  958. @typing.overload
  959. def _normalize_host(host: None, scheme: str | None) -> None:
  960. ...
  961. @typing.overload
  962. def _normalize_host(host: str, scheme: str | None) -> str:
  963. ...
  964. def _normalize_host(host: str | None, scheme: str | None) -> str | None:
  965. """
  966. Normalize hosts for comparisons and use with sockets.
  967. """
  968. host = normalize_host(host, scheme)
  969. # httplib doesn't like it when we include brackets in IPv6 addresses
  970. # Specifically, if we include brackets but also pass the port then
  971. # httplib crazily doubles up the square brackets on the Host header.
  972. # Instead, we need to make sure we never pass ``None`` as the port.
  973. # However, for backward compatibility reasons we can't actually
  974. # *assert* that. See http://bugs.python.org/issue28539
  975. if host and host.startswith("[") and host.endswith("]"):
  976. host = host[1:-1]
  977. return host
  978. def _url_from_pool(
  979. pool: HTTPConnectionPool | HTTPSConnectionPool, path: str | None = None
  980. ) -> str:
  981. """Returns the URL from a given connection pool. This is mainly used for testing and logging."""
  982. return Url(scheme=pool.scheme, host=pool.host, port=pool.port, path=path).url
  983. def _close_pool_connections(pool: queue.LifoQueue[typing.Any]) -> None:
  984. """Drains a queue of connections and closes each one."""
  985. try:
  986. while True:
  987. conn = pool.get(block=False)
  988. if conn:
  989. conn.close()
  990. except queue.Empty:
  991. pass # Done.