Restructure redirect logic so that things like hostname lookup errors don't trigger an infinite loop.

This commit is contained in:
Solderpunk 2019-06-24 18:50:30 +03:00
parent e948ce0a13
commit 1668ed1468
1 changed files with 16 additions and 16 deletions

View File

@ -40,28 +40,28 @@ while True:
print("Sorry, Gemini links only.") print("Sorry, Gemini links only.")
continue continue
# Do the Gemini transaction, following redirects # Do the Gemini transaction, following redirects
while True: try:
try: while True:
s = socket.create_connection((parsed_url.netloc, 1965)) s = socket.create_connection((parsed_url.netloc, 1965))
context = ssl.SSLContext() context = ssl.SSLContext()
context.check_hostname = False context.check_hostname = False
context.verify_mode = ssl.CERT_NONE context.verify_mode = ssl.CERT_NONE
s = context.wrap_socket(s, server_hostname = parsed_url.netloc) s = context.wrap_socket(s, server_hostname = parsed_url.netloc)
s.sendall((parsed_url.path + '\r\n').encode("UTF-8")) s.sendall((parsed_url.path + '\r\n').encode("UTF-8"))
except: # Get header and check for redirects
print("Network error!") fp = s.makefile("rb")
continue header = fp.readline()
# Get header and check for redirects header = header.decode("UTF-8").strip()
fp = s.makefile("rb") status, mime = header.split("\t")
header = fp.readline() # If this isn't a redirect, we're done
header = header.decode("UTF-8").strip() if not status.startswith("3"):
status, mime = header.split("\t") break
# If this isn't a redirect, we're done # Follow the redirect
if not status.startswith("3"): url = absolutise_url(url, mime)
break parsed_url = urllib.parse.urlparse(url)
# Follow the redirect except Exception as err:
url = absolutise_url(url, mime) print(err)
parsed_url = urllib.parse.urlparse(url) continue
# Fail if transaction was not successful # Fail if transaction was not successful
if not status.startswith("2"): if not status.startswith("2"):
print("Error %s: %s" % (status, mime)) print("Error %s: %s" % (status, mime))