]>
git.ipfire.org Git - location/location-database.git/blob - tools/base.py
2 ###############################################################################
4 # location-database - A database to determine someone's #
5 # location on the Internet #
6 # Copyright (C) 2018 Michael Tremer #
8 # This program is free software: you can redistribute it and/or modify #
9 # it under the terms of the GNU General Public License as published by #
10 # the Free Software Foundation, either version 3 of the License, or #
11 # (at your option) any later version. #
13 # This program is distributed in the hope that it will be useful, #
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
16 # GNU General Public License for more details. #
18 # You should have received a copy of the GNU General Public License #
19 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
21 ###############################################################################
33 from . import downloader
36 FILENAME_ASNUMS
= "asnums.txt"
37 FILENMAE_NETWORKS
= "networks.txt"
41 RE_AS
= re
.compile(r
"^(AS|as)(\d+)")
60 return "%s - %s" % (self
.__class
__.__name
__, self
.name
)
62 return self
.__class
__.__name
__
68 def make_path(self
, path
):
69 return os
.path
.join(self
.__class
__.__name
__, path
)
72 def filename_asnums(self
):
73 return self
.make_path(FILENAME_ASNUMS
)
76 def filename_networks(self
):
77 return self
.make_path(FILENMAE_NETWORKS
)
79 def update(self
, directory
):
82 # Download all data and store it in memory
85 # Write the database to disk
86 p
.export_database(directory
)
88 def whois(self
, query
):
93 # Query a specific WHOIS server
95 command
+= ["-h", self
.whois_server
]
97 logging
.info("Running command: %s" % " ".join(command
))
100 output
= subprocess
.check_output(command
, stderr
=subprocess
.STDOUT
)
101 except subprocess
.CalledProcessError
as e
:
102 logging
.error("Could not run WHOIS query %s: %s" % (query
, e
.output
))
105 return output
.decode(errors
="ignore")
107 def get_name_for_asn(self
, asn
):
108 result
= self
.whois("AS%s" % asn
)
110 for line
in result
.splitlines():
111 key
, delim
, value
= line
.partition(":")
115 if key
in ("org-name", "OrgName"):
119 class RIRParser(object):
120 def __init__(self
, rir
):
123 # Create a downloader to fetch data
124 self
.downloader
= downloader
.Downloader()
126 # Create a database to hold temporary data
127 self
.db
= self
._make
_database
(":memory:")
130 self
.start_time
= datetime
.datetime
.utcnow()
132 def _make_database(self
, filename
):
133 db
= sqlite3
.connect(filename
)
134 db
.set_trace_callback(logging
.debug
)
136 # Create database layout
138 cursor
.executescript("""
139 CREATE TABLE IF NOT EXISTS autnums(asn INTEGER, country TEXT, org_id INTEGER, date DATE);
140 CREATE INDEX autnums_org_id ON autnums(org_id);
142 CREATE TABLE IF NOT EXISTS inetnums(network TEXT, country TEXT, org_id INTEGER,
143 family INTEGER, address_start BLOB, address_end BLOB, prefix INTEGER, date DATE);
144 CREATE INDEX inetnums_sort ON inetnums(address_start);
149 def export_database(self
, directory
):
151 with
open(self
.rir
.filename_asnums
, "w") as f
:
152 self
._export
_asnums
(f
)
155 with
open(self
.rir
.filename_networks
, "w") as f
:
156 self
._export
_networks
(f
)
158 def _write_header(self
, f
):
160 f
.write("# %s\n" % self
.rir
)
161 f
.write("# Generated at %s\n" % self
.start_time
)
164 def fetch_data(self
):
165 if not self
.rir
.database_urls
:
166 raise NotImplementedError("Database URLs not set")
168 # Parse entire database in one go
169 for url
in self
.rir
.database_urls
:
174 def parse_url(self
, url
):
175 with self
.downloader
.request(url
) as r
:
177 self
.parse_line(line
)
179 def parse_line(self
, line
):
181 if line
.startswith("2"):
185 if line
.startswith("#"):
189 registry
, country_code
, type, line
= line
.split("|", 3)
191 logging
.warning("Could not parse line: %s" % line
)
194 # Skip any lines that are for stats only
195 if country_code
== "*":
198 if type in ("ipv6", "ipv4"):
199 return self
._parse
_ip
_line
(country_code
, type, line
)
202 return self
._parse
_asn
_line
(country_code
, line
)
205 logging
.warning("Unknown line type: %s" % type)
208 def _parse_ip_line(self
, country_code
, type, line
):
210 address
, prefix
, date
, status
, org_id
= line
.split("|")
214 # Try parsing the line without org_id
216 address
, prefix
, date
, status
= line
.split("|")
218 logging
.warning("Unhandled line format: %s" % line
)
221 # Skip anything that isn't properly assigned
222 if not status
in ("assigned", "allocated"):
225 # Cast prefix into an integer
229 logging
.warning("Invalid prefix: %s" % prefix
)
231 # Fix prefix length for IPv4
233 prefix
= 32 - int(math
.log(prefix
, 2))
237 date
= datetime
.datetime
.strptime(date
, "%Y%m%d")
239 logging
.warning("Could not parse date: %s" % date
)
242 # Try to parse the address
244 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
246 logging
.warning("Invalid IP address: %s" % address
)
250 # Get the first and last address of this network
251 address_start
, address_end
= int(network
.network_address
), int(network
.broadcast_address
)
258 struct
.pack(">QQ", address_start
>> 64, address_start
% (2 ** 64)),
259 struct
.pack(">QQ", address_end
>> 64, address_end
% (2 ** 64)),
264 c
.execute("INSERT INTO inetnums(network, country, org_id, \
265 family, address_start, address_end, prefix, date) \
266 VALUES(?, ?, ?, ?, ?, ?, ?, ?)", args
)
268 def _parse_asn_line(self
, country_code
, line
):
270 asn
, dunno
, date
, status
, org_id
= line
.split("|")
274 # Try parsing the line without org_id
276 asn
, dunno
, date
, status
= line
.split("|")
278 logging
.warning("Could not parse line: %s" % line
)
281 # Skip anything that isn't properly assigned
282 if not status
in ("assigned", "allocated"):
287 date
= datetime
.datetime
.strptime(date
, "%Y%m%d")
289 logging
.warning("Could not parse date: %s" % date
)
300 c
.execute("INSERT INTO autnums(asn, country, org_id, date) \
301 VALUES(?, ?, ?, ?)", args
)
303 def _export_networks(self
, f
):
305 self
._write
_header
(f
)
310 SELECT inetnums.network,
312 inetnums.address_start,
314 STRFTIME('%Y-%m-%d', inetnums.date)
317 WHERE inetnums.org_id = autnums.org_id
318 ORDER BY inetnums.address_start
322 net
, asn
, address_start
, country
, date
= row
324 f
.write(FMT
% ("net:", net
))
327 f
.write(FMT
% ("asnum:", "AS%s" % asn
))
330 f
.write(FMT
% ("country:", country
))
333 f
.write(FMT
% ("assigned:", date
))
338 def _export_asnums(self
, f
):
340 self
._write
_header
(f
)
343 res
= c
.execute("SELECT DISTINCT autnums.asn, autnums.country, \
344 STRFTIME('%Y-%m-%d', autnums.date) FROM autnums ORDER BY autnums.asn")
347 asn
, country
, date
= row
349 f
.write(FMT
% ("asnum:", "AS%s" % asn
))
351 name
= self
.rir
.get_name_for_asn(asn
)
353 f
.write(FMT
% ("name:", name
))
356 f
.write(FMT
% ("country:", country
))
359 f
.write(FMT
% ("assigned:", date
))