Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Include bind address in HTTP/1.1 and HTTP/2 pool keys (#8081)

Adrian1d5fa5a1f9dc
diff --git a/scrapy/core/_http2/agent.py b/scrapy/core/_http2/agent.py
index 1ab449a84..0c769a865 100644
--- a/scrapy/core/_http2/agent.py
+++ b/scrapy/core/_http2/agent.py
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
from scrapy.spiders import Spider
-ConnectionKeyT = tuple[bytes, bytes, int]
+ConnectionKeyT = tuple[bytes, bytes, int, tuple[str, int] | None]
class H2ConnectionPool:
@@ -132,7 +132,7 @@ class H2Agent:
Arguments:
uri - URI obtained directly from request URL
"""
- return uri.scheme, uri.host, uri.port
+ return uri.scheme, uri.host, uri.port, self.endpoint_factory._bindAddress
def request(self, request: Request, spider: Spider) -> Deferred[Response]:
uri = URI.fromBytes(bytes(request.url, encoding="utf-8"))
diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.py
index 614c48a3b..42ebdaace 100644
--- a/scrapy/core/downloader/handlers/http11.py
+++ b/scrapy/core/downloader/handlers/http11.py
@@ -293,7 +293,38 @@ def _tunnel_request_data(
return tunnel_req
-class _TunnelingAgent(Agent):
+class _BindAddressAgent(Agent):
+ """An Agent that adds the configured local bind address to the
+ connection pool key, so pooled connections are not shared between
+ requests bound to different addresses."""
+
+ def __init__(
+ self,
+ reactor: ReactorBase,
+ contextFactory: IPolicyForHTTPS,
+ connectTimeout: float | None = None,
+ bindAddress: tuple[str, int] | None = None,
+ pool: HTTPConnectionPool | None = None,
+ ):
+ super().__init__(reactor, contextFactory, connectTimeout, bindAddress, pool) # type: ignore[no-untyped-call]
+
+ def _requestWithEndpoint(
+ self,
+ key: tuple[Any, ...],
+ endpoint: TCP4ClientEndpoint,
+ method: bytes,
+ parsedURI: URI,
+ headers: TxHeaders | None,
+ bodyProducer: IBodyProducer | None,
+ requestPath: bytes,
+ ) -> Deferred[IResponse]:
+ key += (self._endpointFactory._bindAddress,)
+ return super()._requestWithEndpoint(
+ key, endpoint, method, parsedURI, headers, bodyProducer, requestPath
+ )
+
+
+class _TunnelingAgent(_BindAddressAgent):
"""An agent that uses a ``_TunnelingTCP4ClientEndpoint`` to make HTTPS
downloads. It may look strange that we have chosen to subclass Agent and not
ProxyAgent but consider that after the tunnel is opened the proxy is
@@ -311,7 +342,7 @@ class _TunnelingAgent(Agent):
bindAddress: tuple[str, int] | None = None,
pool: HTTPConnectionPool | None = None,
):
- super().__init__(reactor, contextFactory, connectTimeout, bindAddress, pool) # type: ignore[no-untyped-call]
+ super().__init__(reactor, contextFactory, connectTimeout, bindAddress, pool)
self._proxyConf: tuple[str, int, bytes | None] = proxyConf
self._contextFactory: IPolicyForHTTPS = contextFactory
@@ -351,7 +382,7 @@ class _TunnelingAgent(Agent):
)
-class _ScrapyProxyAgent(Agent):
+class _ScrapyProxyAgent(_BindAddressAgent):
def __init__(
self,
reactor: ReactorBase,
@@ -361,7 +392,7 @@ class _ScrapyProxyAgent(Agent):
bindAddress: tuple[str, int] | None = None,
pool: HTTPConnectionPool | None = None,
):
- super().__init__( # type: ignore[no-untyped-call]
+ super().__init__(
reactor=reactor,
contextFactory=contextFactory,
connectTimeout=connectTimeout,
@@ -456,7 +487,7 @@ class _ScrapyAgent:
pool=self._pool,
)
- return Agent(
+ return _BindAddressAgent(
reactor=reactor,
contextFactory=self._contextFactory,
connectTimeout=timeout,
diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.py
index 719d8a8c9..51d27a31a 100644
--- a/tests/utils/bases/download_handlers_http.py
+++ b/tests/utils/bases/download_handlers_http.py
@@ -957,6 +957,32 @@ class TestHttpBase(ABC):
"The 'bindaddress' request meta key is not supported by" in caplog.text
)
+ @pytest.mark.skipif(
+ sys.platform == "darwin",
+ reason="127.0.0.2 is not available on macOS by default",
+ )
+ @coroutine_test
+ async def test_download_bind_address_meta_pool_reuse(
+ self, mockserver: MockServer, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ # A pooled connection opened for one bindaddress must not be reused
+ # for a request with a different bindaddress.
+ url = mockserver.url("/client-ip", is_secure=self.is_secure)
+ async with self.get_dh() as download_handler:
+ response1 = await download_handler.download_request(
+ Request(url, meta={"bindaddress": "127.0.0.1"})
+ )
+ response2 = await download_handler.download_request(
+ Request(url, meta={"bindaddress": "127.0.0.2"})
+ )
+ if self.handler_supports_bindaddress_meta:
+ assert response1.body == b"127.0.0.1"
+ assert response2.body == b"127.0.0.2"
+ else:
+ assert (
+ "The 'bindaddress' request meta key is not supported by" in caplog.text
+ )
+
@coroutine_test
async def test_verbatim_url(self, mockserver: MockServer) -> None:
# Square brackets are encoded by safe_url_string (w3lib).