-
Notifications
You must be signed in to change notification settings - Fork 18
/
dns-redis.py
88 lines (75 loc) · 1.85 KB
/
dns-redis.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: UTF-8 -*-
import gevent
import pickle
import redis
import dnslib
from gevent import socket
#import socket
from gevent import event
rev=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
rev.bind(('',53))
ip=[]
cur=0
def preload():
for i in open('ip'):
ip.append(i)
print "load "+str(len(ip))+" ip"
def send_request(data):
global cur
ret=rev.sendto(data,(ip[cur],53))
cur=(cur+1)%len(ip)
class Cache:
def __init__(self):
self.c=redis.Redis()
def get(self,key):
tmp=self.c.get(key)
if tmp:
return pickle.loads(self.c.get(key))
else: return None
def set(self,key,value):
self.c.set(key,pickle.dumps(value))
self.c.expire(key,60*60)
def remove(self,key):
self.c.delete(key)
cache=Cache()
def handle_request(s,data,addr):
req=dnslib.DNSRecord.parse(data)
qname=str(req.q.qname)
qid=req.header.id
ret=cache.get(qname)
if ret:
ret=dnslib.DNSRecord.parse(ret)
ret.header.id=qid;
s.sendto(ret.pack(),addr)
else:
e=event.Event()
cache.set(qname+"e",e)
send_request(data)
e.wait(60)
tmp=cache.get(qname)
if tmp:
tmp=dnslib.DNSRecord.parse(tmp)
tmp.header.id=qid;
s.sendto(tmp.pack(),addr)
def handle_response(data):
req=dnslib.DNSRecord.parse(data)
qname=str(req.q.qname)
print qname
cache.set(qname,data)
e=cache.get(qname+"e")
cache.remove(qname+"e")
if e:
e.set()
e.clear()
def handler(s,data,addr):
req=dnslib.DNSRecord.parse(data)
if req.header.qr:
handle_response(data)
else:handle_request(s,data,addr)
def main():
preload()
while True:
data,addr=rev.recvfrom(8192)
gevent.spawn(handler,rev,data,addr)
if __name__ == '__main__':
main()