Skip to content

Commit

Permalink
[3.12] pythongh-112064: Fix incorrect handling of negative read sizes…
Browse files Browse the repository at this point in the history
… in `HTTPResponse.read()` (pythonGH-128270) (python#129396)

pythongh-112064: Fix incorrect handling of negative read sizes in `HTTPResponse.read()` (pythonGH-128270)

The parameter `amt` of `HTTPResponse.read()`, which could be a negative integer,
has not been handled before and led to waiting for the connection to close
for `keep-alive connections`. Now, this has been fixed, and passing negative values
to `HTTPResponse().read()` works the same as passing `None` value.
(cherry picked from commit 4d0d24f)

Co-authored-by: Yury Manushkin <manushkin@gmail.com>
  • Loading branch information
miss-islington and manushkin authored Jan 28, 2025
1 parent ea143e6 commit e5ab9e3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
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 @@ -1078,6 +1078,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.

0 comments on commit e5ab9e3

Please sign in to comment.