Skip to content

gh-112064: fix incorrect handling of negative read sizes in HTTPResponse.read() #128270

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jan 28, 2025
4 changes: 3 additions & 1 deletion Lib/http/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,7 @@ def read(self, amt=None):
if self.chunked:
return self._read_chunked(amt)

if amt is not None:
if amt is not None and amt >= 0:
if self.length is not None and amt > self.length:
# clip the read to the "end of response"
amt = self.length
Expand Down Expand Up @@ -590,6 +590,8 @@ def _get_chunk_left(self):

def _read_chunked(self, amt=None):
assert self.chunked != _UNKNOWN
if amt is not None and amt < 0:
amt = None
value = []
try:
while (chunk_left := self._get_chunk_left()) is not None:
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_httplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,25 @@ def test_chunked(self):
self.assertEqual(resp.read(), expected)
resp.close()

# Explicit full read
for n in (-123, -1, None):
with self.subTest('full read', n=n):
sock = FakeSocket(chunked_start + last_chunk + chunked_end)
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
self.assertTrue(resp.chunked)
self.assertEqual(resp.read(n), expected)
resp.close()

# Read first chunk
with self.subTest('read1(-1)'):
sock = FakeSocket(chunked_start + last_chunk + chunked_end)
resp = client.HTTPResponse(sock, method="GET")
resp.begin()
self.assertTrue(resp.chunked)
self.assertEqual(resp.read1(-1), b"hello worl")
resp.close()

# Various read sizes
for n in range(1, 12):
sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix incorrect handling of negative read sizes in :meth:`HTTPResponse.read
<http.client.HTTPResponse.read>`. Patch by Yury Manushkin.
Loading