-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcache.py
50 lines (40 loc) · 1.44 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import time
from utils import info
def host_add_dot(host):
if not host.endswith('.'):
host += '.'
return host
class Cache:
def __init__(self):
self.cache = dict()
def write(self, src_ip: str, question: map, resp) -> None:
if not self.cache.get(src_ip):
self.cache[src_ip] = dict()
q_type, name = question.get('type'), host_add_dot(question.get('name'))
key = (q_type, name)
self.cache[src_ip][key] = dict()
self.cache[src_ip][key]['mtime'] = int(time.time())
self.cache[src_ip][key]['data'] = resp.raw
self.cache[src_ip][key]['ttl'] = resp.ttl
def select(self, src_ip: str, question: map):
dns_type, name = question.get('type'), question.get('name')
name = host_add_dot(name)
try:
value = self.cache.get(src_ip).get((dns_type, name))
response = value.get('response')
except Exception:
return None
else:
now = time.time()
if response:
ttls = [answer['TTL'] for answer in value['response']['Answer']]
resp = value['response']
else:
resp = value['data']
ttls = [value['ttl']]
for ttl in ttls:
if now - value['mtime'] > ttl:
info(question['name'], 'Need update')
return None
else:
return resp