From b715ee0cb80721db1449bda7d19c8e278fc3577d Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Tue, 12 Sep 2017 08:43:38 +0300 Subject: [PATCH] urllib.urequest: If error happens while parsing response headers, close socket. Because otherwise, user doesn't get any response object, so cannot close socket, and it leaks. --- urllib.urequest/urllib/urequest.py | 63 ++++++++++++++++-------------- 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/urllib.urequest/urllib/urequest.py b/urllib.urequest/urllib/urequest.py index 60281777..360afc91 100644 --- a/urllib.urequest/urllib/urequest.py +++ b/urllib.urequest/urllib/urequest.py @@ -22,39 +22,44 @@ def urlopen(url, data=None, method="GET"): ai = usocket.getaddrinfo(host, port) addr = ai[0][4] + s = usocket.socket() - s.connect(addr) - if proto == "https:": - s = ussl.wrap_socket(s, server_hostname=host) + try: + s.connect(addr) + if proto == "https:": + s = ussl.wrap_socket(s, server_hostname=host) - s.write(method) - s.write(b" /") - s.write(path) - s.write(b" HTTP/1.0\r\nHost: ") - s.write(host) - s.write(b"\r\n") - - if data: - s.write(b"Content-Length: ") - s.write(str(len(data))) + s.write(method) + s.write(b" /") + s.write(path) + s.write(b" HTTP/1.0\r\nHost: ") + s.write(host) s.write(b"\r\n") - s.write(b"\r\n") - if data: - s.write(data) - l = s.readline() - protover, status, msg = l.split(None, 2) - status = int(status) - #print(protover, status, msg) - while True: + if data: + s.write(b"Content-Length: ") + s.write(str(len(data))) + s.write(b"\r\n") + s.write(b"\r\n") + if data: + s.write(data) + l = s.readline() - if not l or l == b"\r\n": - break - #print(l) - if l.startswith(b"Transfer-Encoding:"): - if b"chunked" in l: - raise ValueError("Unsupported " + l) - elif l.startswith(b"Location:"): - raise NotImplementedError("Redirects not yet supported") + protover, status, msg = l.split(None, 2) + status = int(status) + #print(protover, status, msg) + while True: + l = s.readline() + if not l or l == b"\r\n": + break + #print(l) + if l.startswith(b"Transfer-Encoding:"): + if b"chunked" in l: + raise ValueError("Unsupported " + l) + elif l.startswith(b"Location:"): + raise NotImplementedError("Redirects not yet supported") + except OSError: + s.close() + raise return s