connectionpool.py 44 KB

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