resolverdns: better exception handling (#472)

* resolverdns: better exception handling
This commit is contained in:
ilmich
2024-02-22 20:22:14 +01:00
committed by GitHub
parent aa501e2f7d
commit cd15000d71

View File

@@ -2,13 +2,11 @@
import datetime, sys, ssl
PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3:
import urllib.parse as urlparse
import _ssl
DEFAULT_CIPHERS = _ssl._DEFAULT_CIPHERS
else:
import urlparse
DEFAULT_CIPHERS = ssl._DEFAULT_CIPHERS
from lib.requests_toolbelt.adapters import host_header_ssl
from lib import doh
@@ -21,13 +19,6 @@ from urllib3.util.ssl_ import create_urllib3_context
from urllib3.util import connection
from requests.adapters import HTTPAdapter
if 'PROTOCOL_TLS' in ssl.__dict__:
protocol = ssl.PROTOCOL_TLS
elif 'PROTOCOL_SSLv23' in ssl.__dict__:
protocol = ssl.PROTOCOL_SSLv23
else:
protocol = ssl.PROTOCOL_SSLv3
current_date = datetime.datetime.now()
CIPHERS = "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384"
@@ -59,7 +50,7 @@ class CipherSuiteAdapter(HTTPAdapter):
# hack[3/3] patch urllib3 create connection with custom function
connection.create_connection = override_dns_connection
def flushDns(domain, **kwargs):
def flushDns(self, domain, **kwargs):
del db['dnscache'][domain]
def getIp(self, domain):
@@ -71,19 +62,26 @@ class CipherSuiteAdapter(HTTPAdapter):
if not cache: # not cached
try:
ip = doh.query(domain)[0]
ip = doh.query(domain, fallback=False) # fallback is not necessary here
if ip is None or not len(ip): # resolver is not available or return no results
ip = None
else:
ip = ip[0]
logger.info('Query DoH: ' + domain + ' = ' + str(ip))
# IPv6 address
if ':' in ip:
ip = '[' + ip + ']'
self.writeToCache(domain, ip)
except Exception:
logger.error('Failed to resolve hostname, fallback to normal dns')
import traceback
logger.error(traceback.format_exc())
else:
ip = cache.get('ip')
if ip:
logger.info('Cache DNS: ' + domain + ' = ' + str(ip))
else:
logger.error('Failed to resolve hostname ' + domain + ', fallback to normal dns')
return ip
def writeToCache(self, domain, ip):
@@ -97,7 +95,7 @@ class CipherSuiteAdapter(HTTPAdapter):
try:
return super(CipherSuiteAdapter, self).send(request, **kwargs)
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.SSLError) as e:
logger.info(e)
logger.error(e)
try:
parse = urlparse.urlparse(request.url)
except:
@@ -107,7 +105,7 @@ class CipherSuiteAdapter(HTTPAdapter):
logger.info('Request for ' + domain + ' failed')
if not flushedDns:
logger.info('Flushing dns cache for ' + domain)
CipherSuiteAdapter.flushDns(domain, **kwargs)
self.flushDns(domain, **kwargs)
return self.send(request, flushedDns=True, **kwargs)
except Exception as e:
logger.error(e)