-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·223 lines (189 loc) · 6.99 KB
/
main.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
#!/usr/bin/env python3
import bisect
import ipaddress
import psycopg
from collections import namedtuple
from prettytable import PrettyTable
views = {
'192.0.2.0/24': 1,
'10.0.0.0/8': 2,
'10.0.4.0/24': 3,
'2001:db8::/32': 4,
'198.51.100.0/29': 10, # A 0-7
'198.51.100.8/29': 11, # B 8-15
'198.51.100.0/27': 12, # C 0-31
'198.51.100.0/26': 13, # D 0-63
'198.51.100.0/28': 14, # E 0-15
'192.168.5.0/24': 101,
'192.168.5.1/32': 102,
'192.168.5.3/32': 103,
}
ips = {
'192.0.2.5': 1,
'10.0.0.1': 2,
'10.0.4.1': 3,
'10.0.4.255': 3,
'10.8.5.2': 2,
'192.168.0.1': None,
'2001:db8::1234': 4,
'198.51.100.0': 10,
'198.51.100.7': 10,
'198.51.100.8': 11,
'198.51.100.15': 11,
'198.51.100.16': 12,
'198.51.100.23': 12,
'198.51.100.30': 12,
'198.51.100.31': 12,
'198.51.100.32': 13,
'198.51.100.70': None,
'192.168.5.2': 101,
}
methods = []
def registerMethod(cls):
methods.append(cls)
ViewLookupResult = namedtuple('ViewLookupResult', ('ip', 'net', 'view'))
class MethodBase:
def __str__(self):
return f"{str(self.__class__).split('.')[-1][:-2]} " \
f"with {len(self.views)} entries"
def methodname(self):
return f"{str(self.__class__).split('.')[-1][:-2]}"
@registerMethod
class MethodScan(MethodBase):
def __init__(self, views):
self.views = dict()
for k, v in views.items():
self.views[ipaddress.ip_network(k)] = v
def lookup(self, ip):
prefix = 0
ip = ipaddress.ip_address(ip)
net = None
view = None
ops = 0
for k, v in self.views.items():
ops += 1
if ip in k and k.prefixlen > prefix:
net = k
view = v
prefix = k.prefixlen
return ViewLookupResult(ip, net, view)
@registerMethod
class MethodBisectSortedNoScan(MethodBase):
def __init__(self, views):
self.views = []
for k, v in views.items():
self.views.append(ipaddress.get_mixed_type_key(ipaddress.ip_network(k).broadcast_address) + (ipaddress.ip_network(k), v))
self.views.sort()
# print(self.views)
def lookup(self, ip):
i = bisect.bisect(self.views, ipaddress.get_mixed_type_key(ipaddress.ip_address(ip)))
res = self.views[i]
print(res)
if ipaddress.ip_address(ip) in res[2]:
return ViewLookupResult(ip, res[1], res[3])
else:
return ViewLookupResult(ip, None, None)
@registerMethod
class MethodBisectSortedScan(MethodBase):
def __init__(self, views):
self.views = []
for k, v in views.items():
self.views.append((ipaddress.get_mixed_type_key(ipaddress.ip_network(k).broadcast_address), (ipaddress.ip_network(k), v)))
self.views.sort()
print(self.views)
def lookup(self, ip):
ops = 0
i = bisect.bisect(self.views, (ipaddress.get_mixed_type_key(ipaddress.ip_address(ip)),))
print(i)
res = None
prefixlen = -1
for idx in range(i, len(views)):
tmp = self.views[idx]
print(tmp)
print(ipaddress.get_mixed_type_key(ipaddress.ip_address(ip)))
print(ipaddress.ip_address(ip), "in", tmp[1][0], ipaddress.ip_address(ip) in tmp[1][0])
if ipaddress.ip_address(ip) in tmp[1][0] and tmp[1][0].prefixlen > prefixlen:
print("got prefixlen", tmp[1][0].prefixlen)
res = tmp
prefixlen = tmp[1][0].prefixlen
if tmp[0] < ipaddress.get_mixed_type_key(ipaddress.ip_address(ip)):
print("breaking")
print(tmp[0], ">", ipaddress.get_mixed_type_key(ipaddress.ip_address(ip)))
break
ops += 1
if res:
print(res)
return ViewLookupResult(ip, res[1][0], res[1][1])
else:
return ViewLookupResult(ip, None, None)
@registerMethod
class MethodPostgresSimple(MethodBase):
def __init__(self, views):
self.views = views
with psycopg.connect() as conn:
with conn.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS views;")
cur.execute("CREATE TABLE views (net cidr, tag int);")
for k,v in views.items():
cur.execute(f"insert into views values('{k}', {v});")
def lookup(self, ip):
with psycopg.connect() as conn:
with conn.cursor() as cur:
cur.execute(f"select net, tag from views where inet('{ip}') <<= net order by masklen(net) desc limit 1;")
res = cur.fetchone()
if res:
return ViewLookupResult(ip, res[0], res[1])
else:
return ViewLookupResult(ip, None, None)
# this *has* to run after PostgresSimple
@registerMethod
class MethodPostgresDouble(MethodBase):
def __init__(self, views):
self.views = views
with psycopg.connect() as conn:
with conn.cursor() as cur:
cur.execute("DROP TABLE IF EXISTS viewmap;")
cur.execute("CREATE TABLE viewmap (net cidr, netmin inet, netmax inet, tag int);")
cur.execute("insert into viewmap select net, host(net)::inet, host(broadcast(net))::inet, tag from views;")
def lookup(self, ip):
with psycopg.connect() as conn:
with conn.cursor() as cur:
cur.execute(f"select net, tag from viewmap where inet('{ip}') >= netmin order by netmin desc limit 1;")
res1 = cur.fetchone()
cur.execute(f"select net, tag from viewmap where inet('{ip}') <= netmax order by netmax asc limit 1;")
res2 = cur.fetchone()
res = None
print(ip, end=" ")
for res_ in (res1, res2):
net, tag = res_
b = ipaddress.ip_address(ip) in ipaddress.ip_network(net)
if b:
print("in", net, end="; ")
res = res_
else:
print("NOT in", net, end="; ")
if res:
return ViewLookupResult(ip, res[0], res[1])
else:
return ViewLookupResult(ip, None, None)
if __name__ == '__main__':
table = PrettyTable()
table.add_column("IP", list(ips.keys()))
for method in methods:
methodresults = []
db = method(views)
# table.field_names.append(db.methodname()[6:])
print(f"testing {db}")
ops = 0
for ip, view in ips.items():
res = db.lookup(ip)
print(f"{res.ip} in {res.net} with view {res.view}")
# assert res.view == view
if res.view == view:
methodresults.append(res.view)
else:
methodresults.append('XXX')
# ipresults[ip] =
table.add_column(db.methodname()[6:], methodresults)
print(table.field_names)
print(table)