Scrapy, a fast high-level web crawling & scraping framework for Python.
Implement browser-like bad header handling for the default download handler (#7806)
Adrian4cc23566377f
diff --git a/docs/topics/download-handlers.rst b/docs/topics/download-handlers.rstindex 94e75ab6f..433a6d139 100644--- a/docs/topics/download-handlers.rst+++ b/docs/topics/download-handlers.rst@@ -130,17 +130,23 @@ using different handlers.Here is a comparison of some features of the built-in HTTP handlers, see theindividual handler docs for more differences:-================== ================= ===================== ====================-Feature H2DownloadHandler HTTP11DownloadHandler HttpxDownloadHandler-================== ================= ===================== ====================-Requires asyncio No No Yes-Requires a reactor Yes Yes No-HTTP/1.1 No Yes Yes-HTTP/2 Yes No Yes-TLS implementation ``cryptography`` ``cryptography`` Stdlib ``ssl``-HTTP proxies No Yes Yes-SOCKS proxies No No Yes-================== ================= ===================== ====================+=================== ================= ===================== ====================+Feature H2DownloadHandler HTTP11DownloadHandler HttpxDownloadHandler+=================== ================= ===================== ====================+Requires asyncio No No Yes+Requires a reactor Yes Yes No+HTTP/1.1 No Yes Yes+HTTP/2 Yes No Yes+TLS implementation ``cryptography`` ``cryptography`` Stdlib ``ssl``+HTTP proxies No Yes Yes+SOCKS proxies No No Yes+Bad header handling Not applicable Skip bad Fail+=================== ================= ===================== ====================++Bad header handling is what a handler does when a response has a bad header+line, e.g. one with no colon in it, which some servers send. Handlers that skip+bad header lines, like web browsers do, still parse the header lines that follow+them; other handlers also lose those, or cannot download such responses at all.You can find additional HTTP download handlers in thescrapy-download-handlers-incubator_ package. This package is made by the Scrapy@@ -191,6 +197,7 @@ Features and limitationsHTTP proxies No (not implemented)SOCKS proxies No (not supported by the library)HTTP/2 Yes+Bad header handling Not applicable (HTTP/2 only)``response.certificate`` :class:`twisted.internet.ssl.Certificate` objectPer-request ``bindaddress`` YesTLS implementation ``pyOpenSSL``/``cryptography``@@ -239,11 +246,16 @@ Features and limitationsHTTP proxies YesSOCKS proxies No (not supported by the library)HTTP/2 No (implemented as a separate handler)+Bad header handling Skip bad, like web browsers do``response.certificate`` :class:`twisted.internet.ssl.Certificate` objectPer-request ``bindaddress`` YesTLS implementation ``pyOpenSSL``/``cryptography``=========================== ================================================+.. versionchanged:: VERSION+ Bad header lines with no colon in them are now skipped, instead of making+ the whole response impossible to download.+Other limitations:- IPv6 support requires setting :setting:`TWISTED_DNS_RESOLVER`@@ -297,6 +309,7 @@ Features and limitationsHTTP proxies YesSOCKS proxies Yes (SOCKS5)HTTP/2 Yes+Bad header handling Fail (not supported by the library)``response.certificate`` DER bytesPer-request ``bindaddress`` No (not supported by the library)TLS implementation Standard library ``ssl``diff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex 3b5c08666..c288ae792 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -17,12 +17,19 @@ from twisted.internet.defer import Deferred, succeedfrom twisted.internet.endpoints import TCP4ClientEndpointfrom twisted.internet.protocol import Factory, Protocol, connectionDonefrom twisted.python.failure import Failure+from twisted.web._newclient import (+ HEADER,+ STATUS,+ HTTP11ClientProtocol,+ HTTPClientParser,+)from twisted.web.client import (URI,Agent,HTTPConnectionPool,ResponseDone,ResponseFailed,+ _HTTP11ClientFactory,)from twisted.web.client import Response as TxResponsefrom twisted.web.http import PotentialDataLoss, _DataLoss@@ -60,7 +67,8 @@ from ._base_http import BaseHttpDownloadHandlerif TYPE_CHECKING:from twisted.internet.base import ReactorBase- from twisted.internet.interfaces import IConsumer+ from twisted.internet.interfaces import IAddress, IConsumer+ from twisted.web._newclient import Request as TxRequest# typing.NotRequired requires Python 3.11from typing_extensions import NotRequired@@ -95,7 +103,7 @@ class HTTP11DownloadHandler(BaseHttpDownloadHandler):self._pool.maxPersistentPerHost = crawler.settings.getint("CONCURRENT_REQUESTS_PER_DOMAIN")- self._pool._factory.noisy = False+ self._pool._factory = _LenientHTTP11ClientFactoryself._contextFactory: IPolicyForHTTPS = _load_context_factory_from_settings(crawler@@ -740,3 +748,77 @@ class _ResponseReader(Protocol):reason = Failure(exc)self._finished.errback(reason)+++class _LenientHTTPClientParser(HTTPClientParser):+ """Response parser that skips bad response header lines, those with no+ colon in them, instead of failing to parse the whole response.++ Some servers send such lines, and web browsers skip them and keep parsing+ the header lines that follow. See+ https://github.com/scrapy/scrapy/issues/210.+ """++ def lineReceived(self, line: bytes) -> None:+ # A copy of twisted.web._newclient.HTTPParser.lineReceived() where the+ # header name and value are only extracted from header lines that have+ # a colon.++ # Handle the normal CR LF case.+ if line[-1:] == b"\r":+ line = line[:-1]++ if self.state == STATUS:+ self.statusReceived(line) # type: ignore[no-untyped-call]+ self.state = HEADER+ return++ # HEADER is the only other state in which lines are received, as the+ # parser switches to raw mode for the response body.+ if not line or line[0] not in b" \t":+ if self._partialHeader is not None:+ header = b"".join(self._partialHeader)+ if b":" in header:+ name, value = header.split(b":", 1)+ self.headerReceived(name, value.strip()) # type: ignore[no-untyped-call]+ else:+ logger.debug(+ f"Skipping the bad response header line {header!r}, as "+ f"it has no colon."+ )+ if not line:+ # Empty line means the header section is over.+ self.allHeadersReceived() # type: ignore[no-untyped-call]+ else:+ # Line not beginning with LWS is another header.+ self._partialHeader = [line]+ else:+ # A line beginning with LWS is a continuation of a header begun on+ # a previous line.+ self._partialHeader.append(line) # type: ignore[union-attr]+++class _LenientHTTP11ClientProtocol(HTTP11ClientProtocol):+ """Protocol that parses responses with :class:`_LenientHTTPClientParser`."""++ def request(self, request: TxRequest) -> Deferred[IResponse]:+ d: Deferred[IResponse] = super().request(request)+ # HTTP11ClientProtocol.request() hardcodes the parser class, so the+ # only way to use a different one is to replace the class of the parser+ # object that it creates. This is safe because+ # _LenientHTTPClientParser defines no additional state. The parser is+ # always there because HTTPConnectionPool only reuses connections whose+ # protocol is in the QUIESCENT state, for which request() always+ # creates a parser.+ assert self._parser is not None+ self._parser.__class__ = _LenientHTTPClientParser+ return d+++class _LenientHTTP11ClientFactory(_HTTP11ClientFactory):+ """Factory that builds :class:`_LenientHTTP11ClientProtocol` protocols."""++ noisy = False++ def buildProtocol(self, addr: IAddress | None) -> HTTP11ClientProtocol:+ return _LenientHTTP11ClientProtocol(self._quiescentCallback) # type: ignore[no-untyped-call]diff --git a/tests/mockserver/http.py b/tests/mockserver/http.pyindex c4fd4464e..6074f1475 100644--- a/tests/mockserver/http.py+++ b/tests/mockserver/http.py@@ -11,6 +11,7 @@ from tests import tests_datadirfrom .http_base import BaseMockServer, main_factoryfrom .http_resources import (ArbitraryLengthPayloadResource,+ BadHeader,BaseResource,BrokenChunkedResource,BrokenDownloadResource,@@ -52,6 +53,7 @@ class Root(BaseResource):put_child(self, b"partial", Partial())put_child(self, b"drop", Drop())put_child(self, b"raw", Raw())+ put_child(self, b"bad-header", BadHeader())put_child(self, b"echo", Echo())put_child(self, b"payload", PayloadResource())put_child(self, b"alpayload", ArbitraryLengthPayloadResource())diff --git a/tests/mockserver/http_resources.py b/tests/mockserver/http_resources.pyindex cb028bc10..969e29a8c 100644--- a/tests/mockserver/http_resources.py+++ b/tests/mockserver/http_resources.py@@ -210,6 +210,39 @@ class Raw(LeafResource):request.finish()+class BadHeader(LeafResource):+ """Sends a response with a bad header line, one with no colon in it, like+ some servers do, between two good ones.++ One of the good header lines is split into two lines, so that handling of+ such headers is also covered.+ """++ response = (+ b"HTTP/1.1 200 OK\r\n"+ b"Content-Length: 5\r\n"+ b"Content-Type: text/html\r\n"+ b"X-Folded-Header: one\r\n"+ b"\ttwo\r\n"+ b'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\r\n'+ b"X-After-Bad-Header: works\r\n"+ b"\r\n"+ b"Works"+ )++ def render_GET(self, request: Request) -> int:+ request.startedWriting = 1+ self.deferRequest(request, 0, self._delayedRender, request)+ return NOT_DONE_YET++ def _delayedRender(self, request: Request) -> None:+ request.write(self.response)+ # Clients that stop parsing headers at the bad one don't get+ # Content-Length, so they need the connection to be closed to know that+ # the response body is over.+ close_connection(request)++class Echo(LeafResource):def render_GET(self, request: Request) -> bytes:assert request.contentdiff --git a/tests/test_downloader_handler_httpx.py b/tests/test_downloader_handler_httpx.pyindex 976daacaf..27a44227d 100644--- a/tests/test_downloader_handler_httpx.py+++ b/tests/test_downloader_handler_httpx.py@@ -61,6 +61,7 @@ class HttpxDownloadHandlerMixin:class TestHttp(HttpxDownloadHandlerMixin, TestHttpBase):handler_supports_bindaddress_meta = False+ handler_bad_header_handling = "fail"@pytest.mark.skipif(sys.platform == "darwin",@@ -82,6 +83,7 @@ class TestHttp(HttpxDownloadHandlerMixin, TestHttpBase):class TestHttps(HttpxDownloadHandlerMixin, TestHttpsBase):handler_supports_bindaddress_meta = False+ handler_bad_header_handling = "fail"tls_log_message = "SSL connection to 127.0.0.1 using protocol TLSv1.3, cipher"@pytest.mark.skip(reason="The check is Twisted-specific")diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex 65244b938..9b4a38724 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -11,7 +11,7 @@ from contextlib import asynccontextmanagerfrom http import HTTPStatusfrom ipaddress import IPv4Addressfrom socket import gethostbyname-from typing import TYPE_CHECKING, Any, ClassVar+from typing import TYPE_CHECKING, Any, ClassVar, Literalfrom urllib.parse import urlparseimport pytest@@ -60,6 +60,9 @@ if TYPE_CHECKING:from tests.mockserver.http import MockServer+BadHeaderHandling = Literal["skip-bad", "skip-rest", "fail"]++class TestHttpBase(ABC):is_secure: bool = Falsehttp2: bool = False@@ -72,6 +75,14 @@ class TestHttpBase(ABC):# h2.connection.H2Connection.receive_data()), thus closing all streams that# were using it, and we handle this as a normal exception.handler_supports_http2_dataloss: bool = True+ # What the handler does with a bad response header line, e.g. one with no+ # colon in it:+ # "skip-bad": the bad line is skipped and the header lines that follow it+ # are still parsed, which is what web browsers do;+ # "skip-rest": the bad line is skipped along with the header lines that+ # follow it;+ # "fail": the response cannot be downloaded at all.+ handler_bad_header_handling: BadHeaderHandling = "skip-bad"# default headers added by the underlying library that cannot be suppressedalways_present_req_headers: ClassVar[frozenset[str]] = frozenset()default_handler_settings: ClassVar[dict[str, Any]] = {}@@ -645,6 +656,32 @@ class TestHttpBase(ABC):in caplog.text)+ @coroutine_test+ async def test_download_bad_header(self, mockserver: MockServer) -> None:+ if self.http2:+ pytest.skip("Header lines are specific to HTTP/1.x")+ request = Request(mockserver.url("/bad-header", is_secure=self.is_secure))+ async with self.get_dh() as download_handler:+ if self.handler_bad_header_handling == "fail":+ with pytest.raises(DownloadFailedError):+ await download_handler.download_request(request)+ return+ response = await download_handler.download_request(request)+ assert response.status == 200+ assert response.body == b"Works"+ # the header line that precedes the bad one+ assert response.headers.get(b"Content-Type") == b"text/html"+ # the header split into two lines, also before the bad one+ folded_header = response.headers.get(b"X-Folded-Header")+ assert folded_header is not None+ # the separator between both parts depends on the handler+ assert folded_header.split() == [b"one", b"two"]+ # the header line that follows the bad one+ expected_value = (+ b"works" if self.handler_bad_header_handling == "skip-bad" else None+ )+ assert response.headers.get(b"X-After-Bad-Header") == expected_value+@coroutine_testasync def test_download_chunked_content(self, mockserver: MockServer) -> None:request = Request(mockserver.url("/chunked", is_secure=self.is_secure))