Skip to content

Commit 8ea4a5f

Browse files
committed
gh-163110: Don't read the body of a redirect response in urllib.request
1 parent 64c20ff commit 8ea4a5f

3 files changed

Lines changed: 29 additions & 1 deletion

File tree

‎Lib/test/test_urllib2.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,6 +1465,33 @@ def redirect(h, req, url=to_url):
14651465
urllib.request.HTTPRedirectHandler.max_redirections)
14661466
err.close()
14671467

1468+
def test_redirect_does_not_read_body(self):
1469+
# The body of a redirect response is closed without being read.
1470+
from_url = "http://example.com/a.html"
1471+
to_url = "http://example.com/b.html"
1472+
1473+
class UnreadFile(MockFile):
1474+
read_called = closed = False
1475+
1476+
def read(self, count=None):
1477+
self.read_called = True
1478+
1479+
def close(self):
1480+
self.closed = True
1481+
1482+
for code in 301, 302, 303, 307, 308:
1483+
with self.subTest(code=code):
1484+
h = urllib.request.HTTPRedirectHandler()
1485+
o = h.parent = MockOpener()
1486+
req = Request(from_url)
1487+
req.timeout = socket._GLOBAL_DEFAULT_TIMEOUT
1488+
fp = UnreadFile()
1489+
getattr(h, "http_error_%s" % code)(
1490+
req, fp, code, "Blah", MockHeaders({"location": to_url}))
1491+
self.assertFalse(fp.read_called)
1492+
self.assertTrue(fp.closed)
1493+
self.assertEqual(o.req.get_full_url(), to_url)
1494+
14681495
def test_invalid_redirect(self):
14691496
from_url = "http://example.com/a.html"
14701497
valid_schemes = ['http','https','ftp']

‎Lib/urllib/request.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -717,7 +717,6 @@ def http_error_302(self, req, fp, code, msg, headers):
717717

718718
# Don't close the fp until we are sure that we won't use it
719719
# with HTTPError.
720-
fp.read()
721720
fp.close()
722721

723722
return self.parent.open(new, timeout=req.timeout)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`urllib.request.HTTPRedirectHandler` no longer reads the body of a
2+
redirect response before following the redirect.

0 commit comments

Comments
 (0)