]>
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 ###############################################################################
32 from . import downloader
35 FILENAME_ASNUMS
= "asnums.txt"
36 FILENMAE_NETWORKS
= "networks.txt"
40 RE_AS
= re
.compile(r
"^(AS|as)(\d+)")
57 return "%s - %s" % (self
.__class
__.__name
__, self
.name
)
59 return self
.__class
__.__name
__
65 def make_path(self
, path
):
66 return os
.path
.join(self
.__class
__.__name
__, path
)
69 def filename_asnums(self
):
70 return self
.make_path(FILENAME_ASNUMS
)
73 def filename_networks(self
):
74 return self
.make_path(FILENMAE_NETWORKS
)
76 def update(self
, directory
):
79 # Download all data and store it in memory
82 # Write the database to disk
83 p
.export_database(directory
)
86 class RIRParser(object):
87 def __init__(self
, rir
):
90 # Create a downloader to fetch data
91 self
.downloader
= downloader
.Downloader()
93 # Create a database to hold temporary data
94 self
.db
= self
._make
_database
(":memory:")
97 self
.start_time
= datetime
.datetime
.utcnow()
99 def _make_database(self
, filename
):
100 db
= sqlite3
.connect(filename
)
101 db
.set_trace_callback(logging
.debug
)
103 # Create database layout
105 cursor
.executescript("""
106 CREATE TABLE IF NOT EXISTS autnums(asn INTEGER, country TEXT, org_id INTEGER, date DATE);
107 CREATE INDEX autnums_org_id ON autnums(org_id);
109 CREATE TABLE IF NOT EXISTS inetnums(network TEXT, country TEXT, org_id INTEGER,
110 family INTEGER, address_start BLOB, address_end BLOB, prefix INTEGER, date DATE);
111 CREATE INDEX inetnums_sort ON inetnums(address_start);
116 def export_database(self
, directory
):
118 with
open(self
.rir
.filename_asnums
, "w") as f
:
119 self
._export
_asnums
(f
)
122 with
open(self
.rir
.filename_networks
, "w") as f
:
123 self
._export
_networks
(f
)
125 def _write_header(self
, f
):
127 f
.write("# %s\n" % self
.rir
)
128 f
.write("# Generated at %s\n" % self
.start_time
)
131 def fetch_data(self
):
132 if not self
.rir
.database_urls
:
133 raise NotImplementedError("Database URLs not set")
135 # Parse entire database in one go
136 for url
in self
.rir
.database_urls
:
141 def parse_url(self
, url
):
142 with self
.downloader
.request(url
) as r
:
143 for i
, line
in enumerate(r
):
144 # Skip the first line
148 self
.parse_line(line
)
150 def parse_line(self
, line
):
152 if line
.startswith("#"):
156 registry
, country_code
, type, line
= line
.split("|", 3)
158 logging
.warning("Could not parse line: %s" % line
)
161 # Skip any lines that are for stats only
162 if country_code
== "*":
165 if type in ("ipv6", "ipv4"):
166 return self
._parse
_ip
_line
(country_code
, type, line
)
169 return self
._parse
_asn
_line
(country_code
, line
)
172 logging
.warning("Unknown line type: %s" % type)
175 def _parse_ip_line(self
, country_code
, type, line
):
177 address
, prefix
, date
, status
, org_id
= line
.split("|")
181 # Try parsing the line without org_id
183 address
, prefix
, date
, status
= line
.split("|")
185 logging
.warning("Unhandled line format: %s" % line
)
188 # Skip anything that isn't properly assigned
189 if not status
in ("assigned", "allocated"):
192 # Cast prefix into an integer
196 logging
.warning("Invalid prefix: %s" % prefix
)
198 # Fix prefix length for IPv4
200 prefix
= 32 - int(math
.log(prefix
, 2))
204 date
= datetime
.datetime
.strptime(date
, "%Y%m%d")
206 logging
.warning("Could not parse date: %s" % date
)
209 # Try to parse the address
211 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
213 logging
.warning("Invalid IP address: %s" % address
)
217 # Get the first and last address of this network
218 address_start
, address_end
= int(network
.network_address
), int(network
.broadcast_address
)
225 struct
.pack(">QQ", address_start
>> 64, address_start
% (2 ** 64)),
226 struct
.pack(">QQ", address_end
>> 64, address_end
% (2 ** 64)),
231 c
.execute("INSERT INTO inetnums(network, country, org_id, \
232 family, address_start, address_end, prefix, date) \
233 VALUES(?, ?, ?, ?, ?, ?, ?, ?)", args
)
235 def _parse_asn_line(self
, country_code
, line
):
237 asn
, dunno
, date
, status
, org_id
= line
.split("|")
241 # Try parsing the line without org_id
243 asn
, dunno
, date
, status
= line
.split("|")
245 logging
.warning("Could not parse line: %s" % line
)
248 # Skip anything that isn't properly assigned
249 if not status
in ("assigned", "allocated"):
254 date
= datetime
.datetime
.strptime(date
, "%Y%m%d")
256 logging
.warning("Could not parse date: %s" % date
)
267 c
.execute("INSERT INTO autnums(asn, country, org_id, date) \
268 VALUES(?, ?, ?, ?)", args
)
270 def _export_networks(self
, f
):
272 self
._write
_header
(f
)
277 SELECT inetnums.network,
279 inetnums.address_start,
281 STRFTIME('%Y-%m-%d', inetnums.date)
284 WHERE inetnums.org_id = autnums.org_id
285 ORDER BY inetnums.address_start
289 net
, asn
, address_start
, country
, date
= row
291 f
.write(FMT
% ("net:", net
))
294 f
.write(FMT
% ("asnum:", "AS%s" % asn
))
297 f
.write(FMT
% ("country:", country
))
300 f
.write(FMT
% ("assigned:", date
))
305 def _export_asnums(self
, f
):
307 self
._write
_header
(f
)
310 res
= c
.execute("SELECT DISTINCT autnums.asn, autnums.country, \
311 STRFTIME('%Y-%m-%d', autnums.date) FROM autnums ORDER BY autnums.asn")
314 asn
, country
, date
= row
316 f
.write(FMT
% ("asnum:", "AS%s" % asn
))
319 f
.write(FMT
% ("country:", country
))
322 f
.write(FMT
% ("assigned:", date
))