Skip to content

Commit 91d9c16

Browse files
committed
upip: url_open: Reworking error handling to guaranteedly close socket.
1 parent 024d6bc commit 91d9c16

File tree

1 file changed

+30
-28
lines changed

1 file changed

+30
-28
lines changed

upip/upip.py

Lines changed: 30 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -117,32 +117,33 @@ def url_open(url):
117117
addr = ai[0][4]
118118

119119
s = usocket.socket(ai[0][0])
120-
#print("Connect address:", addr)
121-
s.connect(addr)
122-
123-
if proto == "https:":
124-
s = ussl.wrap_socket(s)
125-
if warn_ussl:
126-
print("Warning: %s SSL certificate is not validated" % host)
127-
warn_ussl = False
128-
129-
# MicroPython rawsocket module supports file interface directly
130-
s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
131-
l = s.readline()
132-
protover, status, msg = l.split(None, 2)
133-
if status != b"200":
134-
s.close()
135-
exc = ValueError(status)
136-
if status == b"404" or status == b"301":
137-
fatal("Package not found", exc)
138-
fatal("Unexpected error querying for package", exc)
139-
while 1:
120+
try:
121+
#print("Connect address:", addr)
122+
s.connect(addr)
123+
124+
if proto == "https:":
125+
s = ussl.wrap_socket(s)
126+
if warn_ussl:
127+
print("Warning: %s SSL certificate is not validated" % host)
128+
warn_ussl = False
129+
130+
# MicroPython rawsocket module supports file interface directly
131+
s.write("GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (urlpath, host))
140132
l = s.readline()
141-
if not l:
142-
s.close()
143-
fatal("Unexpected EOF in HTTP headers", ValueError())
144-
if l == b'\r\n':
145-
break
133+
protover, status, msg = l.split(None, 2)
134+
if status != b"200":
135+
if status == b"404" or status == b"301":
136+
raise NotFoundError("Package not found")
137+
raise ValueError(status)
138+
while 1:
139+
l = s.readline()
140+
if not l:
141+
raise ValueError("Unexpected EOF in HTTP headers")
142+
if l == b'\r\n':
143+
break
144+
except Exception as e:
145+
s.close()
146+
raise e
146147

147148
return s
148149

@@ -215,9 +216,10 @@ def install(to_install, install_path=None):
215216
if deps:
216217
deps = deps.decode("utf-8").split("\n")
217218
to_install.extend(deps)
218-
except NotFoundError:
219-
print("Error: cannot find '%s' package (or server error), packages may be partially installed" \
220-
% pkg_spec, file=sys.stderr)
219+
except Exception as e:
220+
print("Error installing '{}': {}, packages may be partially installed".format(
221+
pkg_spec, e),
222+
file=sys.stderr)
221223

222224
def get_install_path():
223225
global install_path

0 commit comments

Comments
 (0)