Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 084daa2

Browse files
committed
Issue #16298: In HTTPResponse.read(), close the socket when there is no Content-Length and the incoming stream is finished.
Patch by Eran Rundstein.
1 parent e0035a2 commit 084daa2

4 files changed

Lines changed: 23 additions & 1 deletion

File tree

Lib/http/client.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,10 @@ def read(self, amt=None):
511511
self.length -= len(s)
512512
if not self.length:
513513
self.close()
514+
else:
515+
if not s:
516+
self.close()
517+
514518
return s
515519

516520
def _read_chunked(self, amt):

Lib/test/test_httplib.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ def test_bad_status_repr(self):
175175
self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
176176

177177
def test_partial_reads(self):
178-
# if we have a lenght, the system knows when to close itself
178+
# if we have a length, the system knows when to close itself
179179
# same behaviour than when we read the whole thing with read()
180180
body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
181181
sock = FakeSocket(body)
@@ -186,6 +186,19 @@ def test_partial_reads(self):
186186
self.assertEqual(resp.read(2), b'xt')
187187
self.assertTrue(resp.isclosed())
188188

189+
def test_partial_reads_no_content_length(self):
190+
# when no length is present, the socket should be gracefully closed when
191+
# all data was read
192+
body = "HTTP/1.1 200 Ok\r\n\r\nText"
193+
sock = FakeSocket(body)
194+
resp = client.HTTPResponse(sock)
195+
resp.begin()
196+
self.assertEqual(resp.read(2), b'Te')
197+
self.assertFalse(resp.isclosed())
198+
self.assertEqual(resp.read(2), b'xt')
199+
self.assertEqual(resp.read(1), b'')
200+
self.assertTrue(resp.isclosed())
201+
189202
def test_host_port(self):
190203
# Check invalid host_port
191204

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -917,6 +917,7 @@ Paul Rubin
917917
Sam Ruby
918918
Demur Rumed
919919
Audun S. Runde
920+
Eran Rundstein
920921
Rauli Ruohonen
921922
Jeff Rush
922923
Sam Rushing

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ Core and Builtins
179179
Library
180180
-------
181181

182+
- Issue #16298: In HTTPResponse.read(), close the socket when there is no
183+
Content-Length and the incoming stream is finished. Patch by Eran
184+
Rundstein.
185+
182186
- Issue #16248: Disable code execution from the user's home directory by
183187
tkinter when the -E flag is passed to Python. Patch by Zachary Ware.
184188

0 commit comments

Comments
 (0)