Skip to content

Commit 153365d

Browse files
authored
[3.9] bpo-42853: Fix http.client fails to download >2GiB data over TLS (GH-27405)
Revert "bpo-36050: optimize HTTPResponse.read() (GH-12698)" This reverts commit d6bf6f2.
1 parent a13edfb commit 153365d

2 files changed

Lines changed: 33 additions & 10 deletions

File tree

‎Lib/http/client.py‎

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,9 @@
105105
# Mapping status codes to official W3C names
106106
responses = {v: v.phrase for v in http.HTTPStatus.__members__.values()}
107107

108+
# maximal amount of data to read at one time in _safe_read
109+
MAXAMOUNT = 1048576
110+
108111
# maximal line length when calling readline().
109112
_MAXLINE = 65536
110113
_MAXHEADERS = 100
@@ -604,24 +607,43 @@ def _readinto_chunked(self, b):
604607
raise IncompleteRead(bytes(b[0:total_bytes]))
605608

606609
def _safe_read(self, amt):
607-
"""Read the number of bytes requested.
610+
"""Read the number of bytes requested, compensating for partial reads.
611+
612+
Normally, we have a blocking socket, but a read() can be interrupted
613+
by a signal (resulting in a partial read).
614+
615+
Note that we cannot distinguish between EOF and an interrupt when zero
616+
bytes have been read. IncompleteRead() will be raised in this
617+
situation.
608618
609619
This function should be used when <amt> bytes "should" be present for
610620
reading. If the bytes are truly not available (due to EOF), then the
611621
IncompleteRead exception can be used to detect the problem.
612622
"""
613-
data = self.fp.read(amt)
614-
if len(data) < amt:
615-
raise IncompleteRead(data, amt-len(data))
616-
return data
623+
s = []
624+
while amt > 0:
625+
chunk = self.fp.read(min(amt, MAXAMOUNT))
626+
if not chunk:
627+
raise IncompleteRead(b''.join(s), amt)
628+
s.append(chunk)
629+
amt -= len(chunk)
630+
return b"".join(s)
617631

618632
def _safe_readinto(self, b):
619633
"""Same as _safe_read, but for reading into a buffer."""
620-
amt = len(b)
621-
n = self.fp.readinto(b)
622-
if n < amt:
623-
raise IncompleteRead(bytes(b[:n]), amt-n)
624-
return n
634+
total_bytes = 0
635+
mvb = memoryview(b)
636+
while total_bytes < len(b):
637+
if MAXAMOUNT < len(mvb):
638+
temp_mvb = mvb[0:MAXAMOUNT]
639+
n = self.fp.readinto(temp_mvb)
640+
else:
641+
n = self.fp.readinto(mvb)
642+
if not n:
643+
raise IncompleteRead(bytes(mvb[0:total_bytes]), len(b))
644+
mvb = mvb[n:]
645+
total_bytes += n
646+
return total_bytes
625647

626648
def read1(self, n=-1):
627649
"""Read with at most one underlying system call. If at least one
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``http.client.HTTPSConnection`` fails to download >2GiB data.

0 commit comments

Comments
 (0)