]> git.ipfire.org Git - people/ms/libloc.git/blame - src/python/location-importer.in
Revert "Revert "Revert "importer: Import raw sources for inetnum's again"""
[people/ms/libloc.git] / src / python / location-importer.in
CommitLineData
78ff0cf2
MT
1#!/usr/bin/python3
2###############################################################################
3# #
4# libloc - A library to determine the location of someone on the Internet #
5# #
6# Copyright (C) 2020 IPFire Development Team <info@ipfire.org> #
7# #
8# This library is free software; you can redistribute it and/or #
9# modify it under the terms of the GNU Lesser General Public #
10# License as published by the Free Software Foundation; either #
11# version 2.1 of the License, or (at your option) any later version. #
12# #
13# This library 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 GNU #
16# Lesser General Public License for more details. #
17# #
18###############################################################################
19
20import argparse
6ffd06b5 21import ipaddress
78ff0cf2 22import logging
6ffd06b5
MT
23import math
24import re
22d8d199 25import socket
78ff0cf2 26import sys
83d61c46 27import telnetlib
78ff0cf2
MT
28
29# Load our location module
30import location
29c6fa22 31import location.database
3192b66c 32import location.importer
78ff0cf2
MT
33from location.i18n import _
34
35# Initialise logging
36log = logging.getLogger("location.importer")
37log.propagate = 1
38
39class CLI(object):
40 def parse_cli(self):
41 parser = argparse.ArgumentParser(
42 description=_("Location Importer Command Line Interface"),
43 )
6ffd06b5 44 subparsers = parser.add_subparsers()
78ff0cf2
MT
45
46 # Global configuration flags
47 parser.add_argument("--debug", action="store_true",
48 help=_("Enable debug output"))
bc1f5f53
MT
49 parser.add_argument("--quiet", action="store_true",
50 help=_("Enable quiet mode"))
78ff0cf2
MT
51
52 # version
53 parser.add_argument("--version", action="version",
54 version="%(prog)s @VERSION@")
55
29c6fa22
MT
56 # Database
57 parser.add_argument("--database-host", required=True,
58 help=_("Database Hostname"), metavar=_("HOST"))
59 parser.add_argument("--database-name", required=True,
60 help=_("Database Name"), metavar=_("NAME"))
61 parser.add_argument("--database-username", required=True,
62 help=_("Database Username"), metavar=_("USERNAME"))
63 parser.add_argument("--database-password", required=True,
64 help=_("Database Password"), metavar=_("PASSWORD"))
65
0983f3dd
MT
66 # Write Database
67 write = subparsers.add_parser("write", help=_("Write database to file"))
68 write.set_defaults(func=self.handle_write)
69 write.add_argument("file", nargs=1, help=_("Database File"))
70 write.add_argument("--signing-key", nargs="?", type=open, help=_("Signing Key"))
1164d876 71 write.add_argument("--backup-signing-key", nargs="?", type=open, help=_("Backup Signing Key"))
0983f3dd
MT
72 write.add_argument("--vendor", nargs="?", help=_("Sets the vendor"))
73 write.add_argument("--description", nargs="?", help=_("Sets a description"))
74 write.add_argument("--license", nargs="?", help=_("Sets the license"))
b904896a 75 write.add_argument("--version", type=int, help=_("Database Format Version"))
0983f3dd 76
6ffd06b5
MT
77 # Update WHOIS
78 update_whois = subparsers.add_parser("update-whois", help=_("Update WHOIS Information"))
79 update_whois.set_defaults(func=self.handle_update_whois)
80
83d61c46
MT
81 # Update announcements
82 update_announcements = subparsers.add_parser("update-announcements",
83 help=_("Update BGP Annoucements"))
84 update_announcements.set_defaults(func=self.handle_update_announcements)
85 update_announcements.add_argument("server", nargs=1,
86 help=_("Route Server to connect to"), metavar=_("SERVER"))
87
d7fc3057
MT
88 # Update overrides
89 update_overrides = subparsers.add_parser("update-overrides",
90 help=_("Update overrides"),
91 )
92 update_overrides.add_argument(
93 "files", nargs="+", help=_("Files to import"),
94 )
95 update_overrides.set_defaults(func=self.handle_update_overrides)
96
8084b33a
MT
97 # Import countries
98 import_countries = subparsers.add_parser("import-countries",
99 help=_("Import countries"),
100 )
101 import_countries.add_argument("file", nargs=1, type=argparse.FileType("r"),
102 help=_("File to import"))
103 import_countries.set_defaults(func=self.handle_import_countries)
104
78ff0cf2
MT
105 args = parser.parse_args()
106
bc1f5f53 107 # Configure logging
78ff0cf2 108 if args.debug:
f9de5e61 109 location.logger.set_level(logging.DEBUG)
bc1f5f53
MT
110 elif args.quiet:
111 location.logger.set_level(logging.WARNING)
78ff0cf2 112
6ffd06b5
MT
113 # Print usage if no action was given
114 if not "func" in args:
115 parser.print_usage()
116 sys.exit(2)
117
78ff0cf2
MT
118 return args
119
120 def run(self):
121 # Parse command line arguments
122 args = self.parse_cli()
123
29c6fa22 124 # Initialise database
6ffd06b5 125 self.db = self._setup_database(args)
29c6fa22 126
78ff0cf2 127 # Call function
6ffd06b5 128 ret = args.func(args)
78ff0cf2
MT
129
130 # Return with exit code
131 if ret:
132 sys.exit(ret)
133
134 # Otherwise just exit
135 sys.exit(0)
136
29c6fa22
MT
137 def _setup_database(self, ns):
138 """
139 Initialise the database
140 """
141 # Connect to database
142 db = location.database.Connection(
143 host=ns.database_host, database=ns.database_name,
144 user=ns.database_username, password=ns.database_password,
145 )
146
147 with db.transaction():
148 db.execute("""
83d61c46
MT
149 -- announcements
150 CREATE TABLE IF NOT EXISTS announcements(network inet, autnum bigint,
151 first_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
152 last_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP);
153 CREATE UNIQUE INDEX IF NOT EXISTS announcements_networks ON announcements(network);
154 CREATE INDEX IF NOT EXISTS announcements_family ON announcements(family(network));
155
6ffd06b5 156 -- autnums
0983f3dd 157 CREATE TABLE IF NOT EXISTS autnums(number bigint, name text NOT NULL);
6ffd06b5
MT
158 CREATE UNIQUE INDEX IF NOT EXISTS autnums_number ON autnums(number);
159
8084b33a
MT
160 -- countries
161 CREATE TABLE IF NOT EXISTS countries(
162 country_code text NOT NULL, name text NOT NULL, continent_code text NOT NULL);
163 CREATE UNIQUE INDEX IF NOT EXISTS countries_country_code ON countries(country_code);
164
429a43d1 165 -- networks
83d61c46 166 CREATE TABLE IF NOT EXISTS networks(network inet, country text);
429a43d1 167 CREATE UNIQUE INDEX IF NOT EXISTS networks_network ON networks(network);
83d61c46 168 CREATE INDEX IF NOT EXISTS networks_search ON networks USING GIST(network inet_ops);
d7fc3057
MT
169
170 -- overrides
171 CREATE TABLE IF NOT EXISTS autnum_overrides(
172 number bigint NOT NULL,
173 name text,
bd1aa6a1 174 country text,
b8e25b71
MT
175 is_anonymous_proxy boolean,
176 is_satellite_provider boolean,
177 is_anycast boolean
d7fc3057
MT
178 );
179 CREATE UNIQUE INDEX IF NOT EXISTS autnum_overrides_number
180 ON autnum_overrides(number);
181
182 CREATE TABLE IF NOT EXISTS network_overrides(
183 network inet NOT NULL,
184 country text,
b8e25b71
MT
185 is_anonymous_proxy boolean,
186 is_satellite_provider boolean,
187 is_anycast boolean
d7fc3057
MT
188 );
189 CREATE UNIQUE INDEX IF NOT EXISTS network_overrides_network
190 ON network_overrides(network);
29c6fa22
MT
191 """)
192
193 return db
194
0983f3dd
MT
195 def handle_write(self, ns):
196 """
197 Compiles a database in libloc format out of what is in the database
198 """
0983f3dd 199 # Allocate a writer
1164d876 200 writer = location.Writer(ns.signing_key, ns.backup_signing_key)
0983f3dd
MT
201
202 # Set all metadata
203 if ns.vendor:
204 writer.vendor = ns.vendor
205
206 if ns.description:
207 writer.description = ns.description
208
209 if ns.license:
210 writer.license = ns.license
211
212 # Add all Autonomous Systems
213 log.info("Writing Autonomous Systems...")
214
215 # Select all ASes with a name
6e97c44b
MT
216 rows = self.db.query("""
217 SELECT
218 autnums.number AS number,
219 COALESCE(
220 (SELECT overrides.name FROM autnum_overrides overrides
221 WHERE overrides.number = autnums.number),
222 autnums.name
223 ) AS name
224 FROM autnums
225 WHERE name <> %s ORDER BY number
226 """, "")
0983f3dd
MT
227
228 for row in rows:
229 a = writer.add_as(row.number)
230 a.name = row.name
231
232 # Add all networks
233 log.info("Writing networks...")
234
235 # Select all known networks
236 rows = self.db.query("""
5372d9c7
MT
237 -- Get a (sorted) list of all known networks
238 WITH known_networks AS (
239 SELECT network FROM announcements
240 UNION
241 SELECT network FROM networks
2373de38
MT
242 UNION
243 SELECT network FROM network_overrides
5372d9c7
MT
244 ORDER BY network
245 )
246
247 -- Return a list of those networks enriched with all
248 -- other information that we store in the database
0983f3dd 249 SELECT
5372d9c7
MT
250 DISTINCT ON (known_networks.network)
251 known_networks.network AS network,
0983f3dd 252 announcements.autnum AS autnum,
bd1aa6a1
MT
253
254 -- Country
255 COALESCE(
256 (
257 SELECT country FROM network_overrides overrides
258 WHERE announcements.network <<= overrides.network
259 ORDER BY masklen(overrides.network) DESC
260 LIMIT 1
261 ),
262 (
263 SELECT country FROM autnum_overrides overrides
264 WHERE announcements.autnum = overrides.number
265 ),
266 networks.country
267 ) AS country,
8e8555bb 268
0983f3dd 269 -- Flags
1422b5d4
MT
270 COALESCE(
271 (
272 SELECT is_anonymous_proxy FROM network_overrides overrides
273 WHERE announcements.network <<= overrides.network
274 ORDER BY masklen(overrides.network) DESC
275 LIMIT 1
276 ),
277 (
278 SELECT is_anonymous_proxy FROM autnum_overrides overrides
279 WHERE announcements.autnum = overrides.number
b8e25b71
MT
280 ),
281 FALSE
1422b5d4
MT
282 ) AS is_anonymous_proxy,
283 COALESCE(
284 (
285 SELECT is_satellite_provider FROM network_overrides overrides
286 WHERE announcements.network <<= overrides.network
287 ORDER BY masklen(overrides.network) DESC
288 LIMIT 1
289 ),
290 (
291 SELECT is_satellite_provider FROM autnum_overrides overrides
292 WHERE announcements.autnum = overrides.number
b8e25b71
MT
293 ),
294 FALSE
1422b5d4
MT
295 ) AS is_satellite_provider,
296 COALESCE(
297 (
298 SELECT is_anycast FROM network_overrides overrides
299 WHERE announcements.network <<= overrides.network
300 ORDER BY masklen(overrides.network) DESC
301 LIMIT 1
302 ),
303 (
304 SELECT is_anycast FROM autnum_overrides overrides
305 WHERE announcements.autnum = overrides.number
b8e25b71
MT
306 ),
307 FALSE
5372d9c7
MT
308 ) AS is_anycast,
309
310 -- Must be part of returned values for ORDER BY clause
17d49c4f
MT
311 masklen(announcements.network) AS sort_a,
312 masklen(networks.network) AS sort_b
5372d9c7
MT
313 FROM known_networks
314 LEFT JOIN announcements ON known_networks.network <<= announcements.network
315 LEFT JOIN networks ON known_networks.network <<= networks.network
17d49c4f 316 ORDER BY known_networks.network, sort_a DESC, sort_b DESC
0983f3dd
MT
317 """)
318
319 for row in rows:
320 network = writer.add_network(row.network)
321
5372d9c7
MT
322 # Save country
323 if row.country:
324 network.country_code = row.country
325
326 # Save ASN
327 if row.autnum:
328 network.asn = row.autnum
0983f3dd
MT
329
330 # Set flags
331 if row.is_anonymous_proxy:
332 network.set_flag(location.NETWORK_FLAG_ANONYMOUS_PROXY)
333
334 if row.is_satellite_provider:
335 network.set_flag(location.NETWORK_FLAG_SATELLITE_PROVIDER)
336
337 if row.is_anycast:
338 network.set_flag(location.NETWORK_FLAG_ANYCAST)
339
8084b33a
MT
340 # Add all countries
341 log.info("Writing countries...")
342 rows = self.db.query("SELECT * FROM countries ORDER BY country_code")
343
344 for row in rows:
345 c = writer.add_country(row.country_code)
346 c.continent_code = row.continent_code
347 c.name = row.name
348
0983f3dd
MT
349 # Write everything to file
350 log.info("Writing database to file...")
351 for file in ns.file:
352 writer.write(file)
353
6ffd06b5
MT
354 def handle_update_whois(self, ns):
355 downloader = location.importer.Downloader()
356
357 # Download all sources
0365119d
MT
358 with self.db.transaction():
359 # Create some temporary tables to store parsed data
360 self.db.execute("""
361 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
362 ON COMMIT DROP;
363 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
364
2cd2e342 365 CREATE TEMPORARY TABLE _organizations(handle text, name text NOT NULL)
0365119d
MT
366 ON COMMIT DROP;
367 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
368 """)
369
370 for source in location.importer.WHOIS_SOURCES:
6ffd06b5
MT
371 with downloader.request(source, return_blocks=True) as f:
372 for block in f:
373 self._parse_block(block)
374
0365119d
MT
375 self.db.execute("""
376 INSERT INTO autnums(number, name)
377 SELECT _autnums.number, _organizations.name FROM _autnums
2cd2e342 378 JOIN _organizations ON _autnums.organization = _organizations.handle
ee6ea398 379 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
0365119d
MT
380 """)
381
429a43d1
MT
382 # Download all extended sources
383 for source in location.importer.EXTENDED_SOURCES:
384 with self.db.transaction():
429a43d1
MT
385 # Download data
386 with downloader.request(source) as f:
387 for line in f:
388 self._parse_line(line)
389
6ffd06b5
MT
390 def _parse_block(self, block):
391 # Get first line to find out what type of block this is
392 line = block[0]
393
6ffd06b5 394 # aut-num
429a43d1 395 if line.startswith("aut-num:"):
6ffd06b5
MT
396 return self._parse_autnum_block(block)
397
398 # organisation
399 elif line.startswith("organisation:"):
400 return self._parse_org_block(block)
401
6ffd06b5 402 def _parse_autnum_block(self, block):
6ffd06b5
MT
403 autnum = {}
404 for line in block:
405 # Split line
406 key, val = split_line(line)
407
408 if key == "aut-num":
409 m = re.match(r"^(AS|as)(\d+)", val)
410 if m:
411 autnum["asn"] = m.group(2)
412
0365119d 413 elif key == "org":
6ffd06b5
MT
414 autnum[key] = val
415
416 # Skip empty objects
417 if not autnum:
418 return
419
420 # Insert into database
0365119d
MT
421 self.db.execute("INSERT INTO _autnums(number, organization) \
422 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
423 organization = excluded.organization",
424 autnum.get("asn"), autnum.get("org"),
6ffd06b5
MT
425 )
426
6ffd06b5
MT
427 def _parse_org_block(self, block):
428 org = {}
429 for line in block:
430 # Split line
431 key, val = split_line(line)
432
0365119d 433 if key in ("organisation", "org-name"):
6ffd06b5
MT
434 org[key] = val
435
436 # Skip empty objects
437 if not org:
438 return
439
0365119d
MT
440 self.db.execute("INSERT INTO _organizations(handle, name) \
441 VALUES(%s, %s) ON CONFLICT (handle) DO \
442 UPDATE SET name = excluded.name",
443 org.get("organisation"), org.get("org-name"),
6ffd06b5
MT
444 )
445
429a43d1
MT
446 def _parse_line(self, line):
447 # Skip version line
448 if line.startswith("2"):
449 return
6ffd06b5 450
429a43d1
MT
451 # Skip comments
452 if line.startswith("#"):
453 return
6ffd06b5 454
429a43d1
MT
455 try:
456 registry, country_code, type, line = line.split("|", 3)
457 except:
458 log.warning("Could not parse line: %s" % line)
459 return
6ffd06b5 460
429a43d1
MT
461 # Skip any lines that are for stats only
462 if country_code == "*":
6ffd06b5
MT
463 return
464
429a43d1
MT
465 if type in ("ipv6", "ipv4"):
466 return self._parse_ip_line(country_code, type, line)
467
429a43d1
MT
468 def _parse_ip_line(self, country, type, line):
469 try:
470 address, prefix, date, status, organization = line.split("|")
471 except ValueError:
472 organization = None
473
474 # Try parsing the line without organization
475 try:
476 address, prefix, date, status = line.split("|")
477 except ValueError:
478 log.warning("Unhandled line format: %s" % line)
479 return
480
481 # Skip anything that isn't properly assigned
482 if not status in ("assigned", "allocated"):
483 return
484
485 # Cast prefix into an integer
486 try:
487 prefix = int(prefix)
488 except:
489 log.warning("Invalid prefix: %s" % prefix)
7177031f 490 return
429a43d1
MT
491
492 # Fix prefix length for IPv4
493 if type == "ipv4":
494 prefix = 32 - int(math.log(prefix, 2))
495
496 # Try to parse the address
497 try:
498 network = ipaddress.ip_network("%s/%s" % (address, prefix), strict=False)
499 except ValueError:
500 log.warning("Invalid IP address: %s" % address)
501 return
502
87b3e102
MT
503 self.db.execute("INSERT INTO networks(network, country) \
504 VALUES(%s, %s) ON CONFLICT (network) DO \
505 UPDATE SET country = excluded.country",
506 "%s" % network, country,
6ffd06b5
MT
507 )
508
83d61c46
MT
509 def handle_update_announcements(self, ns):
510 server = ns.server[0]
511
22d8d199
MT
512 with self.db.transaction():
513 if server.startswith("/"):
514 self._handle_update_announcements_from_bird(server)
515 else:
516 self._handle_update_announcements_from_telnet(server)
517
518 # Purge anything we never want here
519 self.db.execute("""
520 -- Delete default routes
521 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
522
523 -- Delete anything that is not global unicast address space
524 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
525
526 -- DELETE "current network" address space
527 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '0.0.0.0/8';
528
529 -- DELETE local loopback address space
530 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '127.0.0.0/8';
531
532 -- DELETE RFC 1918 address space
533 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
534 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
535 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
536
537 -- DELETE test, benchmark and documentation address space
538 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.0.0/24';
539 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.2.0/24';
540 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.18.0.0/15';
541 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.51.100.0/24';
542 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '203.0.113.0/24';
543
544 -- DELETE CGNAT address space (RFC 6598)
545 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '100.64.0.0/10';
546
547 -- DELETE link local address space
548 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '169.254.0.0/16';
549
550 -- DELETE IPv6 to IPv4 (6to4) address space
551 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.88.99.0/24';
552
553 -- DELETE multicast and reserved address space
554 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '224.0.0.0/4';
555 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '240.0.0.0/4';
556
557 -- Delete networks that are too small to be in the global routing table
558 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
559 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
560
561 -- Delete any non-public or reserved ASNs
562 DELETE FROM announcements WHERE NOT (
563 (autnum >= 1 AND autnum <= 23455)
564 OR
565 (autnum >= 23457 AND autnum <= 64495)
566 OR
567 (autnum >= 131072 AND autnum <= 4199999999)
568 );
569
570 -- Delete everything that we have not seen for 14 days
571 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
572 """)
573
574 def _handle_update_announcements_from_bird(self, server):
575 # Pre-compile the regular expression for faster searching
dc0be5c5 576 route = re.compile(b"^\s(.+?)\s+.+?\[AS(.*?).\]$")
22d8d199
MT
577
578 log.info("Requesting routing table from Bird (%s)" % server)
579
580 # Send command to list all routes
581 for line in self._bird_cmd(server, "show route"):
582 m = route.match(line)
583 if not m:
584 log.debug("Could not parse line: %s" % line.decode())
585 continue
586
587 # Fetch the extracted network and ASN
588 network, autnum = m.groups()
589
590 # Insert it into the database
591 self.db.execute("INSERT INTO announcements(network, autnum) \
592 VALUES(%s, %s) ON CONFLICT (network) DO \
593 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
594 network.decode(), autnum.decode(),
595 )
596
597 def _handle_update_announcements_from_telnet(self, server):
83d61c46 598 # Pre-compile regular expression for routes
83d61c46
MT
599 route = re.compile(b"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re.MULTILINE|re.DOTALL)
600
601 with telnetlib.Telnet(server) as t:
602 # Enable debug mode
603 #if ns.debug:
604 # t.set_debuglevel(10)
605
606 # Wait for console greeting
fcd5b8b2
MT
607 greeting = t.read_until(b"> ", timeout=30)
608 if not greeting:
609 log.error("Could not get a console prompt")
610 return 1
83d61c46
MT
611
612 # Disable pagination
613 t.write(b"terminal length 0\n")
614
615 # Wait for the prompt to return
616 t.read_until(b"> ")
617
618 # Fetch the routing tables
22d8d199
MT
619 for protocol in ("ipv6", "ipv4"):
620 log.info("Requesting %s routing table" % protocol)
83d61c46 621
22d8d199
MT
622 # Request the full unicast routing table
623 t.write(b"show bgp %s unicast\n" % protocol.encode())
83d61c46 624
22d8d199
MT
625 # Read entire header which ends with "Path"
626 t.read_until(b"Path\r\n")
83d61c46 627
22d8d199
MT
628 while True:
629 # Try reading a full entry
630 # Those might be broken across multiple lines but ends with i
631 line = t.read_until(b"i\r\n", timeout=5)
632 if not line:
633 break
83d61c46 634
22d8d199
MT
635 # Show line for debugging
636 #log.debug(repr(line))
d773c1bc 637
22d8d199
MT
638 # Try finding a route in here
639 m = route.match(line)
640 if m:
641 network, autnum = m.groups()
83d61c46 642
22d8d199
MT
643 # Convert network to string
644 network = network.decode()
83d61c46 645
22d8d199
MT
646 # Append /24 for IPv4 addresses
647 if not "/" in network and not ":" in network:
648 network = "%s/24" % network
83d61c46 649
22d8d199
MT
650 # Convert AS number to integer
651 autnum = int(autnum)
83d61c46 652
22d8d199 653 log.info("Found announcement for %s by %s" % (network, autnum))
83d61c46 654
22d8d199
MT
655 self.db.execute("INSERT INTO announcements(network, autnum) \
656 VALUES(%s, %s) ON CONFLICT (network) DO \
657 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
658 network, autnum,
659 )
83d61c46 660
22d8d199 661 log.info("Finished reading the %s routing table" % protocol)
1d4e4e8f 662
22d8d199
MT
663 def _bird_cmd(self, socket_path, command):
664 # Connect to the socket
665 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
666 s.connect(socket_path)
cedee656 667
22d8d199
MT
668 # Allocate some buffer
669 buffer = b""
83d61c46 670
22d8d199
MT
671 # Send the command
672 s.send(b"%s\n" % command.encode())
209c04b6 673
22d8d199
MT
674 while True:
675 # Fill up the buffer
676 buffer += s.recv(4096)
209c04b6 677
22d8d199
MT
678 while True:
679 # Search for the next newline
680 pos = buffer.find(b"\n")
209c04b6 681
22d8d199
MT
682 # If we cannot find one, we go back and read more data
683 if pos <= 0:
684 break
209c04b6 685
22d8d199
MT
686 # Cut after the newline character
687 pos += 1
b89cee80 688
22d8d199
MT
689 # Split the line we want and keep the rest in buffer
690 line, buffer = buffer[:pos], buffer[pos:]
83d61c46 691
22d8d199
MT
692 # Look for the end-of-output indicator
693 if line == b"0000 \n":
694 return
83d61c46 695
22d8d199
MT
696 # Otherwise return the line
697 yield line
83d61c46 698
d7fc3057
MT
699 def handle_update_overrides(self, ns):
700 with self.db.transaction():
701 # Drop all data that we have
702 self.db.execute("""
703 TRUNCATE TABLE autnum_overrides;
704 TRUNCATE TABLE network_overrides;
705 """)
706
707 for file in ns.files:
708 log.info("Reading %s..." % file)
709
710 with open(file, "rb") as f:
711 for type, block in location.importer.read_blocks(f):
712 if type == "net":
713 network = block.get("net")
714 # Try to parse and normalise the network
715 try:
716 network = ipaddress.ip_network(network, strict=False)
717 except ValueError as e:
718 log.warning("Invalid IP network: %s: %s" % (network, e))
719 continue
720
94dfab8c
MT
721 # Prevent that we overwrite all networks
722 if network.prefixlen == 0:
723 log.warning("Skipping %s: You cannot overwrite default" % network)
724 continue
725
d7fc3057
MT
726 self.db.execute("""
727 INSERT INTO network_overrides(
728 network,
729 country,
730 is_anonymous_proxy,
731 is_satellite_provider,
732 is_anycast
56f6587a 733 ) VALUES (%s, %s, %s, %s, %s)
d7fc3057
MT
734 ON CONFLICT (network) DO NOTHING""",
735 "%s" % network,
736 block.get("country"),
28d29b7c
MT
737 self._parse_bool(block, "is-anonymous-proxy"),
738 self._parse_bool(block, "is-satellite-provider"),
739 self._parse_bool(block, "is-anycast"),
d7fc3057
MT
740 )
741
f476cdfd
MT
742 elif type == "aut-num":
743 autnum = block.get("aut-num")
d7fc3057
MT
744
745 # Check if AS number begins with "AS"
746 if not autnum.startswith("AS"):
747 log.warning("Invalid AS number: %s" % autnum)
748 continue
749
750 # Strip "AS"
751 autnum = autnum[2:]
752
753 self.db.execute("""
754 INSERT INTO autnum_overrides(
755 number,
756 name,
bd1aa6a1 757 country,
d7fc3057
MT
758 is_anonymous_proxy,
759 is_satellite_provider,
760 is_anycast
bd1aa6a1 761 ) VALUES(%s, %s, %s, %s, %s, %s)
d7fc3057 762 ON CONFLICT DO NOTHING""",
bd1aa6a1
MT
763 autnum,
764 block.get("name"),
765 block.get("country"),
28d29b7c
MT
766 self._parse_bool(block, "is-anonymous-proxy"),
767 self._parse_bool(block, "is-satellite-provider"),
768 self._parse_bool(block, "is-anycast"),
d7fc3057
MT
769 )
770
771 else:
772 log.warning("Unsupport type: %s" % type)
773
28d29b7c
MT
774 @staticmethod
775 def _parse_bool(block, key):
776 val = block.get(key)
777
778 # There is no point to proceed when we got None
779 if val is None:
780 return
781
782 # Convert to lowercase
783 val = val.lower()
784
785 # True
786 if val in ("yes", "1"):
787 return True
788
789 # False
790 if val in ("no", "0"):
791 return False
792
793 # Default to None
794 return None
795
8084b33a
MT
796 def handle_import_countries(self, ns):
797 with self.db.transaction():
798 # Drop all data that we have
799 self.db.execute("TRUNCATE TABLE countries")
800
801 for file in ns.file:
802 for line in file:
803 line = line.rstrip()
804
805 # Ignore any comments
806 if line.startswith("#"):
807 continue
808
809 try:
810 country_code, continent_code, name = line.split(maxsplit=2)
811 except:
812 log.warning("Could not parse line: %s" % line)
813 continue
814
815 self.db.execute("INSERT INTO countries(country_code, name, continent_code) \
816 VALUES(%s, %s, %s) ON CONFLICT DO NOTHING", country_code, name, continent_code)
817
6ffd06b5
MT
818
819def split_line(line):
820 key, colon, val = line.partition(":")
821
822 # Strip any excess space
823 key = key.strip()
824 val = val.strip()
78ff0cf2 825
6ffd06b5 826 return key, val
78ff0cf2
MT
827
828def main():
829 # Run the command line interface
830 c = CLI()
831 c.run()
832
833main()