-
Notifications
You must be signed in to change notification settings - Fork 2
/
adns.py
68 lines (50 loc) · 1.3 KB
/
adns.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
import threading
from queue import Queue
import dns
_num_workers = 10
_queue = Queue(maxsize=0)
_workers = []
def _async_query(*, callback=None, **kwargs):
_queue.put((callback, kwargs))
def _worker():
while True:
q = _queue.get()
if q is None:
break
_do_work(*q)
_queue.task_done()
def _do_work(callback, kwargs):
kwargs.setdefault('timeout', 2)
try:
response = dns.query.udp(**kwargs)
except dns.exception.Timeout:
response = '(No response before timeout)'
if callback:
callback(response, **kwargs)
def join():
for _ in range(_num_workers):
_queue.put(None)
for w in _workers:
w.join()
def query_all(where_list, q, **kwargs):
_init()
result = {}
def rec(response, where, **kwargs):
result[where_list[where]] = response
for where in where_list:
_async_query(
q=q, # TODO all queries use the same id .. but whatever for now
where=where,
callback=rec,
**kwargs,
)
join()
return result
def _init():
_queue.queue.clear() # TODO evil?
while _workers:
_workers.pop()
for i in range(_num_workers):
t = threading.Thread(target=_worker)
t.start()
_workers.append(t)