DNS cache: rinnovo dopo 7 giorni

This commit is contained in:
mac12m99
2021-08-16 18:19:30 +02:00
parent c7eadf01b1
commit 7404c8cbe2
+14 -6
View File
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os, sys, ssl import datetime, sys, ssl
PY3 = False PY3 = False
if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int
if PY3: if PY3:
@@ -24,6 +24,8 @@ elif 'PROTOCOL_SSLv23' in ssl.__dict__:
else: else:
protocol = ssl.PROTOCOL_SSLv3 protocol = ssl.PROTOCOL_SSLv3
current_date = datetime.datetime.now()
class CustomContext(ssl.SSLContext): class CustomContext(ssl.SSLContext):
def __init__(self, protocol, hostname, *args, **kwargs): def __init__(self, protocol, hostname, *args, **kwargs):
@@ -54,10 +56,13 @@ class CipherSuiteAdapter(host_header_ssl.HostHeaderSSLAdapter):
return self.send(request, flushedDns=True, **kwargs) return self.send(request, flushedDns=True, **kwargs)
def getIp(self, domain): def getIp(self, domain):
ip = db['dnscache'].get(domain, None) cache = db['dnscache'].get(domain, {})
logger.info('Cache DNS: ' + domain + ' = ' + str(ip)) ip = None
if type(cache) != dict or (cache.get('datetime') and
current_date - cache.get('datetime') > datetime.timedelta(days=7)):
cache = None
if not ip: # not cached if not cache: # not cached
try: try:
ip = doh.query(domain)[0] ip = doh.query(domain)[0]
logger.info('Query DoH: ' + domain + ' = ' + str(ip)) logger.info('Query DoH: ' + domain + ' = ' + str(ip))
@@ -65,11 +70,14 @@ class CipherSuiteAdapter(host_header_ssl.HostHeaderSSLAdapter):
except Exception: except Exception:
logger.error('Failed to resolve hostname, fallback to normal dns') logger.error('Failed to resolve hostname, fallback to normal dns')
import traceback import traceback
logger.error(traceback.print_exc()) logger.error(traceback.format_exc())
else:
ip = cache.get('ip')
logger.info('Cache DNS: ' + domain + ' = ' + str(ip))
return ip return ip
def writeToCache(self, domain, ip): def writeToCache(self, domain, ip):
db['dnscache'][domain] = ip db['dnscache'][domain] = {'ip': ip, 'datetime': current_date}
def init_poolmanager(self, *args, **kwargs): def init_poolmanager(self, *args, **kwargs):
kwargs['ssl_context'] = self.ssl_context kwargs['ssl_context'] = self.ssl_context