+def _humanize_bytes(b):
+ b = int(b)
+ i = 0
+ table = " kMGTPEZYRQ"
+ while b > 1024:
+ i += 1
+ b /= 1024.0
+ if i == 0:
+ return "%dB" % (b)
+ else:
+ return "%.2f%siB" % (b, table[i])
+
+def _do_request(url, try_aia=False):
+ """
+ Return value is a tuple consisting of:
+ - the HTTPResponse object, or a string on error. Empty string -> no response.
+ - and a flag indicating whether AIA was used
+ """
+ try:
+ request = urllib2.Request(url, headers={
+ 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
+ 'accept-language': 'en-US,en;q=0.9',
+ 'cache-control': 'max-age=0',
+ 'sec-ch-ua': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
+ 'sec-ch-ua-mobile': '?0',
+ 'sec-ch-ua-platform': '"Linux"',
+ 'sec-fetch-dest': 'document',
+ 'sec-fetch-mode': 'navigate',
+ 'sec-fetch-site': 'none',
+ 'sec-fetch-user': '?1',
+ 'upgrade-insecure-requests': '1',
+ 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'
+ })
+ except ValueError:
+ return '', False
+ if try_aia:
+ try:
+ opener = urllib2.build_opener(urllib2.HTTPSHandler(context=aia_session.ssl_context_from_url(url)), SmartRedirectHandler())
+ except aia.AIAError as e:
+ return 'Request error: %s.%s: %s' % (e.__module__, e.__class__.__name__, e.args[0]), True
+ else:
+ opener = urllib2.build_opener(SmartRedirectHandler())
+
+ # Send request and handle errors
+ try:
+ response = opener.open(request, timeout=2)
+ except http.client.InvalidURL as e: # why does a method under urllib.request raise an exception under http.client???
+ return '', False
+ except urllib2.HTTPError as e:
+ return 'Request error: %s %s' % (e.code, e.reason), False
+ except urllib2.URLError as e:
+ if "certificate verify failed: unable to get local issuer certificate" in str(e.reason):
+ if aia: # Retry with AIA enabled, if module is present
+ return _do_request(url, True)
+ else:
+ lib.parent.log('urls', '?', 'If the site is not serving the certificate chain, installing the aia library might make this request work: pip install aia')
+ return 'Request error: site may have broken TLS configuration (%s)' % (e.reason), False
+ else:
+ return 'Request error: %s' % (e.reason), False
+ except TimeoutError as e:
+ return 'Request error: request timed out', False
+ except Exception as e:
+ return 'Unknown error: %s %r' % (type(e).__name__, e.args), False
+
+ return response, try_aia
+
+