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