From 3223e1209285d96cfe5ac92c68653c5690e6e721 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E8=82=96=E5=9C=A8?= <xiaozai@kylinos.cn>
Date: Mon, 6 May 2024 20:30:09 +0800
Subject: [PATCH] Fix Python parser to mark responses without length as closing

---
 CHANGES/8320.bugfix.rst   |  1 +
 aiohttp/http_parser.py    | 11 ++++++++++-
 tests/test_http_parser.py |  2 +-
 3 files changed, 12 insertions(+), 2 deletions(-)
 create mode 100644 CHANGES/8320.bugfix.rst

diff --git a/CHANGES/8320.bugfix.rst b/CHANGES/8320.bugfix.rst
new file mode 100644
index 0000000..3823e24
--- /dev/null
+++ b/CHANGES/8320.bugfix.rst
@@ -0,0 +1 @@
+Fixed the pure python parser to mark a connection as closing when a response has no length -- by :user:`Dreamsorcerer`
diff --git a/aiohttp/http_parser.py b/aiohttp/http_parser.py
index 1877f55..d7b8dac 100644
--- a/aiohttp/http_parser.py
+++ b/aiohttp/http_parser.py
@@ -703,7 +703,16 @@ class HttpResponseParser(HttpParser[RawResponseMessage]):
         ) = self.parse_headers(lines)
 
         if close is None:
-            close = version_o <= HttpVersion10
+            if version_o <= HttpVersion10:
+                close = True
+            # https://www.rfc-editor.org/rfc/rfc9112.html#name-message-body-length
+            elif 100 <= status_i < 200 or status_i in {204, 304}:
+                close = False
+            elif hdrs.CONTENT_LENGTH in headers or hdrs.TRANSFER_ENCODING in headers:
+                close = False
+            else:
+                # https://www.rfc-editor.org/rfc/rfc9112.html#section-6.3-2.8
+                close = True
 
         return RawResponseMessage(
             version_o,
diff --git a/tests/test_http_parser.py b/tests/test_http_parser.py
index b931730..0417fa4 100644
--- a/tests/test_http_parser.py
+++ b/tests/test_http_parser.py
@@ -743,7 +743,7 @@ def test_http_request_parser(parser) -> None:
     assert msg.version == (1, 1)
     assert msg.headers == CIMultiDict()
     assert msg.raw_headers == ()
-    assert not msg.should_close
+    assert msg.should_close
     assert msg.compression is None
     assert not msg.upgrade
     assert not msg.chunked
-- 
2.33.0

