forked from bieberg0n/bjdns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bjdns2_client.py
212 lines (172 loc) · 5.56 KB
/
bjdns2_client.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
"""bjdns2_client.py
Usage:
bjdns2_client.py (-s <BJDNS2_SERVER_ADDR>) [-d <DIRECT_DNS_SERVER>] [-b <LISTEN_IP_PORT>]
Examples:
bjdns2_client.py -s "https://your.domain.name:your_port" -d "119.29.29.29"
Options:
-h --help Show this screen
-s BJDNS2_SERVER_ADDR bjdns2 server address
-d DIRECT_DNS_SERVER dns server, be used when query type is not A
-b LISTEN_IP_PORT listen ip and port
"""
from docopt import docopt
import json
from struct import (
unpack,
pack,
)
from gevent import (
socket,
monkey,
# spawn,
)
from urllib.parse import urlparse
from gevent.server import DatagramServer
from cache import Cache
from utils import (
log,
resp_from_json,
is_private_ip,
# config,
)
monkey.patch_all()
import requests
def query_by_udp(data):
s = socket.socket(2, 2)
s.settimeout(2)
s.sendto(data, (direct_dns_serv, 53))
try:
res = s.recv(512)
except socket.timeout as e:
log('query special type:', e)
return b''
else:
return res
def parse_query(data):
list_iter = iter(data[13:])
name = ''
for bit in iter(lambda: next(list_iter), 0):
name += '.' if bit < 32 else chr(bit)
type = unpack('>H', data[14+len(name):16+len(name)])
type = type[0]
return name, type
def make_data(data, ip, ttl):
# data is request
if ip:
(id, flags, quests,
answers, author, addition) = unpack('>HHHHHH', data[0:12])
flags_new = 33152
answers_new = 1
res = pack('>HHHHHH', id, flags_new, quests,
answers_new, author, addition)
res += data[12:]
dns_answer = {
'name': 49164,
'type': 1,
'classify': 1,
'ttl': ttl,
'datalength': 4
}
res += pack('>HHHLH',
dns_answer['name'],
dns_answer['type'],
dns_answer['classify'],
dns_answer['ttl'],
dns_answer['datalength'])
ip = ip.split('.')
ip_bytes = pack('BBBB', int(ip[0]), int(ip[1]),
int(ip[2]), int(ip[3]))
res += ip_bytes
return res
else:
return b''
class Bjdns2:
def __init__(self, listen, bjdns2_url):
self.cache = Cache()
ip, port_str = listen.split(':')
self.server = DatagramServer((ip, int(port_str)), self.handle)
self.session = requests.Session()
url = urlparse(bjdns2_url).netloc
self.bjdns2_host = url[:url.rfind(':')]
# self.bjdns2_ip = bjdns2_ip
def query_by_https(self, host, cli_ip):
url_template = bjdns2_url + '/?dn={}&ip={}'
# if host == self.bjdns2_host:
# return self.bjdns2_ip, 3600
# else:
if is_private_ip(cli_ip):
url = url_template.format(host, '')
else:
url = url_template.format(host, cli_ip)
r = self.session.get(url)
result = json.loads(r.text)
if result['Status'] == 0:
self.cache.write(cli_ip, result['Question'][0], result, None)
ip, ttl = resp_from_json(result)
return ip, ttl
else:
return '', 0
def query(self, data, host, q_type, cli_addr) -> bytes:
src_ip, _ = cli_addr
question = dict(name=host, type=q_type)
cache_resp = self.cache.select(src_ip, question)
if cache_resp:
if host == self.bjdns2_host or q_type != 1:
resp = data[:2] + cache_resp
log(cli_addr, '[cache]', '[Type:{}]'.format(q_type), host)
else:
ip, ttl = resp_from_json(cache_resp)
log(cli_addr, '[cache]', host, ip, '(ttl:{})'.format(ttl))
resp = make_data(data, ip, ttl)
else:
if host == self.bjdns2_host or q_type != 1:
resp = query_by_udp(data)
self.cache.write(src_ip, question, None, resp[2:])
log(cli_addr, '[Type:{}]'.format(q_type), host)
else:
ip, ttl = self.query_by_https(host, src_ip)
log(cli_addr, host, ip, '(ttl:{})'.format(ttl))
resp = make_data(data, ip, ttl)
# if ip:
# log(data, resp)
return resp
# else:
# return b''
def handle(self, data, cli_addr):
host, q_type = parse_query(data)
# if host == self.bjdns2_host or type != 1:
# log(host, type)
# resp = query_by_udp(data)
# log(cli_addr, '[Type:{}]'.format(type), host)
# elif type == 1:
try:
resp = self.query(data, host, q_type, cli_addr)
except Exception as e:
log(e)
resp = b''
self.server.sendto(resp, cli_addr)
def start(self):
self.server.serve_forever()
if __name__ == '__main__':
args = docopt(__doc__)
# if args['-c']:
# cfg = config(args['-c']).get('client')
# bjdns2_url, bjdns2_ip = cfg['bjdns2_url'], cfg['bjdns2_ip']
# direct_dns_serv = cfg.get('direct_dns_server')
# listen = cfg.get("listen")
# else:
bjdns2_url = args['-s']
direct_dns_serv = args.get('-d')
listen = args.get('-l')
if not direct_dns_serv:
direct_dns_serv = '119.29.29.29'
if not listen:
listen = '0.0.0.0:53'
log('bjdns2 client start.')
log('bjdns2 server:', bjdns2_url)
log('direct dns server:', direct_dns_serv)
log('listen:', listen)
# log()
bjdns2 = Bjdns2(listen, bjdns2_url)
bjdns2.start()