Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connectionpool.py 42KB

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