forked from henices/Tcp-DNS-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tcpdns.py
executable file
·605 lines (487 loc) · 22 KB
/
tcpdns.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# cody by [email protected]
#
# Change log:
#
# 2011-10-23 use SocketServer to run a multithread udp server
# 2012-04-16 add more public dns servers support tcp dns query
# 2013-05-14 merge code from @linkerlin, add gevent support
# 2013-06-24 add lru cache support
# 2013-08-14 add option to disable cache
# 2014-01-04 add option "servers", "timeout" @jinxingxing
# 2014-04-04 support daemon process on unix like platform
# 2014-05-27 support udp dns server on non-standard port
# 2014-07-08 use json config file
# 2014-07-09 support private host
# 2015-01-14 support dns server auto switch
# 2018-09-01 add DNS compression pointer mutation and pseudo-package filter to Anti DNS Poisoning & hijack(ISP Level)
# 2022-06-06 support Python 3.x
# 8.8.8.8 google
# 8.8.4.4 google
# 208.67.222.222 OpenDNS
# 208.67.220.220 OpenDNS
import gevent
from pylru import lrucache
import os,sys,random,time,json,argparse,logging,struct,socket,ctypes
from fnmatch import fnmatch
# import third_party
if sys.version_info.major < 3: import SocketServer; py2 = 1
else: import socketserver as SocketServer; py2 = 0
cfg = {}
LRUCACHE = []
DNS_SERVERS = None
FAST_SERVERS = None
SPEED = {}
DATA = {'err_counter': 0, 'speed_test': False}
UDPMODE = False
PIDFILE = '/tmp/tcpdns.pid'
def cfg_logging(dbg_level):
""" logging format
"""
logging.basicConfig(format='[%(asctime)s][%(levelname)s] %(message)s', level=dbg_level)
def hexdump(src, width=16):
""" hexdump, default width 16
"""
FILTER = ''.join(
[(x < 0x7f and x > 0x1f) and chr(x) or '.' for x in range(256)])
result = []
for i in xrange(0, len(src), width):
s = src[i:i + width]
hexa = ' '.join(["%02X" % ord(x) for x in s])
printable = s.translate(FILTER)
result.append("%04X %s %s\n" % (i, hexa, printable))
return ''.join(result)
def bytetodomain(s):
"""bytetodomain
03www06google02cn00 => www.google.cn
"""
qnl = []
domain = ''
i = 0
length = struct.unpack('!B', s[0:1])[0]
while length != 0:
i += 1
qnl.append(s[i-1:i + length])
domain += s[i:i + length].decode()
i += length
length = struct.unpack('!B', s[i:i + 1])[0]
if length != 0: # 可取消判断,带根域“.”
domain += '.'
return (domain, qnl)
def dnsping(ip, port):
buff = b"\x00\x16\xb2\xc3\x01\x00\x00\x01"
buff += b"\x00\x00\x00\x00\x00\x00\x01\x67" # '\x67' == 'g'
buff += b"\x02\x63\x6e\x00\x00\x01\x00\x01" # '\x63\x6e' == 'cn'
cost = 100
begin = time.time()
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(cfg['socket_timeout'])
s.connect((ip, int(port)))
s.send(buff)
s.recv(512)
except Exception as e:
logging.error('%s:%s, %s' % (ip, port, str(e)))
else:
cost = time.time() - begin
key = '%s:%d' % (ip, int(port))
if key not in SPEED:
SPEED[key] = []
SPEED[key].append(cost)
def TestSpeed():
global DNS_SERVERS, FAST_SERVERS, DATA
DATA['speed_test'] = True
if cfg['udp_mode']:
servers = cfg['udp_dns_server']
else:
servers = cfg['tcp_dns_server']
logging.info('Testing dns server speed ...')
jobs = []
for i in xrange(0, 6):
for s in servers:
ip, port = s.split(':')
jobs.append(gevent.spawn(dnsping, ip, port))
gevent.joinall(jobs)
cost = {}
for k, v in SPEED.items():
cost[k] = sum(v)
d = sorted(cost, key=cost.get)
FAST_SERVERS = d[:3]
DNS_SERVERS = FAST_SERVERS
DATA['err_counter'] = 0
DATA['speed_test'] = False
def private_dns_response(data):
ret = None
TID = data[0:2]
Questions = data[4:6]
AnswerRRs = data[6:8]
AuthorityRRs = data[8:10]
AdditionalRRs = data[10:12]
q_name, qnl = bytetodomain(data[12:])
lqn = len(q_name)
# q_type = struct.unpack('!h', data[-4:-2])[0] # q_type 处理有问题 未考虑查询包含Additional的附加内容,还有其它几处也是如此
q_type = struct.unpack('!H', data[14+lqn:16+lqn])[0]
logging.debug('domain:%s, qtype:%x' % (q_name, q_type))
try:
if q_type != 0x0001:
return
if Questions != b'\x00\x01' or AnswerRRs != b'\x00\x00' or AuthorityRRs != b'\x00\x00': # or AdditionalRRs != '\x00\x00'
return
items = cfg['private_host'].items()
for domain, ip in items:
if fnmatch(q_name, domain):
ret = TID
ret += b'\x81\x80'
ret += b'\x00\x01'
ret += b'\x00\x01'
ret += b'\x00\x00'
ret += b'\x00\x00'
ret += data[12:]
ret += b'\xc0\x0c'
ret += b'\x00\x01'
ret += b'\x00\x01'
ret += b'\x00\x00\xff\xff'
ret += b'\x00\x04'
ret += socket.inet_aton(ip)
finally:
return (q_type, q_name, ret)
def QueryDNS(server, port, qdata): # 处理传入的UDP包,转发给上游DNS
"""tcp dns request
Args:
server: remote tcp dns server
port: remote tcp dns port
qdata - querydata: udp dns request packet data
Returns:
tcp dns response data
"""
global DATA, DNS_SERVERS
if DATA['err_counter'] > 10 and not DATA['speed_test']:
TestSpeed()
q_name, qnl = bytetodomain(qdata[12:])
lqn = len(q_name)
qll = len(qnl)
AdditionalRRs = qdata[10:12]
rf = len_AddRRs = 0
rand_s = 0
rand_e = 5
if '8.8.4.4:53' in DNS_SERVERS: rand_e = 3 # 0-3 query
else: rand_s = 4 # 4-5 query
# add DNS compression pointer mutation
if qll > 1:# and UDPMODE: # not root or gTLD and only UDP mode
if AdditionalRRs != b'\x00\x00': AddRRs = qdata[18+lqn:] # 判断是否含有附加部分,并提取
else:
AddRRs = b'\x00\x00\x29\x10\x00\x00\x00\x00\x00\x00\x00' # 否则自定义附加部分 0000291000000000000000 len=11(0x0b)
AdditionalRRs = b'\x00\x01'
len_AddRRs = len(AddRRs) # 计算附加部分的长度 # len(qdata) - lqn - 18
cpl = [b'\xC0\x04', b'\xC0\x06', b'\xC0\x07', b'\xC0\x08', b'\xC0\x09', b'\xC0\x0a'] # 结束指针 列表
rf = random.randint(rand_s,rand_e) # rf=0|1时 排序重组 随机2-n查询 2|3时 分别使用2|3查询 4|5 1查询 并过滤伪包 可用其他国外DNS 目前已知仅8888和8844支持多查询
if rf < 2 or qll > 4: # qnl 重组 2-n查询
qi = random.randint(2,qll)
qdi = b'\x00' + struct.pack('!B', qi) # 查询数 随机2-n查询
lp = [b''] * (qll) # qnl[i+1] 的 偏移指针 lp[i] 即指向 qnl[i+1] 的偏移量
lp[qll-1] = random.choice(cpl) # qnl[qll-1] 后的 结束指针
li = list(range(1,qll)) # range(qll)[1:] [1, 2, 3, ..., qll-1]
if rf: random.shuffle(li) # 随机排序 否则 逆序
else: li.reverse() # li = [qll-1, ..., 3, 2, 1]
qdn = [qnl[0], b'\xC0\x30', qdata[lqn + 14: lqn + 18]] # 查询数据部分 第一个查询 qnl[1]的指针(占位) 查询类型
idx = 0x12+len(qnl[0]) # 当前相对偏移 12+2+4=18(0x12)
# 方法1,使用列表索引
for n,i in enumerate(li): # li=[3, 2, 1]
qdn.append(qnl[i])
lp[i-1] = b'\xC0' + struct.pack('!B', idx) # 偏移量
qdn.append(b'\xC0\x3d') # qdn.append('\xC0' + struct.pack('!B',0x31 + i)) 指针占位符 '\xC0\x3d'
qdn.append(struct.pack('!I',random.randint(0,0xFFFFFFFF))) # b'\x00\x01\x00\x01' # 附加随机 QTYPE+QCLASS
idx += len(qnl[i]) + 6
if n+2 == qi: idx += len_AddRRs
for n,i in enumerate([0]+li): qdn[n*3+1] = lp[i] # 写入指针偏移
qdn.insert(qi*3, AddRRs) # 插入 附加数据
''' 方法2,无列表索引,后面使用 qdn.index 查找索引,逻辑较简单
for v in li: # li = [2, 1, 0]
qdn.append(qnl[v])
lp[v] = '\xC0' + struct.pack('!B', idx)
# idx += len(qnl[v])
if v == qll - 1: qdn.append(random.choice(cpl)) # 判断 并且附加结束指针
else: qdn.append('\xC0' + struct.pack('!B',0x31 + v))
if rf: idx += len(qnl[v]) + 2
else:
qdn.append('\x00' + '\x01' + '\x00' + '\x01')
idx += len(qnl[v]) + 6
for i,v in enumerate(lp): qdn[qdn.index('\xC0' + struct.pack('!B',0x30 + i))] = v
qdn.append(AddRRs) # 添加 附加数据
'''
elif rf > 3: # rf=4|5 1查询
qdi = b'\x00\x01'
if rf > 4: qdn = [qdata[12:lqn+13], random.choice(cpl), qdata[lqn+14:lqn+18], AddRRs] # 仅修改结束指针,返回2个伪包
else: # rn后移 随机排序
cpl += [b'\xC0\x0e', b'\xC0\x10']
lp = [b''] * (qll + 1) # rn的指针数据
lp[qll] = random.choice(cpl)
li = list(range(qll))
random.shuffle(li) # li=[0, 3, 2, 1]
qdn = [b'\xC0\x30', qdata[lqn + 14: lqn + 18], AddRRs] # 第一个查询的指针 查询类型 附加数据
idx = 0x12 + len_AddRRs
for i in li: # i=0,3,2,1
qdn.append(qnl[i])
lp[i] = b'\xC0' + struct.pack('!B', idx)
qdn.append(b'\xC0\x3d') # qdn.append('\xC0' + struct.pack('!B',0x31 + v)) 指针占位符 '\xC0\x3d'
idx += len(qnl[i]) + 2
for n,i in enumerate(li): qdn[n*2+4] = lp[i+1] # 写入指针偏移
qdn[0] = lp[0]
else: # rf=2|3 r2后移 随机使用2|3个查询
qdi = b'\x00' + struct.pack('!B', rf) # 2|3查询
r1 = qnl[-1] # 顶级域名gTLD
r2 = qnl[-2] # 一级域名
cp_r2 = 0 # r2的偏移指针
cp_r1 = lqn-len(r2)-len(r1)+19 # 计算 r1的偏移指针 len(rn)-len(r2)-len(r1)+6+12
qdn = qnl[:-2] # 提取 r2 前的子域名数据
qdn.append(b'\xC0\x00') # 添加占位字符串 r2的偏移指针
qdn.append(qdata[14+lqn:18+lqn]) # 添加QTYPE和QCLASS
qdn.append(r1)
cpl += [b'\x00', b'\x00', b'\x00', b'\x00']
cpe = random.choice(cpl)
qdn.append(cpe) # 添加 结束指针
qdn.append(struct.pack('!I',random.randint(0,0xFFFFFFFF))) # 尾部 QTYPE:A QCLASS:IN 固定值 00010001 不影响查询
if rf == 2: # 2查询
qdn.append(AddRRs) # 先添加 附加数据
cp_r2 += len(AddRRs)
qdn.append(r2) # 添加 r2
qdn.append(struct.pack('!2B',0xc0,cp_r1)) # 添加 r1的偏移指针
qdn.append(struct.pack('!I',random.randint(0,0xFFFFFFFF))) # 多添加一个 QTYPE:A QCLASS:IN 和 附加数据
qdn.append(AddRRs)
''' # 原始逻辑 2查询后面不会多出 QTYPE:A QCLASS:IN 和 附加数据
if rf == 2: # 2查询
qdn.append(AddRRs) # 添加 附加数据
cp_r2 += len(AddRRs)
qdi = '\x00\x02' # 查询数写为2
qdn.append(r2) # 添加 r2
qdn.append(struct.pack('!2B',0xc0,cp_r1)) # 添加 r1的偏移指针
else: # 3查询
qdn.append(r2) # 添加 r2 (后移为第3个查询)
qdn.append(struct.pack('!2B',0xc0,cp_r1)) # 添加 r1的偏移指针
qdn.append('\x00\x01\x00\x01') # 多添加一个 QTYPE:A QCLASS:IN
qdn.append(AddRRs) # 附加数据
'''
cp_r2 += lqn-len(r2)+len(cpe)+23 # 计算 r2的偏移指针 len(rn)-len(r2)+5|6+6+12; 其中 len(rn)=lqn+1 (尾部 结束指针|00 00010001 共5|6字节;指针偏移+QTYPE+QCLASS共6字节;头部12字节)
qdn[len(qnl[:-2])] = struct.pack('!2B',0xc0,cp_r2) # 写入 r2的偏移指针
# 结果:
# qdn = [03777777, C02a, 00010001, 03636f6d, 00 00010001, 0000291000000000000000, 06676f6f676c65, C016, 00010001, 0000291000000000000000]
# qdn = [03777777, C01f, 00010001, 03636f6d, 00 00010001, 06676f6f676c65, C016, 00010001, 0000291000000000000000]
logging.debug('Query rand: %d\tQuery Count: %d' % (rf,ord(qdi[1:])))
logging.debug('qdn= %s' % qdn)
qdl = [qdata[0:4], qdi, qdata[6:10], AdditionalRRs] + qdn # 添加头部 合成数据
#print('%r\n----------------------------------------'%qdl)
qdata = b''.join(qdl) # 修改数据包,生成新的 qdata
# length
Buflen = struct.pack('!H', len(qdata))
sendbuf = UDPMODE and qdata or Buflen + qdata
data = None
protocol = UDPMODE and socket.SOCK_DGRAM or socket.SOCK_STREAM
s = socket.socket(socket.AF_INET, protocol)
# set socket timeout fix TCP-timeout
s_tmo = UDPMODE and cfg['socket_timeout'] or cfg['socket_timeout'] + 3
s.settimeout(s_tmo)
logging.debug('Send Questions: %s'%' '.join('%02X'%(ord(x) if py2 else x) for x in sendbuf)) # repr(qdata).replace('\\x', '')[1:-1]
try:
s.connect((server, int(port)))
s.send(sendbuf)
# pseudo-package filter
i = 0
while i < 3:
data = s.recv(2048)
logging.debug('Recv Data: %s'%''.join('%02X'%(ord(x) if py2 else x) for x in data))
if rf < 4: break # 不过滤多查询 部分ISP 8.8.8.8 返回错误
if not UDPMODE: break # 不过滤TCP查询 UDP53有污染 TCP53被RST
if AdditionalRRs == b'\x00\x00': break # 请求包中没有 附加数据
recv_AddRRs = UDPMODE and data[10:12] or data[12:14] # 响应包中附加RR的数量
if recv_AddRRs == AdditionalRRs: break
else:
# data = None
i += 1
continue
logging.debug('Remote Answers: %s'%' '.join('%02X'%(ord(x) if py2 else x) for x in data))
except Exception as e:
DATA['err_counter'] += 1
logging.error('Server %s:%s %s' % (server,port, str(e)))
else:
return data
finally:
if s: s.close()
'''
def check_dns_packet(data, q_type): # 响应包检查 不使用
global UDPMODE
test_ipv4 = False
test_ipv6 = False
if len(data) < 12:
return False
Flags = UDPMODE and data[2:4] or data[4:6]
AddRRs = UDPMODE and data[10:12] or data[12:14] # 检查并移除附加部分,使用请求包中附加部分的长度,可能会有问题?
if AddRRs != '\x00\x00':
if len_AddRRs != 0: data = data[:-len_AddRRs]
Reply_code = struct.unpack('!H', Flags)[0] & 0x000F
# TODO: need more check
if Reply_code == 3: # RCODE(Response code)由服务端在响应中设置的 4 位响应代码
return True
0 – 没有错误。
1 – 格式错误。服务器无法解释请求。
2 – 服务器失败。因为服务器的某些故障而不能完成解析请求。
3 – 名字错误。这个错误代码只会出现在授权的域名服务器的响应中,含义为请求查询的域名不存在。
4 – 未实现。当前服务器不支持这种查询。
5 – 拒绝。服务器主动拒绝当前的查询请求。
6 ~ 15 – 为其他失败保留的代码。
if q_type == 0x0001: # A 记录
# 处理有问题,未考虑附加部分的记录,暂时使用移除附加部分来解决
ipv4_len = data[-6:-4]
ipv4_answer_class = data[-12:-10]
ipv4_answer_type = data[-14:-12]
test_ipv4 = (ipv4_len == '\x00\x04' and \
ipv4_answer_class == '\x00\x01' and \
ipv4_answer_type == '\x00\x01')
if not test_ipv4:
ipv6_len = data[-18:-16]
ipv6_answer_class = data[-24:-22]
ipv6_answer_type =data[-26:-24]
test_ipv6 = (ipv6_len == '\x00\x10' and \
ipv6_answer_class == '\x00\x01' and \
ipv6_answer_type == '\x00\x1c')
if not (test_ipv4 or test_ipv6):
return False
return Reply_code == 0
'''
def transfer(querydata, addr, server):
"""send udp dns respones back to client program
Args:
querydata: udp dns request data
addr: udp dns client address
server: udp dns server socket
Returns:
None
"""
global UDPMODE
if len(querydata) < 12: return
response = None
t_id = querydata[:2]
key = ''.join(['%02x'%(ord(x) if py2 else x) for x in querydata[2:]]) # querydata[2:].encode('hex')
q_type, q_name, response = private_dns_response(querydata)
if response:
server.sendto(response, addr)
return
UDPMODE = cfg['udp_mode']
if FAST_SERVERS:
DNS_SERVERS = FAST_SERVERS
else:
DNS_SERVERS = UDPMODE and cfg['udp_dns_server'] or cfg['tcp_dns_server']
if cfg['internal_dns_server'] and cfg['internal_domain']:
for item in cfg['internal_domain']:
if fnmatch(q_name, item):
UDPMODE = True
DNS_SERVERS = cfg['internal_dns_server']
# logging.debug('Key Hit Cache:%r\n'%(key in LRUCACHE))
if cfg['enable_lru_cache'] and key in LRUCACHE: # Hit cache
response = LRUCACHE[key]
# sendbuf = UDPMODE and response[2:] or response[4:]
server.sendto(t_id + response[2:], addr)
return
if cfg['enable_server_switch']: random.shuffle(DNS_SERVERS) # switch DNS_SERVERS sls=DNS_SERVERS[:] copy
for item in DNS_SERVERS:
ip, port = item.split(':')
logging.debug("server: %s port:%s" % (ip, port))
response = QueryDNS(ip, port, querydata)
if response is None: # or not check_dns_packet(response, q_type): 不检查DNS响应包
continue
sendbuf = UDPMODE and response or response[2:]
if cfg['enable_lru_cache'] and len(sendbuf) > 12: LRUCACHE[key] = sendbuf
server.sendto(sendbuf, addr)
break
if response is None:
logging.error('******** Tried many times failed to resolve %s' % q_name)
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
def __init__(self, s, t):
SocketServer.UDPServer.__init__(self, s, t)
class ThreadedUDPRequestHandler(SocketServer.BaseRequestHandler):
# Ctrl-C will cleanly kill all spawned threads
daemon_threads = True
# much faster rebinding
allow_reuse_address = True
def handle(self):
data = self.request[0]
socket = self.request[1]
addr = self.client_address
transfer(data, addr, socket) # 只允许传入的UDP查询
logging.debug('------------------------------------- End transfer')
'''
import daemon as Daemon
class RunDaemon(Daemon):
def run(self):
thread_main(cfg)
def StopDaemon():
RunDaemon(PIDFILE).stop()
'''
def HideCMD():
whnd = ctypes.windll.kernel32.GetConsoleWindow()
if whnd != 0:
ctypes.windll.user32.ShowWindow(whnd, 0)
ctypes.windll.kernel32.CloseHandle(whnd)
def thread_main(cfg):
server = ThreadedUDPServer((cfg["host"], cfg["port"]), ThreadedUDPRequestHandler)
try:
server.serve_forever()
except KeyboardInterrupt:
print("Ctrl+C pressed... Exit(0)")
sys.exit(0)
finally:
server.shutdown()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='A DNS Proxy')
parser.add_argument('-f', dest='config_json', type=argparse.FileType('r'),
required=False, default='tcpdns.json', help='Json config file')
parser.add_argument('-d', dest='dbg_level', action='store_true',
required=False, default=False, help='Print debug message')
parser.add_argument('-s', dest="stop_daemon", action='store_true',
required=False, default=False, help='Stop dns proxy daemon')
args = parser.parse_args()
if args.stop_daemon:
# StopDaemon()
sys.exit(0)
if args.dbg_level:
cfg_logging(logging.DEBUG)
else:
cfg_logging(logging.INFO)
try:
cfg = json.load(args.config_json)
except:
logging.error('Loading json config file error [!!]')
sys.exit(1)
if "host" not in cfg.keys(): # 注意大小写
cfg["host"] = "0.0.0.0"
if "port" not in cfg.keys():
cfg["port"] = 53
if cfg['udp_mode']:
DNS_SERVERS = cfg['udp_dns_server']
else:
DNS_SERVERS = cfg['tcp_dns_server']
if cfg['enable_lru_cache']:
LRUCACHE = lrucache(cfg['lru_cache_size'])
logging.info('A DNS Proxy, Thanks https://github.com/henices/Tcp-DNS-proxy' )
logging.info('DNS Servers: %s' % DNS_SERVERS)
logging.info('Upstream Mode: %s' % ('UDP' if cfg['udp_mode'] else 'TCP'))
logging.info('Enable Cache: %r' % (cfg['enable_lru_cache']))
logging.info('Enable Switch: %r' % (cfg['enable_server_switch']))
logging.info('Query Timeout: %f' % (cfg['socket_timeout']))
if cfg['speed_test']: TestSpeed()
logging.info('Now you can set dns server to %s:%s' % (cfg["host"], cfg["port"]))
if cfg['daemon_process']:
if os.name == 'nt':
HideCMD()
thread_main(cfg)
else:
# d = RunDaemon(PIDFILE)
# d.start()
try:
import daemon
logging.info('Run code in daemon process')
with daemon.DaemonContext(detach_process=True): thread_main(cfg)
except ImportError:
logging.error('Please install python-daemon')
else:
thread_main(cfg)