write results to the database
[0tDNS.git] / src / perform_queries.py
blob8262ef0bb2d1ec36768ebd1ba3c665bdf2056ad8
1 #!/bin/python3
3 from sys import argv
4 import unbound
6 # our own module used by several scripts in the project
7 from ztdns_db_connectivity import start_db_connection
9 class dns_queries:
10 def __init__(self, dns_IP, dns_id, services):
11 self.dns_IP = dns_IP
12 self.dns_id = dns_id
13 self.services = services
15 class single_query:
16 def __init__(self, cursor, vpn_id, dns_id, service_id):
17 self.cursor = cursor
18 self.vpn_id = vpn_id
19 self.dns_id = dns_id
20 self.service_id = service_id
22 def query_planned_queries(cursor, hour, vpn_id):
23 # return [
24 # # dns server IP | dns server id | service_id | service_name
25 # dns_queries("195.98.79.117", 23, [[89, "devuan.org"],
26 # [44, "gry.pl"],
27 # [112, "invidio.us"]]),
28 # dns_queries("192.71.245.208", 33, [[77, "debian.org"],
29 # [22, "nie.ma.takiej.domeny"],
30 # [100, "onet.pl"]])
31 # ]
32 cursor.execute('''
33 SELECT DISTINCT d.IP, d.dns_id
34 FROM user_side_queries AS q JOIN user_side_dns AS d
35 ON dns.id = q.dns_id
36 WHERE q.vpn_id = %s
37 ''', (vpn_id,))
38 dnss = cursor.fetchall()
40 dnss_to_query = []
42 for dns_IP, dns_id in dnss:
43 cursor.execute('''
44 SELECT s.id, s.name
45 FROM user_side_services AS s JOIN user_side_queries AS q
46 ON s.id = q.service_id
47 WHERE q.vpn_id = %s AND q.dns_id = %s
48 ''', (vpn_id, dns_id))
50 queries = dns_queries(dns_IP, dns_id, cursor.fetchall())
52 dnss_to_query.append(queries)
54 return dnss_to_query
56 def resolve_call_back(mydata, status, result):
57 query = mydata
58 # debugging
59 print("callback called for {}".format(result.qname))
60 if status==0 and result.havedata:
61 print("Result:",result.data.address_list)
62 # write to database
63 query.cursor.execute('''
64 INSERT INTO user_side_responses (date, result, dns_id, service_id, vpn_id)
65 VALUES (current_timestamp, '', %s, %s, %s)
66 RETURNING id
67 ''', (query.dns_id, query.service_id, query.vpn_id))
69 responses_id = query.cursor.fetchone()[0]
71 if status==0 and result.havedata:
72 for address in data.address_list:
73 query.cursor.execute('''
74 INSERT INTO user_side_response (returned_ip, responses_id)
75 VALUES(%s, %s)
76 ''', (address, responses_id))
77 # no committing, since auto-commit mode is set on the connection
79 hour = argv[1]
80 vpn_id = argv[2]
81 connection = start_db_connection()
82 cursor = connection.cursor()
84 contexts = []
85 for dns_query in query_planned_queries(cursor, hour, vpn_id):
86 ctx = unbound.ub_ctx()
87 ctx.set_fwd(dns_IP)
88 for service_id, service_name in dns_query.services:
89 print("starting resolution of {} through {}".format(service_name, dns_IP))
90 query = single_query(cursor, vpn_id, dns_query.dns_id, service_id)
92 ctx.resolve_async(service_name, query, resolve_call_back,
93 unbound.RR_TYPE_A, unbound.RR_CLASS_IN)
94 contexts.append(ctx)
96 for ctx in contexts:
97 ctx.wait()
99 cursor.close()
100 connection.close()