2 libloc - A library to determine the location of someone on the Internet
4 Copyright (C) 2017 IPFire Development Team <info@ipfire.org>
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
17 #include <arpa/inet.h>
20 #include <netinet/in.h>
27 #include <sys/types.h>
35 #include <openssl/err.h>
36 #include <openssl/evp.h>
37 #include <openssl/pem.h>
39 #include <libloc/libloc.h>
40 #include <libloc/address.h>
41 #include <libloc/as.h>
42 #include <libloc/as-list.h>
43 #include <libloc/compat.h>
44 #include <libloc/country.h>
45 #include <libloc/country-list.h>
46 #include <libloc/database.h>
47 #include <libloc/format.h>
48 #include <libloc/network.h>
49 #include <libloc/network-list.h>
50 #include <libloc/private.h>
51 #include <libloc/stringpool.h>
53 struct loc_database_objects
{
66 enum loc_database_version version
;
74 size_t signature1_length
;
76 size_t signature2_length
;
78 struct loc_stringpool
* pool
;
80 // ASes in the database
81 struct loc_database_objects as_objects
;
84 struct loc_database_objects network_node_objects
;
87 struct loc_database_objects network_objects
;
90 struct loc_database_objects country_objects
;
93 #define MAX_STACK_DEPTH 256
95 struct loc_node_stack
{
97 int i
; // Is this node 0 or 1?
101 struct loc_database_enumerator
{
103 struct loc_database
* db
;
104 enum loc_database_enumerator_mode mode
;
109 struct loc_country_list
* countries
;
110 struct loc_as_list
* asns
;
111 enum loc_network_flags flags
;
117 // Index of the AS we are looking at
118 unsigned int as_index
;
120 // Index of the country we are looking at
121 unsigned int country_index
;
124 struct in6_addr network_address
;
125 struct loc_node_stack network_stack
[MAX_STACK_DEPTH
];
126 int network_stack_depth
;
127 unsigned int* networks_visited
;
129 // For subnet search and bogons
130 struct loc_network_list
* stack
;
131 struct loc_network_list
* subnets
;
134 struct in6_addr gap6_start
;
135 struct in6_addr gap4_start
;
138 #define loc_database_read_object(db, buffer, objects, pos) \
139 __loc_database_read_object(db, buffer, sizeof(*buffer), objects, pos)
142 Reads an object into memory (used when mmap() isn't available)
144 static void* __loc_database_read_object(struct loc_database
* db
, void* buffer
,
145 const size_t length
, const struct loc_database_objects
* objects
, const off_t pos
) {
147 const off_t offset
= pos
* length
;
149 // Map the object first if possible
151 return (uint8_t*)objects
->p
+ offset
;
153 // Otherwise fall back and read the object into the buffer
154 const int fd
= fileno(db
->f
);
157 ssize_t bytes_read
= pread(fd
, buffer
, length
, objects
->offset
+ offset
);
159 // Check if we could read what we wanted
160 if (bytes_read
< (ssize_t
)length
) {
161 ERROR(db
->ctx
, "Error reading object from database: %m\n");
169 static int loc_database_read_magic(struct loc_database
* db
) {
170 struct loc_database_magic magic
;
173 size_t bytes_read
= fread(&magic
, 1, sizeof(magic
), db
->f
);
175 // Check if we have been able to read enough data
176 if (bytes_read
< sizeof(magic
)) {
177 ERROR(db
->ctx
, "Could not read enough data to validate magic bytes\n");
178 DEBUG(db
->ctx
, "Read %zu bytes, but needed %zu\n", bytes_read
, sizeof(magic
));
182 // Compare magic bytes
183 if (memcmp(LOC_DATABASE_MAGIC
, magic
.magic
, strlen(LOC_DATABASE_MAGIC
)) == 0) {
184 DEBUG(db
->ctx
, "Magic value matches\n");
187 db
->version
= magic
.version
;
193 ERROR(db
->ctx
, "Unrecognized file type\n");
201 Maps arbitrary objects from the database into memory.
203 static int loc_database_map_objects(struct loc_database
* db
,
204 struct loc_database_objects
* objects
, const size_t size
,
205 off_t offset
, size_t length
) {
209 objects
->offset
= offset
;
210 objects
->length
= length
;
211 objects
->count
= objects
->length
/ size
;
213 // End if there is nothing to map
214 if (!objects
->length
)
217 DEBUG(db
->ctx
, "Mapping %zu object(s) from %jd (%zu bytes)\n",
218 objects
->count
, (intmax_t)objects
->offset
, objects
->length
);
220 // mmap() objects into memory
221 void* p
= mmap(NULL
, objects
->length
, PROT_READ
, MAP_PRIVATE
,
222 fileno(db
->f
), objects
->offset
);
224 if (p
== MAP_FAILED
) {
225 // Ignore if the database wasn't page aligned for this architecture
226 // and fall back to use pread().
227 if (errno
== EINVAL
) {
228 DEBUG(db
->ctx
, "Falling back to pread()\n");
232 ERROR(db
->ctx
, "mmap() failed: %m\n");
242 static int loc_database_unmap_objects(struct loc_database
* db
,
243 struct loc_database_objects
* objects
) {
246 // Nothing to do if nothing was mapped
250 // Call munmap() to free everything
251 r
= munmap(objects
->p
, objects
->length
);
253 ERROR(db
->ctx
, "Could not unmap objects: %m\n");
260 static int loc_database_read_signature(struct loc_database
* db
,
261 char** dst
, char* src
, size_t length
) {
262 // Check for a plausible signature length
263 if (length
> LOC_SIGNATURE_MAX_LENGTH
) {
264 ERROR(db
->ctx
, "Signature too long: %zu\n", length
);
268 DEBUG(db
->ctx
, "Reading signature of %zu bytes\n", length
);
271 *dst
= malloc(length
);
276 memcpy(*dst
, src
, length
);
281 static int loc_database_read_header_v1(struct loc_database
* db
) {
282 struct loc_database_header_v1 header
;
286 size_t size
= fread(&header
, 1, sizeof(header
), db
->f
);
288 if (size
< sizeof(header
)) {
289 ERROR(db
->ctx
, "Could not read enough data for header\n");
295 db
->created_at
= be64toh(header
.created_at
);
296 db
->vendor
= be32toh(header
.vendor
);
297 db
->description
= be32toh(header
.description
);
298 db
->license
= be32toh(header
.license
);
300 db
->signature1_length
= be16toh(header
.signature1_length
);
301 db
->signature2_length
= be16toh(header
.signature2_length
);
304 if (db
->signature1_length
) {
305 r
= loc_database_read_signature(db
, &db
->signature1
,
306 header
.signature1
, db
->signature1_length
);
311 if (db
->signature2_length
) {
312 r
= loc_database_read_signature(db
, &db
->signature2
,
313 header
.signature2
, db
->signature2_length
);
318 // Open the stringpool
319 r
= loc_stringpool_open(db
->ctx
, &db
->pool
, db
->f
,
320 be32toh(header
.pool_length
), be32toh(header
.pool_offset
));
325 r
= loc_database_map_objects(db
, &db
->as_objects
,
326 sizeof(struct loc_database_as_v1
),
327 be32toh(header
.as_offset
),
328 be32toh(header
.as_length
));
333 r
= loc_database_map_objects(db
, &db
->network_node_objects
,
334 sizeof(struct loc_database_network_node_v1
),
335 be32toh(header
.network_tree_offset
),
336 be32toh(header
.network_tree_length
));
341 r
= loc_database_map_objects(db
, &db
->network_objects
,
342 sizeof(struct loc_database_network_v1
),
343 be32toh(header
.network_data_offset
),
344 be32toh(header
.network_data_length
));
349 r
= loc_database_map_objects(db
, &db
->country_objects
,
350 sizeof(struct loc_database_country_v1
),
351 be32toh(header
.countries_offset
),
352 be32toh(header
.countries_length
));
359 static int loc_database_read_header(struct loc_database
* db
) {
360 DEBUG(db
->ctx
, "Database version is %u\n", db
->version
);
362 switch (db
->version
) {
363 case LOC_DATABASE_VERSION_1
:
364 return loc_database_read_header_v1(db
);
367 ERROR(db
->ctx
, "Incompatible database version: %u\n", db
->version
);
372 static int loc_database_read(struct loc_database
* db
, FILE* f
) {
373 clock_t start
= clock();
377 // Clone file descriptor
380 ERROR(db
->ctx
, "Could not duplicate file descriptor\n");
384 // Reopen the file so that we can keep our own file handle
385 db
->f
= fdopen(fd
, "r");
387 ERROR(db
->ctx
, "Could not re-open database file\n");
391 // Rewind to the start of the file
395 int r
= loc_database_read_magic(db
);
400 r
= loc_database_read_header(db
);
404 clock_t end
= clock();
406 INFO(db
->ctx
, "Opened database in %.4fms\n",
407 (double)(end
- start
) / CLOCKS_PER_SEC
* 1000);
412 LOC_EXPORT
int loc_database_new(struct loc_ctx
* ctx
, struct loc_database
** database
, FILE* f
) {
413 // Fail on invalid file handle
417 struct loc_database
* db
= calloc(1, sizeof(*db
));
422 db
->ctx
= loc_ref(ctx
);
425 DEBUG(db
->ctx
, "Database object allocated at %p\n", db
);
427 int r
= loc_database_read(db
, f
);
429 loc_database_unref(db
);
438 LOC_EXPORT
struct loc_database
* loc_database_ref(struct loc_database
* db
) {
444 static void loc_database_free(struct loc_database
* db
) {
445 DEBUG(db
->ctx
, "Releasing database %p\n", db
);
448 loc_database_unmap_objects(db
, &db
->as_objects
);
450 // Remove mapped network sections
451 loc_database_unmap_objects(db
, &db
->network_objects
);
453 // Remove mapped network nodes section
454 loc_database_unmap_objects(db
, &db
->network_node_objects
);
456 // Remove mapped countries section
457 loc_database_unmap_objects(db
, &db
->country_objects
);
459 // Free the stringpool
461 loc_stringpool_unref(db
->pool
);
465 free(db
->signature1
);
467 free(db
->signature2
);
469 // Close database file
477 LOC_EXPORT
struct loc_database
* loc_database_unref(struct loc_database
* db
) {
478 if (--db
->refcount
> 0)
481 loc_database_free(db
);
485 LOC_EXPORT
int loc_database_verify(struct loc_database
* db
, FILE* f
) {
486 size_t bytes_read
= 0;
488 // Cannot do this when no signature is available
489 if (!db
->signature1
&& !db
->signature2
) {
490 DEBUG(db
->ctx
, "No signature available to verify\n");
494 // Start the stopwatch
495 clock_t start
= clock();
498 EVP_PKEY
* pkey
= PEM_read_PUBKEY(f
, NULL
, NULL
, NULL
);
500 ERROR(db
->ctx
, "Could not parse public key: %s\n",
501 ERR_error_string(ERR_get_error(), NULL
));
508 EVP_MD_CTX
* mdctx
= EVP_MD_CTX_new();
510 // Initialise hash function
511 r
= EVP_DigestVerifyInit(mdctx
, NULL
, NULL
, NULL
, pkey
);
513 ERROR(db
->ctx
, "Error initializing signature validation: %s\n",
514 ERR_error_string(ERR_get_error(), NULL
));
520 // Reset file to start
524 struct loc_database_magic magic
;
525 bytes_read
= fread(&magic
, 1, sizeof(magic
), db
->f
);
526 if (bytes_read
< sizeof(magic
)) {
527 ERROR(db
->ctx
, "Could not read header: %m\n");
532 hexdump(db
->ctx
, &magic
, sizeof(magic
));
534 // Feed magic into the hash
535 r
= EVP_DigestVerifyUpdate(mdctx
, &magic
, sizeof(magic
));
537 ERROR(db
->ctx
, "%s\n", ERR_error_string(ERR_get_error(), NULL
));
544 struct loc_database_header_v1 header_v1
;
546 switch (db
->version
) {
547 case LOC_DATABASE_VERSION_1
:
548 bytes_read
= fread(&header_v1
, 1, sizeof(header_v1
), db
->f
);
549 if (bytes_read
< sizeof(header_v1
)) {
550 ERROR(db
->ctx
, "Could not read header\n");
557 memset(header_v1
.signature1
, '\0', sizeof(header_v1
.signature1
));
558 header_v1
.signature1_length
= 0;
559 memset(header_v1
.signature2
, '\0', sizeof(header_v1
.signature2
));
560 header_v1
.signature2_length
= 0;
562 hexdump(db
->ctx
, &header_v1
, sizeof(header_v1
));
564 // Feed header into the hash
565 r
= EVP_DigestVerifyUpdate(mdctx
, &header_v1
, sizeof(header_v1
));
567 ERROR(db
->ctx
, "%s\n", ERR_error_string(ERR_get_error(), NULL
));
575 ERROR(db
->ctx
, "Cannot compute hash for database with format %d\n",
581 // Walk through the file in chunks of 64kB
582 char buffer
[64 * 1024];
584 while (!feof(db
->f
)) {
585 bytes_read
= fread(buffer
, 1, sizeof(buffer
), db
->f
);
587 hexdump(db
->ctx
, buffer
, bytes_read
);
589 r
= EVP_DigestVerifyUpdate(mdctx
, buffer
, bytes_read
);
591 ERROR(db
->ctx
, "%s\n", ERR_error_string(ERR_get_error(), NULL
));
598 // Check first signature
599 if (db
->signature1
) {
600 hexdump(db
->ctx
, db
->signature1
, db
->signature1_length
);
602 r
= EVP_DigestVerifyFinal(mdctx
,
603 (unsigned char*)db
->signature1
, db
->signature1_length
);
606 DEBUG(db
->ctx
, "The first signature is invalid\n");
609 DEBUG(db
->ctx
, "The first signature is valid\n");
612 ERROR(db
->ctx
, "Error verifying the first signature: %s\n",
613 ERR_error_string(ERR_get_error(), NULL
));
618 // Check second signature only when the first one was invalid
619 if (r
&& db
->signature2
) {
620 hexdump(db
->ctx
, db
->signature2
, db
->signature2_length
);
622 r
= EVP_DigestVerifyFinal(mdctx
,
623 (unsigned char*)db
->signature2
, db
->signature2_length
);
626 DEBUG(db
->ctx
, "The second signature is invalid\n");
629 DEBUG(db
->ctx
, "The second signature is valid\n");
632 ERROR(db
->ctx
, "Error verifying the second signature: %s\n",
633 ERR_error_string(ERR_get_error(), NULL
));
638 clock_t end
= clock();
639 INFO(db
->ctx
, "Signature checked in %.4fms\n",
640 (double)(end
- start
) / CLOCKS_PER_SEC
* 1000);
644 EVP_MD_CTX_free(mdctx
);
650 LOC_EXPORT
time_t loc_database_created_at(struct loc_database
* db
) {
651 return db
->created_at
;
654 LOC_EXPORT
const char* loc_database_get_vendor(struct loc_database
* db
) {
655 return loc_stringpool_get(db
->pool
, db
->vendor
);
658 LOC_EXPORT
const char* loc_database_get_description(struct loc_database
* db
) {
659 return loc_stringpool_get(db
->pool
, db
->description
);
662 LOC_EXPORT
const char* loc_database_get_license(struct loc_database
* db
) {
663 return loc_stringpool_get(db
->pool
, db
->license
);
666 LOC_EXPORT
size_t loc_database_count_as(struct loc_database
* db
) {
667 return db
->as_objects
.count
;
670 // Returns the AS at position pos
671 static int loc_database_fetch_as(struct loc_database
* db
, struct loc_as
** as
, off_t pos
) {
672 struct loc_database_as_v1 as_v1
;
673 struct loc_database_as_v1
* p_v1
;
676 if ((size_t)pos
>= db
->as_objects
.count
) {
681 DEBUG(db
->ctx
, "Fetching AS at position %jd\n", (intmax_t)pos
);
683 switch (db
->version
) {
684 case LOC_DATABASE_VERSION_1
:
686 p_v1
= loc_database_read_object(db
, &as_v1
, &db
->as_objects
, pos
);
690 r
= loc_as_new_from_database_v1(db
->ctx
, db
->pool
, as
, p_v1
);
699 DEBUG(db
->ctx
, "Got AS%u\n", loc_as_get_number(*as
));
704 // Performs a binary search to find the AS in the list
705 LOC_EXPORT
int loc_database_get_as(struct loc_database
* db
, struct loc_as
** as
, uint32_t number
) {
707 off_t hi
= db
->as_objects
.count
- 1;
711 clock_t start
= clock();
715 off_t i
= (lo
+ hi
) / 2;
717 // Fetch AS in the middle between lo and hi
718 int r
= loc_database_fetch_as(db
, as
, i
);
722 // Check if this is a match
723 uint32_t as_number
= loc_as_get_number(*as
);
724 if (as_number
== number
) {
726 clock_t end
= clock();
728 // Log how fast this has been
729 DEBUG(db
->ctx
, "Found AS%u in %.4fms\n", as_number
,
730 (double)(end
- start
) / CLOCKS_PER_SEC
* 1000);
736 // If it wasn't, we release the AS and
737 // adjust our search pointers
740 if (as_number
< number
) {
752 // Returns the network at position pos
753 static int loc_database_fetch_network(struct loc_database
* db
, struct loc_network
** network
,
754 struct in6_addr
* address
, unsigned int prefix
, off_t pos
) {
755 struct loc_database_network_v1 network_v1
;
756 struct loc_database_network_v1
* p_v1
;
759 if ((size_t)pos
>= db
->network_objects
.count
) {
760 DEBUG(db
->ctx
, "Network ID out of range: %jd/%jd\n",
761 (intmax_t)pos
, (intmax_t)db
->network_objects
.count
);
766 DEBUG(db
->ctx
, "Fetching network at position %jd\n", (intmax_t)pos
);
768 switch (db
->version
) {
769 case LOC_DATABASE_VERSION_1
:
771 p_v1
= loc_database_read_object(db
, &network_v1
, &db
->network_objects
, pos
);
775 r
= loc_network_new_from_database_v1(db
->ctx
, network
, address
, prefix
, p_v1
);
784 DEBUG(db
->ctx
, "Got network %s\n", loc_network_str(*network
));
789 static int __loc_database_node_is_leaf(const struct loc_database_network_node_v1
* node
) {
790 return (node
->network
!= htobe32(0xffffffff));
793 static int __loc_database_lookup_handle_leaf(struct loc_database
* db
, const struct in6_addr
* address
,
794 struct loc_network
** network
, struct in6_addr
* network_address
, unsigned int prefix
,
795 const struct loc_database_network_node_v1
* node
) {
796 off_t network_index
= be32toh(node
->network
);
798 DEBUG(db
->ctx
, "Handling leaf node at %jd\n", (intmax_t)network_index
);
801 int r
= loc_database_fetch_network(db
, network
, network_address
, prefix
, network_index
);
803 ERROR(db
->ctx
, "Could not fetch network %jd from database: %m\n",
804 (intmax_t)network_index
);
808 // Check if the given IP address is inside the network
809 if (!loc_network_matches_address(*network
, address
)) {
810 DEBUG(db
->ctx
, "Searched address is not part of the network\n");
812 loc_network_unref(*network
);
817 // A network was found and the IP address matches
821 // Searches for an exact match along the path
822 static int __loc_database_lookup(struct loc_database
* db
, const struct in6_addr
* address
,
823 struct loc_network
** network
, struct in6_addr
* network_address
,
824 off_t node_index
, unsigned int level
) {
825 struct loc_database_network_node_v1 node_v1
;
826 struct loc_database_network_node_v1
* p_v1
;
830 // Fetch the next node
831 p_v1
= loc_database_read_object(db
, &node_v1
, &db
->network_node_objects
, node_index
);
836 int bit
= loc_address_get_bit(address
, level
);
837 loc_address_set_bit(network_address
, level
, bit
);
840 node_index
= be32toh(p_v1
->zero
);
842 node_index
= be32toh(p_v1
->one
);
844 // If the node index is zero, the tree ends here
845 // and we cannot descend any further
846 if (node_index
> 0) {
848 if ((size_t)node_index
>= db
->network_node_objects
.count
) {
853 // Move on to the next node
854 r
= __loc_database_lookup(db
, address
, network
, network_address
, node_index
, level
+ 1);
856 // End here if a result was found
864 DEBUG(db
->ctx
, "No match found below level %u\n", level
);
866 DEBUG(db
->ctx
, "Tree ended at level %u\n", level
);
869 // If this node has a leaf, we will check if it matches
870 if (__loc_database_node_is_leaf(p_v1
)) {
871 r
= __loc_database_lookup_handle_leaf(db
, address
, network
, network_address
, level
, p_v1
);
879 LOC_EXPORT
int loc_database_lookup(struct loc_database
* db
,
880 const struct in6_addr
* address
, struct loc_network
** network
) {
881 struct in6_addr network_address
;
882 memset(&network_address
, 0, sizeof(network_address
));
888 clock_t start
= clock();
891 int r
= __loc_database_lookup(db
, address
, network
, &network_address
, 0, 0);
894 clock_t end
= clock();
896 // Log how fast this has been
897 DEBUG(db
->ctx
, "Executed network search in %.4fms\n",
898 (double)(end
- start
) / CLOCKS_PER_SEC
* 1000);
904 LOC_EXPORT
int loc_database_lookup_from_string(struct loc_database
* db
,
905 const char* string
, struct loc_network
** network
) {
906 struct in6_addr address
;
908 int r
= loc_address_parse(&address
, NULL
, string
);
912 return loc_database_lookup(db
, &address
, network
);
915 // Returns the country at position pos
916 static int loc_database_fetch_country(struct loc_database
* db
,
917 struct loc_country
** country
, off_t pos
) {
918 struct loc_database_country_v1 country_v1
;
919 struct loc_database_country_v1
* p_v1
;
922 // Check if the country is within range
923 if ((size_t)pos
>= db
->country_objects
.count
) {
928 DEBUG(db
->ctx
, "Fetching country at position %jd\n", (intmax_t)pos
);
930 switch (db
->version
) {
931 case LOC_DATABASE_VERSION_1
:
933 p_v1
= loc_database_read_object(db
, &country_v1
, &db
->country_objects
, pos
);
937 r
= loc_country_new_from_database_v1(db
->ctx
, db
->pool
, country
, p_v1
);
946 DEBUG(db
->ctx
, "Got country %s\n", loc_country_get_code(*country
));
951 // Performs a binary search to find the country in the list
952 LOC_EXPORT
int loc_database_get_country(struct loc_database
* db
,
953 struct loc_country
** country
, const char* code
) {
955 off_t hi
= db
->country_objects
.count
- 1;
959 clock_t start
= clock();
963 off_t i
= (lo
+ hi
) / 2;
965 // Fetch country in the middle between lo and hi
966 int r
= loc_database_fetch_country(db
, country
, i
);
970 // Check if this is a match
971 const char* cc
= loc_country_get_code(*country
);
972 int result
= strcmp(code
, cc
);
976 clock_t end
= clock();
978 // Log how fast this has been
979 DEBUG(db
->ctx
, "Found country %s in %.4fms\n", cc
,
980 (double)(end
- start
) / CLOCKS_PER_SEC
* 1000);
986 // If it wasn't, we release the country and
987 // adjust our search pointers
988 loc_country_unref(*country
);
1004 static void loc_database_enumerator_free(struct loc_database_enumerator
* enumerator
) {
1005 DEBUG(enumerator
->ctx
, "Releasing database enumerator %p\n", enumerator
);
1007 // Release all references
1008 loc_database_unref(enumerator
->db
);
1009 loc_unref(enumerator
->ctx
);
1011 if (enumerator
->string
)
1012 free(enumerator
->string
);
1014 if (enumerator
->countries
)
1015 loc_country_list_unref(enumerator
->countries
);
1017 if (enumerator
->asns
)
1018 loc_as_list_unref(enumerator
->asns
);
1020 // Free network search
1021 if (enumerator
->networks_visited
)
1022 free(enumerator
->networks_visited
);
1024 // Free subnet/bogons stack
1025 if (enumerator
->stack
)
1026 loc_network_list_unref(enumerator
->stack
);
1028 if (enumerator
->subnets
)
1029 loc_network_list_unref(enumerator
->subnets
);
1034 LOC_EXPORT
int loc_database_enumerator_new(struct loc_database_enumerator
** enumerator
,
1035 struct loc_database
* db
, enum loc_database_enumerator_mode mode
, int flags
) {
1038 struct loc_database_enumerator
* e
= calloc(1, sizeof(*e
));
1043 // Reference context
1044 e
->ctx
= loc_ref(db
->ctx
);
1045 e
->db
= loc_database_ref(db
);
1050 e
->flatten
= (flags
& LOC_DB_ENUMERATOR_FLAGS_FLATTEN
);
1052 // Initialise graph search
1053 e
->network_stack_depth
= 1;
1054 e
->networks_visited
= calloc(db
->network_node_objects
.count
, sizeof(*e
->networks_visited
));
1055 printf("COUNT = %zu, P = %p\n", db
->network_node_objects
.count
, e
->networks_visited
);
1056 if (!e
->networks_visited
) {
1057 ERROR(db
->ctx
, "Could not allocated visited networks: %m\n");
1063 r
= loc_network_list_new(e
->ctx
, &e
->stack
);
1067 // Initialize bogon search
1068 loc_address_reset(&e
->gap6_start
, AF_INET6
);
1069 loc_address_reset(&e
->gap4_start
, AF_INET
);
1071 DEBUG(e
->ctx
, "Database enumerator object allocated at %p\n", e
);
1078 loc_database_enumerator_free(e
);
1083 LOC_EXPORT
struct loc_database_enumerator
* loc_database_enumerator_ref(struct loc_database_enumerator
* enumerator
) {
1084 enumerator
->refcount
++;
1089 LOC_EXPORT
struct loc_database_enumerator
* loc_database_enumerator_unref(struct loc_database_enumerator
* enumerator
) {
1093 if (--enumerator
->refcount
> 0)
1096 loc_database_enumerator_free(enumerator
);
1100 LOC_EXPORT
int loc_database_enumerator_set_string(struct loc_database_enumerator
* enumerator
, const char* string
) {
1101 enumerator
->string
= strdup(string
);
1103 // Make the string lowercase
1104 for (char *p
= enumerator
->string
; *p
; p
++)
1110 LOC_EXPORT
struct loc_country_list
* loc_database_enumerator_get_countries(
1111 struct loc_database_enumerator
* enumerator
) {
1112 if (!enumerator
->countries
)
1115 return loc_country_list_ref(enumerator
->countries
);
1118 LOC_EXPORT
int loc_database_enumerator_set_countries(
1119 struct loc_database_enumerator
* enumerator
, struct loc_country_list
* countries
) {
1120 if (enumerator
->countries
)
1121 loc_country_list_unref(enumerator
->countries
);
1123 enumerator
->countries
= loc_country_list_ref(countries
);
1128 LOC_EXPORT
struct loc_as_list
* loc_database_enumerator_get_asns(
1129 struct loc_database_enumerator
* enumerator
) {
1130 if (!enumerator
->asns
)
1133 return loc_as_list_ref(enumerator
->asns
);
1136 LOC_EXPORT
int loc_database_enumerator_set_asns(
1137 struct loc_database_enumerator
* enumerator
, struct loc_as_list
* asns
) {
1138 if (enumerator
->asns
)
1139 loc_as_list_unref(enumerator
->asns
);
1141 enumerator
->asns
= loc_as_list_ref(asns
);
1146 LOC_EXPORT
int loc_database_enumerator_set_flag(
1147 struct loc_database_enumerator
* enumerator
, enum loc_network_flags flag
) {
1148 enumerator
->flags
|= flag
;
1153 LOC_EXPORT
int loc_database_enumerator_set_family(
1154 struct loc_database_enumerator
* enumerator
, int family
) {
1155 enumerator
->family
= family
;
1160 LOC_EXPORT
int loc_database_enumerator_next_as(
1161 struct loc_database_enumerator
* enumerator
, struct loc_as
** as
) {
1164 // Do not do anything if not in AS mode
1165 if (enumerator
->mode
!= LOC_DB_ENUMERATE_ASES
)
1168 struct loc_database
* db
= enumerator
->db
;
1170 while (enumerator
->as_index
< db
->as_objects
.count
) {
1171 // Fetch the next AS
1172 int r
= loc_database_fetch_as(db
, as
, enumerator
->as_index
++);
1176 r
= loc_as_match_string(*as
, enumerator
->string
);
1178 DEBUG(enumerator
->ctx
, "AS%d (%s) matches %s\n",
1179 loc_as_get_number(*as
), loc_as_get_name(*as
), enumerator
->string
);
1190 enumerator
->as_index
= 0;
1192 // We have searched through all of them
1196 static int loc_database_enumerator_stack_push_node(
1197 struct loc_database_enumerator
* e
, off_t offset
, int i
, int depth
) {
1198 // Do not add empty nodes
1202 // Check if there is any space left on the stack
1203 if (e
->network_stack_depth
>= MAX_STACK_DEPTH
) {
1204 ERROR(e
->ctx
, "Maximum stack size reached: %d\n", e
->network_stack_depth
);
1208 // Check if the node is in range
1209 if (offset
>= (off_t
)e
->db
->network_node_objects
.count
) {
1210 ERROR(e
->ctx
, "Trying to add invalid node with offset %jd/%zu\n",
1211 offset
, e
->db
->network_node_objects
.count
);
1216 // Increase stack size
1217 int s
= ++e
->network_stack_depth
;
1219 DEBUG(e
->ctx
, "Added node %jd to stack (%d)\n", (intmax_t)offset
, depth
);
1221 e
->network_stack
[s
].offset
= offset
;
1222 e
->network_stack
[s
].i
= i
;
1223 e
->network_stack
[s
].depth
= depth
;
1228 static int loc_database_enumerator_match_network(
1229 struct loc_database_enumerator
* enumerator
, struct loc_network
* network
) {
1230 // If family is set, it must match
1231 if (enumerator
->family
&& loc_network_address_family(network
) != enumerator
->family
) {
1232 DEBUG(enumerator
->ctx
, "Filtered network %p because of family not matching\n", network
);
1236 // Match if no filter criteria is configured
1237 if (!enumerator
->countries
&& !enumerator
->asns
&& !enumerator
->flags
)
1240 // Check if the country code matches
1241 if (enumerator
->countries
&& !loc_country_list_empty(enumerator
->countries
)) {
1242 const char* country_code
= loc_network_get_country_code(network
);
1244 if (loc_country_list_contains_code(enumerator
->countries
, country_code
)) {
1245 DEBUG(enumerator
->ctx
, "Matched network %p because of its country code\n", network
);
1250 // Check if the ASN matches
1251 if (enumerator
->asns
&& !loc_as_list_empty(enumerator
->asns
)) {
1252 uint32_t asn
= loc_network_get_asn(network
);
1254 if (loc_as_list_contains_number(enumerator
->asns
, asn
)) {
1255 DEBUG(enumerator
->ctx
, "Matched network %p because of its ASN\n", network
);
1260 // Check if flags match
1261 if (enumerator
->flags
&& loc_network_has_flag(network
, enumerator
->flags
)) {
1262 DEBUG(enumerator
->ctx
, "Matched network %p because of its flags\n", network
);
1270 static int __loc_database_enumerator_next_network(
1271 struct loc_database_enumerator
* enumerator
, struct loc_network
** network
, int filter
) {
1272 struct loc_database_network_node_v1 node_v1
;
1274 // Return top element from the stack
1276 *network
= loc_network_list_pop_first(enumerator
->stack
);
1282 // Return everything if filter isn't enabled, or only return matches
1283 if (!filter
|| loc_database_enumerator_match_network(enumerator
, *network
))
1286 // Throw away anything that doesn't match
1287 loc_network_unref(*network
);
1291 DEBUG(enumerator
->ctx
, "Called with a stack of %u nodes\n",
1292 enumerator
->network_stack_depth
);
1295 while (enumerator
->network_stack_depth
> 0) {
1296 DEBUG(enumerator
->ctx
, "Stack depth: %u\n", enumerator
->network_stack_depth
);
1298 // Get object from top of the stack
1299 struct loc_node_stack
* node
= &enumerator
->network_stack
[enumerator
->network_stack_depth
];
1301 DEBUG(enumerator
->ctx
, " Got node: %jd\n", node
->offset
);
1303 // Remove the node from the stack if we have already visited it
1304 if (enumerator
->networks_visited
[node
->offset
]) {
1305 enumerator
->network_stack_depth
--;
1309 // Mark the bits on the path correctly
1310 loc_address_set_bit(&enumerator
->network_address
,
1311 (node
->depth
> 0) ? node
->depth
- 1 : 0, node
->i
);
1313 DEBUG(enumerator
->ctx
, "Looking at node %jd\n", (intmax_t)node
->offset
);
1314 enumerator
->networks_visited
[node
->offset
]++;
1316 // Pop node from top of the stack
1317 struct loc_database_network_node_v1
* n
= loc_database_read_object(enumerator
->db
,
1318 &node_v1
, &enumerator
->db
->network_node_objects
, node
->offset
);
1322 // Add edges to stack
1323 int r
= loc_database_enumerator_stack_push_node(enumerator
,
1324 be32toh(n
->one
), 1, node
->depth
+ 1);
1328 r
= loc_database_enumerator_stack_push_node(enumerator
,
1329 be32toh(n
->zero
), 0, node
->depth
+ 1);
1333 // Check if this node is a leaf and has a network object
1334 if (__loc_database_node_is_leaf(n
)) {
1335 off_t network_index
= be32toh(n
->network
);
1337 DEBUG(enumerator
->ctx
, "Node has a network at %jd\n", (intmax_t)network_index
);
1339 // Fetch the network object
1340 r
= loc_database_fetch_network(enumerator
->db
, network
,
1341 &enumerator
->network_address
, node
->depth
, network_index
);
1343 // Break on any errors
1347 // Return all networks when the filter is disabled, or check for match
1348 if (!filter
|| loc_database_enumerator_match_network(enumerator
, *network
))
1351 // Does not seem to be a match, so we cleanup and move on
1352 loc_network_unref(*network
);
1357 // Reached the end of the search
1361 static int __loc_database_enumerator_next_network_flattened(
1362 struct loc_database_enumerator
* enumerator
, struct loc_network
** network
) {
1363 // Fetch the next network
1364 int r
= __loc_database_enumerator_next_network(enumerator
, network
, 1);
1368 // End if we could not read another network
1372 struct loc_network
* subnet
= NULL
;
1374 // Create a list with all subnets
1375 if (!enumerator
->subnets
) {
1376 r
= loc_network_list_new(enumerator
->ctx
, &enumerator
->subnets
);
1381 // Search all subnets from the database
1383 // Fetch the next network in line
1384 r
= __loc_database_enumerator_next_network(enumerator
, &subnet
, 0);
1386 loc_network_unref(subnet
);
1387 loc_network_list_clear(enumerator
->subnets
);
1392 // End if we did not receive another subnet
1396 // Collect all subnets in a list
1397 if (loc_network_is_subnet(*network
, subnet
)) {
1398 r
= loc_network_list_push(enumerator
->subnets
, subnet
);
1400 loc_network_unref(subnet
);
1401 loc_network_list_clear(enumerator
->subnets
);
1406 loc_network_unref(subnet
);
1410 // If this is not a subnet, we push it back onto the stack and break
1411 r
= loc_network_list_push(enumerator
->stack
, subnet
);
1413 loc_network_unref(subnet
);
1414 loc_network_list_clear(enumerator
->subnets
);
1419 loc_network_unref(subnet
);
1423 DEBUG(enumerator
->ctx
, "Found %zu subnet(s)\n",
1424 loc_network_list_size(enumerator
->subnets
));
1426 // We can abort here if the network has no subnets
1427 if (loc_network_list_empty(enumerator
->subnets
)) {
1428 loc_network_list_clear(enumerator
->subnets
);
1433 // If the network has any subnets, we will break it into smaller parts
1434 // without the subnets.
1435 struct loc_network_list
* excluded
= loc_network_exclude_list(*network
, enumerator
->subnets
);
1437 loc_network_list_clear(enumerator
->subnets
);
1441 // Merge subnets onto the stack
1442 r
= loc_network_list_merge(enumerator
->stack
, enumerator
->subnets
);
1444 loc_network_list_clear(enumerator
->subnets
);
1445 loc_network_list_unref(excluded
);
1450 // Push excluded list onto the stack
1451 r
= loc_network_list_merge(enumerator
->stack
, excluded
);
1453 loc_network_list_clear(enumerator
->subnets
);
1454 loc_network_list_unref(excluded
);
1459 loc_network_list_clear(enumerator
->subnets
);
1460 loc_network_list_unref(excluded
);
1462 // Drop the network and restart the whole process again to pick the next network
1463 loc_network_unref(*network
);
1465 return __loc_database_enumerator_next_network_flattened(enumerator
, network
);
1469 This function finds all bogons (i.e. gaps) between the input networks
1471 static int __loc_database_enumerator_next_bogon(
1472 struct loc_database_enumerator
* enumerator
, struct loc_network
** bogon
) {
1475 // Return top element from the stack
1477 *bogon
= loc_network_list_pop_first(enumerator
->stack
);
1487 struct loc_network
* network
= NULL
;
1488 struct in6_addr
* gap_start
= NULL
;
1489 struct in6_addr gap_end
= IN6ADDR_ANY_INIT
;
1492 r
= __loc_database_enumerator_next_network(enumerator
, &network
, 1);
1496 // We have read the last network
1500 const char* country_code
= loc_network_get_country_code(network
);
1503 Skip anything that does not have a country code
1505 Even if a network is part of the routing table, and the database provides
1506 an ASN, this does not mean that this is a legitimate announcement.
1508 if (country_code
&& !*country_code
) {
1509 loc_network_unref(network
);
1513 // Determine the network family
1514 int family
= loc_network_address_family(network
);
1518 gap_start
= &enumerator
->gap6_start
;
1522 gap_start
= &enumerator
->gap4_start
;
1526 ERROR(enumerator
->ctx
, "Unsupported network family %d\n", family
);
1531 const struct in6_addr
* first_address
= loc_network_get_first_address(network
);
1532 const struct in6_addr
* last_address
= loc_network_get_last_address(network
);
1534 // Skip if this network is a subnet of a former one
1535 if (loc_address_cmp(gap_start
, last_address
) >= 0) {
1536 loc_network_unref(network
);
1540 // Search where the gap could end
1541 gap_end
= *first_address
;
1542 loc_address_decrement(&gap_end
);
1545 if (loc_address_cmp(gap_start
, &gap_end
) <= 0) {
1546 r
= loc_network_list_summarize(enumerator
->ctx
,
1547 gap_start
, &gap_end
, &enumerator
->stack
);
1549 loc_network_unref(network
);
1554 // The gap now starts after this network
1555 *gap_start
= *last_address
;
1556 loc_address_increment(gap_start
);
1558 loc_network_unref(network
);
1560 // Try to return something
1561 *bogon
= loc_network_list_pop_first(enumerator
->stack
);
1570 if (!loc_address_all_zeroes(&enumerator
->gap6_start
)) {
1571 r
= loc_address_reset_last(&gap_end
, AF_INET6
);
1575 if (loc_address_cmp(&enumerator
->gap6_start
, &gap_end
) <= 0) {
1576 r
= loc_network_list_summarize(enumerator
->ctx
,
1577 &enumerator
->gap6_start
, &gap_end
, &enumerator
->stack
);
1583 loc_address_reset(&enumerator
->gap6_start
, AF_INET6
);
1586 if (!loc_address_all_zeroes(&enumerator
->gap4_start
)) {
1587 r
= loc_address_reset_last(&gap_end
, AF_INET
);
1591 if (loc_address_cmp(&enumerator
->gap4_start
, &gap_end
) <= 0) {
1592 r
= loc_network_list_summarize(enumerator
->ctx
,
1593 &enumerator
->gap4_start
, &gap_end
, &enumerator
->stack
);
1599 loc_address_reset(&enumerator
->gap4_start
, AF_INET
);
1602 // Try to return something
1603 *bogon
= loc_network_list_pop_first(enumerator
->stack
);
1608 LOC_EXPORT
int loc_database_enumerator_next_network(
1609 struct loc_database_enumerator
* enumerator
, struct loc_network
** network
) {
1610 switch (enumerator
->mode
) {
1611 case LOC_DB_ENUMERATE_NETWORKS
:
1613 if (enumerator
->flatten
)
1614 return __loc_database_enumerator_next_network_flattened(enumerator
, network
);
1616 return __loc_database_enumerator_next_network(enumerator
, network
, 1);
1618 case LOC_DB_ENUMERATE_BOGONS
:
1619 return __loc_database_enumerator_next_bogon(enumerator
, network
);
1626 LOC_EXPORT
int loc_database_enumerator_next_country(
1627 struct loc_database_enumerator
* enumerator
, struct loc_country
** country
) {
1630 // Do not do anything if not in country mode
1631 if (enumerator
->mode
!= LOC_DB_ENUMERATE_COUNTRIES
)
1634 struct loc_database
* db
= enumerator
->db
;
1636 while (enumerator
->country_index
< db
->country_objects
.count
) {
1637 // Fetch the next country
1638 int r
= loc_database_fetch_country(db
, country
, enumerator
->country_index
++);
1642 // We do not filter here, so it always is a match
1647 enumerator
->country_index
= 0;
1649 // We have searched through all of them