]> git.ipfire.org Git - people/ms/libloc.git/blame - src/database.c
database: Drop unused offset variable in objects
[people/ms/libloc.git] / src / database.c
CommitLineData
2601e83e
MT
1/*
2 libloc - A library to determine the location of someone on the Internet
3
4 Copyright (C) 2017 IPFire Development Team <info@ipfire.org>
5
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.
10
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.
15*/
16
2a30e4de 17#include <arpa/inet.h>
d3d8ede6 18#include <ctype.h>
2601e83e 19#include <errno.h>
10778041 20#include <netinet/in.h>
2601e83e
MT
21#include <stddef.h>
22#include <stdint.h>
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
c182393f 26#include <sys/mman.h>
2601e83e 27#include <sys/types.h>
96ea74a5 28#include <time.h>
3f35869a 29#include <unistd.h>
2601e83e 30
42f3ccd7
MT
31#ifdef HAVE_ENDIAN_H
32# include <endian.h>
33#endif
34
726f9984 35#include <openssl/err.h>
b1720435 36#include <openssl/evp.h>
726f9984 37#include <openssl/pem.h>
b1720435 38
c12a1385 39#include <libloc/libloc.h>
0b1fef38 40#include <libloc/address.h>
c12a1385
MT
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>
2601e83e 52
18638ad2 53struct loc_database_objects {
866ae435 54 char* data;
18638ad2
MT
55 size_t length;
56 size_t count;
57};
58
866ae435
MT
59struct loc_database_signature {
60 const char* data;
61 size_t length;
62};
63
2601e83e
MT
64struct loc_database {
65 struct loc_ctx* ctx;
66 int refcount;
67
b1720435
MT
68 FILE* f;
69
22c7b98b 70 enum loc_database_version version;
96ea74a5 71 time_t created_at;
2601e83e
MT
72 off_t vendor;
73 off_t description;
4bf49d00 74 off_t license;
2601e83e 75
5ce881d4 76 // Signatures
866ae435
MT
77 struct loc_database_signature signature1;
78 struct loc_database_signature signature2;
726f9984 79
3496a16c
MT
80 // Data mapped into memory
81 char* data;
82 off_t length;
83
18638ad2
MT
84 struct loc_stringpool* pool;
85
a5db3e49 86 // ASes in the database
18638ad2 87 struct loc_database_objects as_objects;
a5db3e49 88
f66b7b09 89 // Network tree
18638ad2 90 struct loc_database_objects network_node_objects;
f66b7b09 91
a735a563 92 // Networks
18638ad2 93 struct loc_database_objects network_objects;
a735a563 94
ec684c1a 95 // Countries
18638ad2 96 struct loc_database_objects country_objects;
2601e83e
MT
97};
98
e3f696c1
MT
99#define MAX_STACK_DEPTH 256
100
101struct loc_node_stack {
102 off_t offset;
103 int i; // Is this node 0 or 1?
104 int depth;
105};
106
7e13db74
MT
107struct loc_database_enumerator {
108 struct loc_ctx* ctx;
109 struct loc_database* db;
ccc7ab4e 110 enum loc_database_enumerator_mode mode;
7e13db74 111 int refcount;
d3d8ede6
MT
112
113 // Search string
114 char* string;
e646a8f3 115 struct loc_country_list* countries;
84a2f0c2 116 struct loc_as_list* asns;
9268db5a 117 enum loc_network_flags flags;
44e5ef71 118 int family;
d3d8ede6 119
681ff05c
MT
120 // Flatten output?
121 int flatten;
122
d3d8ede6
MT
123 // Index of the AS we are looking at
124 unsigned int as_index;
e3f696c1 125
fa9a3663
MT
126 // Index of the country we are looking at
127 unsigned int country_index;
128
e3f696c1
MT
129 // Network state
130 struct in6_addr network_address;
131 struct loc_node_stack network_stack[MAX_STACK_DEPTH];
132 int network_stack_depth;
133 unsigned int* networks_visited;
d87fd7a3 134
8c37d8a7 135 // For subnet search and bogons
d87fd7a3 136 struct loc_network_list* stack;
065b3496 137 struct loc_network_list* subnets;
9306c68d
MT
138
139 // For bogons
140 struct in6_addr gap6_start;
141 struct in6_addr gap4_start;
7e13db74
MT
142};
143
18638ad2 144/*
975f280f 145 Checks if it is safe to read the buffer of size length starting at p.
18638ad2 146*/
975f280f
MT
147#define loc_database_check_boundaries(db, p) \
148 __loc_database_check_boundaries(db, (const char*)p, sizeof(*p))
18638ad2 149
0e0be76c 150static inline int __loc_database_check_boundaries(struct loc_database* db,
975f280f
MT
151 const char* p, const size_t length) {
152 size_t offset = p - db->data;
18638ad2 153
975f280f
MT
154 // Return if everything is within the boundary
155 if (offset <= db->length - length)
156 return 1;
18638ad2 157
975f280f
MT
158 DEBUG(db->ctx, "Database read check failed at %p for %zu byte(s)\n", p, length);
159 DEBUG(db->ctx, " p = %p (offset = %jd, length = %zu)\n", p, offset, length);
160 DEBUG(db->ctx, " data = %p (length = %zu)\n", db->data, db->length);
161 DEBUG(db->ctx, " end = %p\n", db->data + db->length);
162 DEBUG(db->ctx, " overflow of %zu byte(s)\n", offset + length - db->length);
18638ad2 163
975f280f
MT
164 // Otherwise raise EFAULT
165 errno = EFAULT;
166 return 0;
167}
168
169/*
170 Returns a pointer to the n-th object
171*/
0e0be76c 172static inline char* loc_database_object(struct loc_database* db,
975f280f 173 const struct loc_database_objects* objects, const size_t length, const off_t n) {
975f280f
MT
174 // Calculate offset
175 const off_t offset = n * length;
176
177 // Return a pointer to where the object lies
178 char* object = objects->data + offset;
179
180 // Check if the object is part of the memory
181 if (!__loc_database_check_boundaries(db, object, length))
182 return NULL;
183
184 return object;
18638ad2
MT
185}
186
5acc1d5f
MT
187static int loc_database_version_supported(struct loc_database* db, uint8_t version) {
188 switch (version) {
189 // Supported versions
190 case LOC_DATABASE_VERSION_1:
191 return 1;
192
193 default:
194 ERROR(db->ctx, "Database version %d is not supported\n", version);
195 errno = ENOTSUP;
196 return 0;
197 }
198}
199
546c0ac0 200static int loc_database_check_magic(struct loc_database* db) {
2601e83e
MT
201 struct loc_database_magic magic;
202
203 // Read from file
b1720435 204 size_t bytes_read = fread(&magic, 1, sizeof(magic), db->f);
2601e83e
MT
205
206 // Check if we have been able to read enough data
207 if (bytes_read < sizeof(magic)) {
208 ERROR(db->ctx, "Could not read enough data to validate magic bytes\n");
209 DEBUG(db->ctx, "Read %zu bytes, but needed %zu\n", bytes_read, sizeof(magic));
808d6ac8 210 goto ERROR;
2601e83e
MT
211 }
212
213 // Compare magic bytes
546c0ac0 214 if (memcmp(magic.magic, LOC_DATABASE_MAGIC, sizeof(magic.magic)) == 0) {
2601e83e
MT
215 DEBUG(db->ctx, "Magic value matches\n");
216
5acc1d5f
MT
217 // Do we support this version?
218 if (!loc_database_version_supported(db, magic.version))
219 return 1;
220
2601e83e 221 // Parse version
22c7b98b 222 db->version = magic.version;
2601e83e
MT
223
224 return 0;
225 }
226
808d6ac8 227ERROR:
22c7b98b 228 ERROR(db->ctx, "Unrecognized file type\n");
808d6ac8 229 errno = ENOMSG;
2601e83e
MT
230
231 // Return an error
232 return 1;
233}
234
3496a16c
MT
235/*
236 Maps the entire database into memory
237*/
238static int loc_database_mmap(struct loc_database* db) {
e63d76be
MT
239 int r;
240
241 // Get file descriptor
3496a16c
MT
242 int fd = fileno(db->f);
243
244 // Determine the length of the database
245 db->length = lseek(fd, 0, SEEK_END);
246 if (db->length < 0) {
247 ERROR(db->ctx, "Could not determine the length of the database: %m\n");
248 return 1;
249 }
250
251 rewind(db->f);
252
253 // Map all data
254 db->data = mmap(NULL, db->length, PROT_READ, MAP_SHARED, fd, 0);
255 if (db->data == MAP_FAILED) {
256 ERROR(db->ctx, "Could not map the database: %m\n");
257 db->data = NULL;
258 return 1;
259 }
260
261 DEBUG(db->ctx, "Mapped database of %zu byte(s) at %p\n", db->length, db->data);
262
e63d76be
MT
263 // Tell the system that we expect to read data randomly
264 r = madvise(db->data, db->length, MADV_RANDOM);
265 if (r) {
266 ERROR(db->ctx, "madvise() failed: %m\n");
267 return r;
268 }
269
3496a16c
MT
270 return 0;
271}
272
18638ad2
MT
273/*
274 Maps arbitrary objects from the database into memory.
275*/
ff59db8e
MT
276static int loc_database_map_objects(struct loc_database* db, struct loc_database_objects* objects,
277 const size_t size, const off_t offset, const size_t length) {
18638ad2 278 // Store parameters
866ae435 279 objects->data = db->data + offset;
18638ad2
MT
280 objects->length = length;
281 objects->count = objects->length / size;
a5db3e49 282
866ae435
MT
283 return 0;
284}
a735a563 285
866ae435
MT
286static int loc_database_read_signature(struct loc_database* db,
287 struct loc_database_signature* signature, const char* data, const size_t length) {
288 // Check for a plausible signature length
289 if (length > LOC_SIGNATURE_MAX_LENGTH) {
290 ERROR(db->ctx, "Signature too long: %zu\n", length);
291 errno = EINVAL;
18638ad2 292 return 1;
a735a563
MT
293 }
294
866ae435
MT
295 // Store data & length
296 signature->data = data;
297 signature->length = length;
a735a563 298
866ae435
MT
299 DEBUG(db->ctx, "Read signature of %zu byte(s) at %p\n",
300 signature->length, signature->data);
ec684c1a 301
866ae435 302 hexdump(db->ctx, signature->data, signature->length);
ec684c1a 303
ec684c1a
MT
304 return 0;
305}
306
b904896a 307static int loc_database_read_header_v1(struct loc_database* db) {
866ae435
MT
308 const struct loc_database_header_v1* header =
309 (const struct loc_database_header_v1*)(db->data + LOC_DATABASE_MAGIC_SIZE);
5ce881d4 310 int r;
2601e83e 311
866ae435 312 DEBUG(db->ctx, "Reading header at %p\n", header);
2601e83e 313
866ae435
MT
314 // Check if we can read the header
315 if (!loc_database_check_boundaries(db, header)) {
2601e83e 316 ERROR(db->ctx, "Could not read enough data for header\n");
18638ad2 317 return 1;
2601e83e
MT
318 }
319
866ae435
MT
320 // Dump the entire header
321 hexdump(db->ctx, header, sizeof(*header));
2601e83e 322
866ae435
MT
323 // Copy over data
324 db->created_at = be64toh(header->created_at);
325 db->vendor = be32toh(header->vendor);
326 db->description = be32toh(header->description);
327 db->license = be32toh(header->license);
726f9984 328
5ce881d4 329 // Read signatures
866ae435
MT
330 r = loc_database_read_signature(db, &db->signature1,
331 header->signature1, be16toh(header->signature1_length));
332 if (r)
333 return r;
726f9984 334
866ae435
MT
335 r = loc_database_read_signature(db, &db->signature2,
336 header->signature2, be16toh(header->signature2_length));
337 if (r)
338 return r;
726f9984 339
975f280f
MT
340 const char* stringpool_start = db->data + be32toh(header->pool_offset);
341 size_t stringpool_length = be32toh(header->pool_length);
342
343 // Check if the stringpool is part of the mapped area
344 if (!__loc_database_check_boundaries(db, stringpool_start, stringpool_length))
345 return 1;
346
18638ad2 347 // Open the stringpool
975f280f 348 r = loc_stringpool_open(db->ctx, &db->pool, stringpool_start, stringpool_length);
2601e83e
MT
349 if (r)
350 return r;
351
18638ad2
MT
352 // Map AS objects
353 r = loc_database_map_objects(db, &db->as_objects,
354 sizeof(struct loc_database_as_v1),
866ae435
MT
355 be32toh(header->as_offset),
356 be32toh(header->as_length));
a5db3e49
MT
357 if (r)
358 return r;
359
18638ad2
MT
360 // Map Network Nodes
361 r = loc_database_map_objects(db, &db->network_node_objects,
362 sizeof(struct loc_database_network_node_v1),
866ae435
MT
363 be32toh(header->network_tree_offset),
364 be32toh(header->network_tree_length));
f66b7b09
MT
365 if (r)
366 return r;
367
18638ad2
MT
368 // Map Networks
369 r = loc_database_map_objects(db, &db->network_objects,
370 sizeof(struct loc_database_network_v1),
866ae435
MT
371 be32toh(header->network_data_offset),
372 be32toh(header->network_data_length));
a735a563
MT
373 if (r)
374 return r;
375
18638ad2
MT
376 // Map countries
377 r = loc_database_map_objects(db, &db->country_objects,
378 sizeof(struct loc_database_country_v1),
866ae435
MT
379 be32toh(header->countries_offset),
380 be32toh(header->countries_length));
ec684c1a
MT
381 if (r)
382 return r;
383
2601e83e
MT
384 return 0;
385}
386
b1720435 387static int loc_database_read_header(struct loc_database* db) {
22c7b98b
MT
388 DEBUG(db->ctx, "Database version is %u\n", db->version);
389
2601e83e 390 switch (db->version) {
22c7b98b 391 case LOC_DATABASE_VERSION_1:
b904896a 392 return loc_database_read_header_v1(db);
2601e83e
MT
393
394 default:
395 ERROR(db->ctx, "Incompatible database version: %u\n", db->version);
396 return 1;
397 }
398}
399
1642ccea
MT
400static int loc_database_clone_handle(struct loc_database* db, FILE* f) {
401 // Fetch the FD of the original handle
b1720435
MT
402 int fd = fileno(f);
403
404 // Clone file descriptor
405 fd = dup(fd);
406 if (!fd) {
407 ERROR(db->ctx, "Could not duplicate file descriptor\n");
1642ccea 408 return 1;
b1720435
MT
409 }
410
411 // Reopen the file so that we can keep our own file handle
412 db->f = fdopen(fd, "r");
413 if (!db->f) {
414 ERROR(db->ctx, "Could not re-open database file\n");
1642ccea 415 return 1;
b1720435
MT
416 }
417
418 // Rewind to the start of the file
419 rewind(db->f);
420
1642ccea
MT
421 return 0;
422}
423
424static int loc_database_open(struct loc_database* db, FILE* f) {
425 int r;
426
427 clock_t start = clock();
428
429 // Clone the file handle
430 r = loc_database_clone_handle(db, f);
431 if (r)
432 return r;
433
02879100 434 // Read magic bytes
546c0ac0 435 r = loc_database_check_magic(db);
02879100
MT
436 if (r)
437 return r;
438
3496a16c
MT
439 // Map the database into memory
440 r = loc_database_mmap(db);
441 if (r)
442 return r;
443
02879100 444 // Read the header
b1720435 445 r = loc_database_read_header(db);
02879100
MT
446 if (r)
447 return r;
448
449 clock_t end = clock();
450
e16c943b
MT
451 INFO(db->ctx, "Opened database in %.4fms\n",
452 (double)(end - start) / CLOCKS_PER_SEC * 1000);
02879100
MT
453
454 return 0;
455}
456
c182393f 457static void loc_database_free(struct loc_database* db) {
3496a16c
MT
458 int r;
459
c182393f 460 DEBUG(db->ctx, "Releasing database %p\n", db);
c34e76f1 461
3496a16c
MT
462 // Unmap the entire database
463 if (db->data) {
464 r = munmap(db->data, db->length);
465 if (r)
466 ERROR(db->ctx, "Could not unmap the database: %m\n");
467 }
468
18638ad2 469 // Free the stringpool
414d8958
MT
470 if (db->pool)
471 loc_stringpool_unref(db->pool);
c34e76f1 472
b1720435
MT
473 // Close database file
474 if (db->f)
475 fclose(db->f);
476
c182393f
MT
477 loc_unref(db->ctx);
478 free(db);
c34e76f1
MT
479}
480
50c0fbcd
MT
481LOC_EXPORT int loc_database_new(struct loc_ctx* ctx, struct loc_database** database, FILE* f) {
482 struct loc_database* db = NULL;
483 int r;
484
485 // Fail on invalid file handle
486 if (!f) {
487 errno = EINVAL;
488 return 1;
489 }
490
491 // Allocate the database object
492 db = calloc(1, sizeof(*db));
493 if (!db)
494 goto ERROR;
495
496 // Reference context
497 db->ctx = loc_ref(ctx);
498 db->refcount = 1;
499
500 DEBUG(db->ctx, "Database object allocated at %p\n", db);
501
502 // Try to open the database
1642ccea 503 r = loc_database_open(db, f);
50c0fbcd
MT
504 if (r)
505 goto ERROR;
506
507 *database = db;
508 return 0;
509
510ERROR:
511 if (db)
512 loc_database_free(db);
513
514 return r;
515}
516
517LOC_EXPORT struct loc_database* loc_database_ref(struct loc_database* db) {
518 db->refcount++;
519
520 return db;
521}
522
c182393f
MT
523LOC_EXPORT struct loc_database* loc_database_unref(struct loc_database* db) {
524 if (--db->refcount > 0)
525 return NULL;
78ace4ed 526
c182393f
MT
527 loc_database_free(db);
528 return NULL;
529}
78ace4ed 530
726f9984 531LOC_EXPORT int loc_database_verify(struct loc_database* db, FILE* f) {
98b2876e
MT
532 size_t bytes_read = 0;
533
726f9984 534 // Cannot do this when no signature is available
866ae435 535 if (!db->signature1.data && !db->signature2.data) {
726f9984
MT
536 DEBUG(db->ctx, "No signature available to verify\n");
537 return 1;
538 }
539
c81205a5
MT
540 // Start the stopwatch
541 clock_t start = clock();
542
726f9984
MT
543 // Load public key
544 EVP_PKEY* pkey = PEM_read_PUBKEY(f, NULL, NULL, NULL);
545 if (!pkey) {
6cd02f1d
MT
546 ERROR(db->ctx, "Could not parse public key: %s\n",
547 ERR_error_string(ERR_get_error(), NULL));
726f9984
MT
548
549 return -1;
550 }
551
b1720435
MT
552 int r = 0;
553
554 EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
555
b1720435 556 // Initialise hash function
e7f4b2ce
MT
557 r = EVP_DigestVerifyInit(mdctx, NULL, NULL, NULL, pkey);
558 if (r != 1) {
559 ERROR(db->ctx, "Error initializing signature validation: %s\n",
560 ERR_error_string(ERR_get_error(), NULL));
561 r = 1;
562
563 goto CLEANUP;
564 }
b1720435
MT
565
566 // Reset file to start
567 rewind(db->f);
568
569 // Read magic
570 struct loc_database_magic magic;
98b2876e
MT
571 bytes_read = fread(&magic, 1, sizeof(magic), db->f);
572 if (bytes_read < sizeof(magic)) {
573 ERROR(db->ctx, "Could not read header: %m\n");
574 r = 1;
575 goto CLEANUP;
576 }
b1720435 577
a0cff45d
MT
578 hexdump(db->ctx, &magic, sizeof(magic));
579
b1720435 580 // Feed magic into the hash
e7f4b2ce
MT
581 r = EVP_DigestVerifyUpdate(mdctx, &magic, sizeof(magic));
582 if (r != 1) {
583 ERROR(db->ctx, "%s\n", ERR_error_string(ERR_get_error(), NULL));
584 r = 1;
585
586 goto CLEANUP;
587 }
b1720435
MT
588
589 // Read the header
b904896a 590 struct loc_database_header_v1 header_v1;
b1720435
MT
591
592 switch (db->version) {
22c7b98b 593 case LOC_DATABASE_VERSION_1:
54f0649f
MT
594 bytes_read = fread(&header_v1, 1, sizeof(header_v1), db->f);
595 if (bytes_read < sizeof(header_v1)) {
596 ERROR(db->ctx, "Could not read header\n");
597 r = 1;
598
599 goto CLEANUP;
600 }
b1720435 601
5ce881d4
MT
602 // Clear signatures
603 memset(header_v1.signature1, '\0', sizeof(header_v1.signature1));
604 header_v1.signature1_length = 0;
605 memset(header_v1.signature2, '\0', sizeof(header_v1.signature2));
606 header_v1.signature2_length = 0;
b1720435 607
b904896a 608 hexdump(db->ctx, &header_v1, sizeof(header_v1));
a0cff45d 609
b1720435 610 // Feed header into the hash
b904896a 611 r = EVP_DigestVerifyUpdate(mdctx, &header_v1, sizeof(header_v1));
e7f4b2ce
MT
612 if (r != 1) {
613 ERROR(db->ctx, "%s\n", ERR_error_string(ERR_get_error(), NULL));
614 r = 1;
615
616 goto CLEANUP;
617 }
b1720435
MT
618 break;
619
620 default:
621 ERROR(db->ctx, "Cannot compute hash for database with format %d\n",
622 db->version);
623 r = -EINVAL;
624 goto CLEANUP;
625 }
626
726f9984
MT
627 // Walk through the file in chunks of 64kB
628 char buffer[64 * 1024];
b1720435
MT
629
630 while (!feof(db->f)) {
54f0649f 631 bytes_read = fread(buffer, 1, sizeof(buffer), db->f);
b1720435 632
a0cff45d
MT
633 hexdump(db->ctx, buffer, bytes_read);
634
e7f4b2ce
MT
635 r = EVP_DigestVerifyUpdate(mdctx, buffer, bytes_read);
636 if (r != 1) {
637 ERROR(db->ctx, "%s\n", ERR_error_string(ERR_get_error(), NULL));
638 r = 1;
639
640 goto CLEANUP;
641 }
b1720435
MT
642 }
643
5ce881d4 644 // Check first signature
866ae435
MT
645 if (db->signature1.data) {
646 hexdump(db->ctx, db->signature1.data, db->signature1.length);
726f9984 647
5ce881d4 648 r = EVP_DigestVerifyFinal(mdctx,
866ae435 649 (unsigned char*)db->signature1.data, db->signature1.length);
5ce881d4
MT
650
651 if (r == 0) {
652 DEBUG(db->ctx, "The first signature is invalid\n");
653 r = 1;
654 } else if (r == 1) {
655 DEBUG(db->ctx, "The first signature is valid\n");
656 r = 0;
657 } else {
658 ERROR(db->ctx, "Error verifying the first signature: %s\n",
659 ERR_error_string(ERR_get_error(), NULL));
660 r = -1;
661 }
b1720435
MT
662 }
663
5ce881d4 664 // Check second signature only when the first one was invalid
866ae435
MT
665 if (r && db->signature2.data) {
666 hexdump(db->ctx, db->signature2.data, db->signature2.length);
5ce881d4
MT
667
668 r = EVP_DigestVerifyFinal(mdctx,
866ae435 669 (unsigned char*)db->signature2.data, db->signature2.length);
5ce881d4
MT
670
671 if (r == 0) {
672 DEBUG(db->ctx, "The second signature is invalid\n");
673 r = 1;
674 } else if (r == 1) {
675 DEBUG(db->ctx, "The second signature is valid\n");
676 r = 0;
677 } else {
678 ERROR(db->ctx, "Error verifying the second signature: %s\n",
679 ERR_error_string(ERR_get_error(), NULL));
680 r = -1;
681 }
682 }
257626f5 683
c81205a5 684 clock_t end = clock();
6661692f 685 INFO(db->ctx, "Signature checked in %.4fms\n",
c81205a5
MT
686 (double)(end - start) / CLOCKS_PER_SEC * 1000);
687
b1720435
MT
688CLEANUP:
689 // Cleanup
690 EVP_MD_CTX_free(mdctx);
726f9984 691 EVP_PKEY_free(pkey);
b1720435
MT
692
693 return r;
694}
695
c182393f
MT
696LOC_EXPORT time_t loc_database_created_at(struct loc_database* db) {
697 return db->created_at;
698}
78ace4ed 699
c182393f
MT
700LOC_EXPORT const char* loc_database_get_vendor(struct loc_database* db) {
701 return loc_stringpool_get(db->pool, db->vendor);
702}
78ace4ed 703
c182393f
MT
704LOC_EXPORT const char* loc_database_get_description(struct loc_database* db) {
705 return loc_stringpool_get(db->pool, db->description);
706}
78ace4ed 707
4bf49d00
MT
708LOC_EXPORT const char* loc_database_get_license(struct loc_database* db) {
709 return loc_stringpool_get(db->pool, db->license);
710}
711
c182393f 712LOC_EXPORT size_t loc_database_count_as(struct loc_database* db) {
18638ad2 713 return db->as_objects.count;
78ace4ed
MT
714}
715
c182393f
MT
716// Returns the AS at position pos
717static int loc_database_fetch_as(struct loc_database* db, struct loc_as** as, off_t pos) {
975f280f 718 struct loc_database_as_v1* as_v1 = NULL;
18638ad2
MT
719 int r;
720
721 if ((size_t)pos >= db->as_objects.count) {
722 errno = ERANGE;
723 return 1;
724 }
2601e83e 725
5c57de03 726 DEBUG(db->ctx, "Fetching AS at position %jd\n", (intmax_t)pos);
2601e83e 727
c182393f 728 switch (db->version) {
22c7b98b 729 case LOC_DATABASE_VERSION_1:
975f280f
MT
730 // Find the object
731 as_v1 = (struct loc_database_as_v1*)loc_database_object(db,
732 &db->as_objects, sizeof(*as_v1), pos);
733 if (!as_v1)
18638ad2
MT
734 return 1;
735
975f280f 736 r = loc_as_new_from_database_v1(db->ctx, db->pool, as, as_v1);
c182393f 737 break;
2601e83e 738
c182393f 739 default:
18638ad2
MT
740 errno = ENOTSUP;
741 return 1;
c182393f 742 }
2601e83e 743
18638ad2 744 if (r == 0)
c182393f 745 DEBUG(db->ctx, "Got AS%u\n", loc_as_get_number(*as));
2601e83e 746
c182393f
MT
747 return r;
748}
c34e76f1 749
c182393f
MT
750// Performs a binary search to find the AS in the list
751LOC_EXPORT int loc_database_get_as(struct loc_database* db, struct loc_as** as, uint32_t number) {
752 off_t lo = 0;
18638ad2 753 off_t hi = db->as_objects.count - 1;
c34e76f1 754
6661692f 755#ifdef ENABLE_DEBUG
8f3e2a06
MT
756 // Save start time
757 clock_t start = clock();
6661692f 758#endif
8f3e2a06 759
c182393f
MT
760 while (lo <= hi) {
761 off_t i = (lo + hi) / 2;
8f5b676a 762
c182393f
MT
763 // Fetch AS in the middle between lo and hi
764 int r = loc_database_fetch_as(db, as, i);
765 if (r)
766 return r;
a5db3e49 767
c182393f
MT
768 // Check if this is a match
769 uint32_t as_number = loc_as_get_number(*as);
8f3e2a06 770 if (as_number == number) {
6661692f 771#ifdef ENABLE_DEBUG
8f3e2a06
MT
772 clock_t end = clock();
773
774 // Log how fast this has been
e16c943b
MT
775 DEBUG(db->ctx, "Found AS%u in %.4fms\n", as_number,
776 (double)(end - start) / CLOCKS_PER_SEC * 1000);
6661692f 777#endif
8f3e2a06 778
c182393f 779 return 0;
8f3e2a06 780 }
c182393f
MT
781
782 // If it wasn't, we release the AS and
783 // adjust our search pointers
784 loc_as_unref(*as);
785
786 if (as_number < number) {
787 lo = i + 1;
788 } else
789 hi = i - 1;
790 }
2601e83e 791
c182393f
MT
792 // Nothing found
793 *as = NULL;
2601e83e 794
8f3e2a06 795 return 1;
2601e83e 796}
10778041
MT
797
798// Returns the network at position pos
39a55353
MT
799static int loc_database_fetch_network(struct loc_database* db, struct loc_network** network,
800 struct in6_addr* address, unsigned int prefix, off_t pos) {
975f280f 801 struct loc_database_network_v1* network_v1 = NULL;
18638ad2
MT
802 int r;
803
804 if ((size_t)pos >= db->network_objects.count) {
9b9e5faf 805 DEBUG(db->ctx, "Network ID out of range: %jd/%jd\n",
18638ad2
MT
806 (intmax_t)pos, (intmax_t)db->network_objects.count);
807 errno = ERANGE;
808 return 1;
9b9e5faf
MT
809 }
810
5c57de03 811 DEBUG(db->ctx, "Fetching network at position %jd\n", (intmax_t)pos);
10778041 812
10778041 813 switch (db->version) {
22c7b98b 814 case LOC_DATABASE_VERSION_1:
18638ad2 815 // Read the object
975f280f
MT
816 network_v1 = (struct loc_database_network_v1*)loc_database_object(db,
817 &db->network_objects, sizeof(*network_v1), pos);
818 if (!network_v1)
18638ad2
MT
819 return 1;
820
975f280f 821 r = loc_network_new_from_database_v1(db->ctx, network, address, prefix, network_v1);
10778041
MT
822 break;
823
824 default:
18638ad2
MT
825 errno = ENOTSUP;
826 return 1;
10778041
MT
827 }
828
0a0a289a
MT
829 if (r == 0)
830 DEBUG(db->ctx, "Got network %s\n", loc_network_str(*network));
10778041
MT
831
832 return r;
833}
2a30e4de 834
b904896a 835static int __loc_database_node_is_leaf(const struct loc_database_network_node_v1* node) {
39a55353 836 return (node->network != htobe32(0xffffffff));
025ef489
MT
837}
838
839static int __loc_database_lookup_handle_leaf(struct loc_database* db, const struct in6_addr* address,
39a55353 840 struct loc_network** network, struct in6_addr* network_address, unsigned int prefix,
b904896a 841 const struct loc_database_network_node_v1* node) {
39a55353
MT
842 off_t network_index = be32toh(node->network);
843
18638ad2 844 DEBUG(db->ctx, "Handling leaf node at %jd\n", (intmax_t)network_index);
2a30e4de
MT
845
846 // Fetch the network
18638ad2 847 int r = loc_database_fetch_network(db, network, network_address, prefix, network_index);
e85e2b0b 848 if (r) {
18638ad2
MT
849 ERROR(db->ctx, "Could not fetch network %jd from database: %m\n",
850 (intmax_t)network_index);
2a30e4de 851 return r;
e85e2b0b 852 }
39a55353 853
2a30e4de 854 // Check if the given IP address is inside the network
0258d3c9 855 if (!loc_network_matches_address(*network, address)) {
2a30e4de
MT
856 DEBUG(db->ctx, "Searched address is not part of the network\n");
857
858 loc_network_unref(*network);
859 *network = NULL;
860 return 1;
861 }
862
863 // A network was found and the IP address matches
864 return 0;
865}
866
2a30e4de
MT
867// Searches for an exact match along the path
868static int __loc_database_lookup(struct loc_database* db, const struct in6_addr* address,
869 struct loc_network** network, struct in6_addr* network_address,
18638ad2 870 off_t node_index, unsigned int level) {
975f280f 871 struct loc_database_network_node_v1* node_v1 = NULL;
18638ad2 872
025ef489 873 int r;
18638ad2
MT
874
875 // Fetch the next node
975f280f
MT
876 node_v1 = (struct loc_database_network_node_v1*)loc_database_object(db,
877 &db->network_node_objects, sizeof(*node_v1), node_index);
878 if (!node_v1)
18638ad2 879 return 1;
2a30e4de
MT
880
881 // Follow the path
d698ca09
MT
882 int bit = loc_address_get_bit(address, level);
883 loc_address_set_bit(network_address, level, bit);
2a30e4de
MT
884
885 if (bit == 0)
975f280f 886 node_index = be32toh(node_v1->zero);
2a30e4de 887 else
975f280f 888 node_index = be32toh(node_v1->one);
2a30e4de 889
9086d2b1
MT
890 // If the node index is zero, the tree ends here
891 // and we cannot descend any further
892 if (node_index > 0) {
893 // Check boundaries
18638ad2
MT
894 if ((size_t)node_index >= db->network_node_objects.count) {
895 errno = ERANGE;
896 return 1;
897 }
2a30e4de 898
9086d2b1 899 // Move on to the next node
18638ad2 900 r = __loc_database_lookup(db, address, network, network_address, node_index, level + 1);
2a30e4de 901
9086d2b1
MT
902 // End here if a result was found
903 if (r == 0)
904 return r;
2a30e4de 905
9086d2b1
MT
906 // Raise any errors
907 else if (r < 0)
908 return r;
ec1d9681
MT
909
910 DEBUG(db->ctx, "No match found below level %u\n", level);
911 } else {
912 DEBUG(db->ctx, "Tree ended at level %u\n", level);
9086d2b1 913 }
2a30e4de 914
9086d2b1 915 // If this node has a leaf, we will check if it matches
975f280f
MT
916 if (__loc_database_node_is_leaf(node_v1)) {
917 r = __loc_database_lookup_handle_leaf(db, address, network, network_address, level, node_v1);
9086d2b1
MT
918 if (r <= 0)
919 return r;
920 }
2a30e4de 921
ec1d9681 922 return 1;
2a30e4de
MT
923}
924
925LOC_EXPORT int loc_database_lookup(struct loc_database* db,
a178efea 926 const struct in6_addr* address, struct loc_network** network) {
2a30e4de
MT
927 struct in6_addr network_address;
928 memset(&network_address, 0, sizeof(network_address));
929
930 *network = NULL;
931
6661692f 932#ifdef ENABLE_DEBUG
2a30e4de
MT
933 // Save start time
934 clock_t start = clock();
6661692f 935#endif
2a30e4de 936
18638ad2 937 int r = __loc_database_lookup(db, address, network, &network_address, 0, 0);
2a30e4de 938
6661692f 939#ifdef ENABLE_DEBUG
2a30e4de
MT
940 clock_t end = clock();
941
942 // Log how fast this has been
e16c943b
MT
943 DEBUG(db->ctx, "Executed network search in %.4fms\n",
944 (double)(end - start) / CLOCKS_PER_SEC * 1000);
6661692f 945#endif
2a30e4de
MT
946
947 return r;
948}
949
950LOC_EXPORT int loc_database_lookup_from_string(struct loc_database* db,
951 const char* string, struct loc_network** network) {
952 struct in6_addr address;
953
95b6a8e4 954 int r = loc_address_parse(&address, NULL, string);
2a30e4de
MT
955 if (r)
956 return r;
957
958 return loc_database_lookup(db, &address, network);
959}
7e13db74 960
ec684c1a
MT
961// Returns the country at position pos
962static int loc_database_fetch_country(struct loc_database* db,
963 struct loc_country** country, off_t pos) {
975f280f 964 struct loc_database_country_v1* country_v1 = NULL;
18638ad2
MT
965 int r;
966
967 // Check if the country is within range
968 if ((size_t)pos >= db->country_objects.count) {
969 errno = ERANGE;
970 return 1;
971 }
ec684c1a 972
2e2325a9 973 DEBUG(db->ctx, "Fetching country at position %jd\n", (intmax_t)pos);
ec684c1a 974
ec684c1a 975 switch (db->version) {
22c7b98b 976 case LOC_DATABASE_VERSION_1:
18638ad2 977 // Read the object
975f280f
MT
978 country_v1 = (struct loc_database_country_v1*)loc_database_object(db,
979 &db->country_objects, sizeof(*country_v1), pos);
980 if (!country_v1)
18638ad2
MT
981 return 1;
982
975f280f 983 r = loc_country_new_from_database_v1(db->ctx, db->pool, country, country_v1);
ec684c1a
MT
984 break;
985
986 default:
18638ad2
MT
987 errno = ENOTSUP;
988 return 1;
ec684c1a
MT
989 }
990
18638ad2 991 if (r == 0)
ec684c1a 992 DEBUG(db->ctx, "Got country %s\n", loc_country_get_code(*country));
ec684c1a
MT
993
994 return r;
995}
996
997// Performs a binary search to find the country in the list
998LOC_EXPORT int loc_database_get_country(struct loc_database* db,
999 struct loc_country** country, const char* code) {
1000 off_t lo = 0;
18638ad2 1001 off_t hi = db->country_objects.count - 1;
ec684c1a 1002
8fcb5bc7
MT
1003 // Check if the country code is valid
1004 if (!loc_country_code_is_valid(code)) {
1005 errno = EINVAL;
1006 return 1;
1007 }
1008
6661692f 1009#ifdef ENABLE_DEBUG
ec684c1a
MT
1010 // Save start time
1011 clock_t start = clock();
6661692f 1012#endif
ec684c1a
MT
1013
1014 while (lo <= hi) {
1015 off_t i = (lo + hi) / 2;
1016
1017 // Fetch country in the middle between lo and hi
1018 int r = loc_database_fetch_country(db, country, i);
1019 if (r)
1020 return r;
1021
1022 // Check if this is a match
1023 const char* cc = loc_country_get_code(*country);
1024 int result = strcmp(code, cc);
1025
1026 if (result == 0) {
6661692f 1027#ifdef ENABLE_DEBUG
ec684c1a
MT
1028 clock_t end = clock();
1029
1030 // Log how fast this has been
1031 DEBUG(db->ctx, "Found country %s in %.4fms\n", cc,
1032 (double)(end - start) / CLOCKS_PER_SEC * 1000);
6661692f 1033#endif
ec684c1a
MT
1034
1035 return 0;
1036 }
1037
1038 // If it wasn't, we release the country and
1039 // adjust our search pointers
1040 loc_country_unref(*country);
1041
191830da 1042 if (result > 0) {
ec684c1a
MT
1043 lo = i + 1;
1044 } else
1045 hi = i - 1;
1046 }
1047
1048 // Nothing found
1049 *country = NULL;
1050
8fcb5bc7 1051 return 0;
ec684c1a
MT
1052}
1053
7e13db74
MT
1054// Enumerator
1055
d87fd7a3
MT
1056static void loc_database_enumerator_free(struct loc_database_enumerator* enumerator) {
1057 DEBUG(enumerator->ctx, "Releasing database enumerator %p\n", enumerator);
1058
1059 // Release all references
1060 loc_database_unref(enumerator->db);
1061 loc_unref(enumerator->ctx);
1062
1063 if (enumerator->string)
1064 free(enumerator->string);
1065
5470d06c
MT
1066 if (enumerator->countries)
1067 loc_country_list_unref(enumerator->countries);
1068
1069 if (enumerator->asns)
1070 loc_as_list_unref(enumerator->asns);
1071
d87fd7a3 1072 // Free network search
18638ad2
MT
1073 if (enumerator->networks_visited)
1074 free(enumerator->networks_visited);
d87fd7a3 1075
8c37d8a7 1076 // Free subnet/bogons stack
d87fd7a3
MT
1077 if (enumerator->stack)
1078 loc_network_list_unref(enumerator->stack);
1079
065b3496
MT
1080 if (enumerator->subnets)
1081 loc_network_list_unref(enumerator->subnets);
1082
d87fd7a3
MT
1083 free(enumerator);
1084}
1085
ccc7ab4e 1086LOC_EXPORT int loc_database_enumerator_new(struct loc_database_enumerator** enumerator,
681ff05c 1087 struct loc_database* db, enum loc_database_enumerator_mode mode, int flags) {
18638ad2
MT
1088 int r;
1089
7e13db74 1090 struct loc_database_enumerator* e = calloc(1, sizeof(*e));
18638ad2 1091 if (!e) {
7e13db74 1092 return -ENOMEM;
18638ad2 1093 }
7e13db74
MT
1094
1095 // Reference context
1096 e->ctx = loc_ref(db->ctx);
1097 e->db = loc_database_ref(db);
ccc7ab4e 1098 e->mode = mode;
7e13db74
MT
1099 e->refcount = 1;
1100
681ff05c
MT
1101 // Flatten output?
1102 e->flatten = (flags & LOC_DB_ENUMERATOR_FLAGS_FLATTEN);
1103
e3f696c1 1104 // Initialise graph search
e3f696c1 1105 e->network_stack_depth = 1;
18638ad2
MT
1106 e->networks_visited = calloc(db->network_node_objects.count, sizeof(*e->networks_visited));
1107 printf("COUNT = %zu, P = %p\n", db->network_node_objects.count, e->networks_visited);
1108 if (!e->networks_visited) {
1109 ERROR(db->ctx, "Could not allocated visited networks: %m\n");
1110 r = 1;
1111 goto ERROR;
1112 }
e3f696c1 1113
d87fd7a3 1114 // Allocate stack
18638ad2
MT
1115 r = loc_network_list_new(e->ctx, &e->stack);
1116 if (r)
1117 goto ERROR;
d87fd7a3 1118
9306c68d
MT
1119 // Initialize bogon search
1120 loc_address_reset(&e->gap6_start, AF_INET6);
1121 loc_address_reset(&e->gap4_start, AF_INET);
1122
7e13db74
MT
1123 DEBUG(e->ctx, "Database enumerator object allocated at %p\n", e);
1124
1125 *enumerator = e;
1126 return 0;
18638ad2
MT
1127
1128ERROR:
1129 if (e)
1130 loc_database_enumerator_free(e);
1131
1132 return r;
7e13db74
MT
1133}
1134
1135LOC_EXPORT struct loc_database_enumerator* loc_database_enumerator_ref(struct loc_database_enumerator* enumerator) {
1136 enumerator->refcount++;
1137
1138 return enumerator;
1139}
1140
7e13db74
MT
1141LOC_EXPORT struct loc_database_enumerator* loc_database_enumerator_unref(struct loc_database_enumerator* enumerator) {
1142 if (!enumerator)
1143 return NULL;
1144
1145 if (--enumerator->refcount > 0)
1146 return enumerator;
1147
1148 loc_database_enumerator_free(enumerator);
1149 return NULL;
1150}
d3d8ede6
MT
1151
1152LOC_EXPORT int loc_database_enumerator_set_string(struct loc_database_enumerator* enumerator, const char* string) {
1153 enumerator->string = strdup(string);
1154
1155 // Make the string lowercase
1156 for (char *p = enumerator->string; *p; p++)
1157 *p = tolower(*p);
1158
1159 return 0;
1160}
1161
e646a8f3
MT
1162LOC_EXPORT struct loc_country_list* loc_database_enumerator_get_countries(
1163 struct loc_database_enumerator* enumerator) {
1164 if (!enumerator->countries)
1165 return NULL;
35bb3a32 1166
e646a8f3
MT
1167 return loc_country_list_ref(enumerator->countries);
1168}
4ef1761f 1169
e646a8f3
MT
1170LOC_EXPORT int loc_database_enumerator_set_countries(
1171 struct loc_database_enumerator* enumerator, struct loc_country_list* countries) {
1172 if (enumerator->countries)
1173 loc_country_list_unref(enumerator->countries);
57146963 1174
e646a8f3 1175 enumerator->countries = loc_country_list_ref(countries);
35bb3a32
MT
1176
1177 return 0;
1178}
1179
84a2f0c2
MT
1180LOC_EXPORT struct loc_as_list* loc_database_enumerator_get_asns(
1181 struct loc_database_enumerator* enumerator) {
1182 if (!enumerator->asns)
1183 return NULL;
1184
1185 return loc_as_list_ref(enumerator->asns);
1186}
1187
1188LOC_EXPORT int loc_database_enumerator_set_asns(
1189 struct loc_database_enumerator* enumerator, struct loc_as_list* asns) {
1190 if (enumerator->asns)
1191 loc_as_list_unref(enumerator->asns);
1192
1193 enumerator->asns = loc_as_list_ref(asns);
82910b95
MT
1194
1195 return 0;
1196}
1197
9268db5a
MT
1198LOC_EXPORT int loc_database_enumerator_set_flag(
1199 struct loc_database_enumerator* enumerator, enum loc_network_flags flag) {
1200 enumerator->flags |= flag;
1201
1202 return 0;
1203}
1204
44e5ef71
MT
1205LOC_EXPORT int loc_database_enumerator_set_family(
1206 struct loc_database_enumerator* enumerator, int family) {
1207 enumerator->family = family;
1208
1209 return 0;
1210}
1211
15f79e2d
MT
1212LOC_EXPORT int loc_database_enumerator_next_as(
1213 struct loc_database_enumerator* enumerator, struct loc_as** as) {
1214 *as = NULL;
1215
ccc7ab4e
MT
1216 // Do not do anything if not in AS mode
1217 if (enumerator->mode != LOC_DB_ENUMERATE_ASES)
15f79e2d 1218 return 0;
ccc7ab4e 1219
d3d8ede6 1220 struct loc_database* db = enumerator->db;
d3d8ede6 1221
18638ad2 1222 while (enumerator->as_index < db->as_objects.count) {
d3d8ede6 1223 // Fetch the next AS
15f79e2d 1224 int r = loc_database_fetch_as(db, as, enumerator->as_index++);
d3d8ede6 1225 if (r)
15f79e2d 1226 return r;
d3d8ede6 1227
15f79e2d 1228 r = loc_as_match_string(*as, enumerator->string);
273948cf 1229 if (r == 1) {
d3d8ede6 1230 DEBUG(enumerator->ctx, "AS%d (%s) matches %s\n",
15f79e2d 1231 loc_as_get_number(*as), loc_as_get_name(*as), enumerator->string);
d3d8ede6 1232
15f79e2d 1233 return 0;
d3d8ede6
MT
1234 }
1235
1236 // No match
15f79e2d 1237 loc_as_unref(*as);
74f218f0 1238 *as = NULL;
d3d8ede6
MT
1239 }
1240
1241 // Reset the index
1242 enumerator->as_index = 0;
1243
1244 // We have searched through all of them
15f79e2d 1245 return 0;
d3d8ede6 1246}
e3f696c1
MT
1247
1248static int loc_database_enumerator_stack_push_node(
1249 struct loc_database_enumerator* e, off_t offset, int i, int depth) {
1250 // Do not add empty nodes
1251 if (!offset)
1252 return 0;
1253
1254 // Check if there is any space left on the stack
1255 if (e->network_stack_depth >= MAX_STACK_DEPTH) {
1256 ERROR(e->ctx, "Maximum stack size reached: %d\n", e->network_stack_depth);
18638ad2
MT
1257 return 1;
1258 }
1259
1260 // Check if the node is in range
1261 if (offset >= (off_t)e->db->network_node_objects.count) {
1262 ERROR(e->ctx, "Trying to add invalid node with offset %jd/%zu\n",
1263 offset, e->db->network_node_objects.count);
1264 errno = ERANGE;
1265 return 1;
e3f696c1
MT
1266 }
1267
1268 // Increase stack size
1269 int s = ++e->network_stack_depth;
1270
2e2325a9 1271 DEBUG(e->ctx, "Added node %jd to stack (%d)\n", (intmax_t)offset, depth);
e3f696c1
MT
1272
1273 e->network_stack[s].offset = offset;
1274 e->network_stack[s].i = i;
1275 e->network_stack[s].depth = depth;
1276
1277 return 0;
1278}
1279
964633d9 1280static int loc_database_enumerator_match_network(
69248038 1281 struct loc_database_enumerator* enumerator, struct loc_network* network) {
964633d9 1282 // If family is set, it must match
e0e96878
MT
1283 if (enumerator->family && loc_network_address_family(network) != enumerator->family) {
1284 DEBUG(enumerator->ctx, "Filtered network %p because of family not matching\n", network);
964633d9 1285 return 0;
e0e96878 1286 }
69248038 1287
098d871b
MT
1288 // Match if no filter criteria is configured
1289 if (!enumerator->countries && !enumerator->asns && !enumerator->flags)
1290 return 1;
1291
964633d9 1292 // Check if the country code matches
e0e96878
MT
1293 if (enumerator->countries && !loc_country_list_empty(enumerator->countries)) {
1294 const char* country_code = loc_network_get_country_code(network);
50120b99 1295
964633d9
MT
1296 if (loc_country_list_contains_code(enumerator->countries, country_code)) {
1297 DEBUG(enumerator->ctx, "Matched network %p because of its country code\n", network);
e0e96878 1298 return 1;
50120b99
MT
1299 }
1300 }
69248038 1301
964633d9 1302 // Check if the ASN matches
e0e96878
MT
1303 if (enumerator->asns && !loc_as_list_empty(enumerator->asns)) {
1304 uint32_t asn = loc_network_get_asn(network);
c1a36c94 1305
964633d9
MT
1306 if (loc_as_list_contains_number(enumerator->asns, asn)) {
1307 DEBUG(enumerator->ctx, "Matched network %p because of its ASN\n", network);
e0e96878 1308 return 1;
c1a36c94
MT
1309 }
1310 }
69248038 1311
964633d9
MT
1312 // Check if flags match
1313 if (enumerator->flags && loc_network_has_flag(network, enumerator->flags)) {
1314 DEBUG(enumerator->ctx, "Matched network %p because of its flags\n", network);
69248038 1315 return 1;
e0e96878 1316 }
69248038 1317
964633d9 1318 // Not a match
69248038
MT
1319 return 0;
1320}
1321
d87fd7a3
MT
1322static int __loc_database_enumerator_next_network(
1323 struct loc_database_enumerator* enumerator, struct loc_network** network, int filter) {
1324 // Return top element from the stack
2113e71b 1325 while (1) {
04cbd2bf 1326 *network = loc_network_list_pop_first(enumerator->stack);
2113e71b
MT
1327
1328 // Stack is empty
1329 if (!*network)
1330 break;
1331
964633d9
MT
1332 // Return everything if filter isn't enabled, or only return matches
1333 if (!filter || loc_database_enumerator_match_network(enumerator, *network))
1334 return 0;
2113e71b 1335
964633d9
MT
1336 // Throw away anything that doesn't match
1337 loc_network_unref(*network);
1338 *network = NULL;
2113e71b 1339 }
15f79e2d 1340
15f79e2d
MT
1341 DEBUG(enumerator->ctx, "Called with a stack of %u nodes\n",
1342 enumerator->network_stack_depth);
e3f696c1
MT
1343
1344 // Perform DFS
15f79e2d
MT
1345 while (enumerator->network_stack_depth > 0) {
1346 DEBUG(enumerator->ctx, "Stack depth: %u\n", enumerator->network_stack_depth);
e3f696c1
MT
1347
1348 // Get object from top of the stack
15f79e2d 1349 struct loc_node_stack* node = &enumerator->network_stack[enumerator->network_stack_depth];
e3f696c1 1350
18638ad2
MT
1351 DEBUG(enumerator->ctx, " Got node: %jd\n", node->offset);
1352
e3f696c1 1353 // Remove the node from the stack if we have already visited it
15f79e2d
MT
1354 if (enumerator->networks_visited[node->offset]) {
1355 enumerator->network_stack_depth--;
e3f696c1
MT
1356 continue;
1357 }
1358
74fb733a 1359 // Mark the bits on the path correctly
d698ca09 1360 loc_address_set_bit(&enumerator->network_address,
e3f696c1
MT
1361 (node->depth > 0) ? node->depth - 1 : 0, node->i);
1362
2e2325a9 1363 DEBUG(enumerator->ctx, "Looking at node %jd\n", (intmax_t)node->offset);
15f79e2d 1364 enumerator->networks_visited[node->offset]++;
e3f696c1
MT
1365
1366 // Pop node from top of the stack
975f280f
MT
1367 struct loc_database_network_node_v1* n =
1368 (struct loc_database_network_node_v1*)loc_database_object(enumerator->db,
1369 &enumerator->db->network_node_objects, sizeof(*n), node->offset);
18638ad2
MT
1370 if (!n)
1371 return 1;
e3f696c1
MT
1372
1373 // Add edges to stack
d87fd7a3 1374 int r = loc_database_enumerator_stack_push_node(enumerator,
e3f696c1 1375 be32toh(n->one), 1, node->depth + 1);
e3f696c1
MT
1376 if (r)
1377 return r;
1378
15f79e2d 1379 r = loc_database_enumerator_stack_push_node(enumerator,
e3f696c1 1380 be32toh(n->zero), 0, node->depth + 1);
e3f696c1
MT
1381 if (r)
1382 return r;
1383
1384 // Check if this node is a leaf and has a network object
1385 if (__loc_database_node_is_leaf(n)) {
1386 off_t network_index = be32toh(n->network);
1387
2e2325a9 1388 DEBUG(enumerator->ctx, "Node has a network at %jd\n", (intmax_t)network_index);
e3f696c1
MT
1389
1390 // Fetch the network object
15f79e2d
MT
1391 r = loc_database_fetch_network(enumerator->db, network,
1392 &enumerator->network_address, node->depth, network_index);
e3f696c1
MT
1393
1394 // Break on any errors
1395 if (r)
1396 return r;
1397
964633d9
MT
1398 // Return all networks when the filter is disabled, or check for match
1399 if (!filter || loc_database_enumerator_match_network(enumerator, *network))
d87fd7a3
MT
1400 return 0;
1401
964633d9
MT
1402 // Does not seem to be a match, so we cleanup and move on
1403 loc_network_unref(*network);
1404 *network = NULL;
e3f696c1
MT
1405 }
1406 }
1407
1408 // Reached the end of the search
d87fd7a3
MT
1409 return 0;
1410}
fe483cdc 1411
d87fd7a3
MT
1412static int __loc_database_enumerator_next_network_flattened(
1413 struct loc_database_enumerator* enumerator, struct loc_network** network) {
1414 // Fetch the next network
1415 int r = __loc_database_enumerator_next_network(enumerator, network, 1);
1416 if (r)
1417 return r;
e3f696c1 1418
d87fd7a3
MT
1419 // End if we could not read another network
1420 if (!*network)
1421 return 0;
1422
1423 struct loc_network* subnet = NULL;
d87fd7a3
MT
1424
1425 // Create a list with all subnets
065b3496
MT
1426 if (!enumerator->subnets) {
1427 r = loc_network_list_new(enumerator->ctx, &enumerator->subnets);
1428 if (r)
1429 return r;
1430 }
d87fd7a3
MT
1431
1432 // Search all subnets from the database
1433 while (1) {
1434 // Fetch the next network in line
1435 r = __loc_database_enumerator_next_network(enumerator, &subnet, 0);
ed0f53df
MT
1436 if (r) {
1437 loc_network_unref(subnet);
065b3496 1438 loc_network_list_clear(enumerator->subnets);
ed0f53df
MT
1439
1440 return r;
1441 }
d87fd7a3
MT
1442
1443 // End if we did not receive another subnet
1444 if (!subnet)
1445 break;
1446
1447 // Collect all subnets in a list
1448 if (loc_network_is_subnet(*network, subnet)) {
065b3496 1449 r = loc_network_list_push(enumerator->subnets, subnet);
ed0f53df
MT
1450 if (r) {
1451 loc_network_unref(subnet);
065b3496 1452 loc_network_list_clear(enumerator->subnets);
ed0f53df
MT
1453
1454 return r;
1455 }
d87fd7a3
MT
1456
1457 loc_network_unref(subnet);
1458 continue;
1459 }
1460
1461 // If this is not a subnet, we push it back onto the stack and break
1462 r = loc_network_list_push(enumerator->stack, subnet);
ed0f53df
MT
1463 if (r) {
1464 loc_network_unref(subnet);
065b3496 1465 loc_network_list_clear(enumerator->subnets);
ed0f53df
MT
1466
1467 return r;
1468 }
d87fd7a3
MT
1469
1470 loc_network_unref(subnet);
1471 break;
1472 }
1473
065b3496
MT
1474 DEBUG(enumerator->ctx, "Found %zu subnet(s)\n",
1475 loc_network_list_size(enumerator->subnets));
d87fd7a3
MT
1476
1477 // We can abort here if the network has no subnets
065b3496
MT
1478 if (loc_network_list_empty(enumerator->subnets)) {
1479 loc_network_list_clear(enumerator->subnets);
d87fd7a3
MT
1480
1481 return 0;
1482 }
1483
1484 // If the network has any subnets, we will break it into smaller parts
1485 // without the subnets.
065b3496 1486 struct loc_network_list* excluded = loc_network_exclude_list(*network, enumerator->subnets);
ed0f53df 1487 if (!excluded) {
065b3496 1488 loc_network_list_clear(enumerator->subnets);
725718e1 1489 return 1;
ed0f53df
MT
1490 }
1491
5dacb45a 1492 // Merge subnets onto the stack
065b3496 1493 r = loc_network_list_merge(enumerator->stack, enumerator->subnets);
ed0f53df 1494 if (r) {
065b3496 1495 loc_network_list_clear(enumerator->subnets);
ed0f53df
MT
1496 loc_network_list_unref(excluded);
1497
1498 return r;
d87fd7a3
MT
1499 }
1500
5dacb45a
MT
1501 // Push excluded list onto the stack
1502 r = loc_network_list_merge(enumerator->stack, excluded);
1503 if (r) {
065b3496 1504 loc_network_list_clear(enumerator->subnets);
5dacb45a 1505 loc_network_list_unref(excluded);
d87fd7a3 1506
5dacb45a
MT
1507 return r;
1508 }
d87fd7a3 1509
065b3496 1510 loc_network_list_clear(enumerator->subnets);
5dacb45a
MT
1511 loc_network_list_unref(excluded);
1512
6bd9cd76 1513 // Drop the network and restart the whole process again to pick the next network
5dacb45a 1514 loc_network_unref(*network);
d87fd7a3 1515
6bd9cd76 1516 return __loc_database_enumerator_next_network_flattened(enumerator, network);
d87fd7a3
MT
1517}
1518
8c37d8a7
MT
1519/*
1520 This function finds all bogons (i.e. gaps) between the input networks
1521*/
8c37d8a7
MT
1522static int __loc_database_enumerator_next_bogon(
1523 struct loc_database_enumerator* enumerator, struct loc_network** bogon) {
1524 int r;
1525
1526 // Return top element from the stack
1527 while (1) {
1528 *bogon = loc_network_list_pop_first(enumerator->stack);
1529
1530 // Stack is empty
1531 if (!*bogon)
1532 break;
1533
1534 // Return result
1535 return 0;
1536 }
1537
1538 struct loc_network* network = NULL;
9306c68d
MT
1539 struct in6_addr* gap_start = NULL;
1540 struct in6_addr gap_end = IN6ADDR_ANY_INIT;
8c37d8a7
MT
1541
1542 while (1) {
1543 r = __loc_database_enumerator_next_network(enumerator, &network, 1);
1544 if (r)
9306c68d 1545 return r;
8c37d8a7 1546
9306c68d 1547 // We have read the last network
8c37d8a7 1548 if (!network)
9306c68d
MT
1549 goto FINISH;
1550
5a01e11e
MT
1551 const char* country_code = loc_network_get_country_code(network);
1552
1553 /*
1554 Skip anything that does not have a country code
1555
1556 Even if a network is part of the routing table, and the database provides
1557 an ASN, this does not mean that this is a legitimate announcement.
1558 */
1559 if (country_code && !*country_code) {
1560 loc_network_unref(network);
1561 continue;
1562 }
1563
9306c68d
MT
1564 // Determine the network family
1565 int family = loc_network_address_family(network);
1566
1567 switch (family) {
1568 case AF_INET6:
1569 gap_start = &enumerator->gap6_start;
1570 break;
1571
1572 case AF_INET:
1573 gap_start = &enumerator->gap4_start;
1574 break;
1575
1576 default:
1577 ERROR(enumerator->ctx, "Unsupported network family %d\n", family);
1578 errno = ENOTSUP;
1579 return 1;
1580 }
1581
8649c654
MT
1582 const struct in6_addr* first_address = loc_network_get_first_address(network);
1583 const struct in6_addr* last_address = loc_network_get_last_address(network);
1584
1585 // Skip if this network is a subnet of a former one
1586 if (loc_address_cmp(gap_start, last_address) >= 0) {
1587 loc_network_unref(network);
1588 continue;
1589 }
1590
9306c68d 1591 // Search where the gap could end
8649c654 1592 gap_end = *first_address;
5b72642c 1593 loc_address_decrement(&gap_end);
8c37d8a7 1594
9306c68d 1595 // There is a gap
c833e45e 1596 if (loc_address_cmp(gap_start, &gap_end) <= 0) {
9306c68d
MT
1597 r = loc_network_list_summarize(enumerator->ctx,
1598 gap_start, &gap_end, &enumerator->stack);
8c37d8a7
MT
1599 if (r) {
1600 loc_network_unref(network);
9306c68d 1601 return r;
8c37d8a7
MT
1602 }
1603 }
1604
9306c68d 1605 // The gap now starts after this network
8649c654 1606 *gap_start = *last_address;
5b72642c 1607 loc_address_increment(gap_start);
9306c68d 1608
8c37d8a7
MT
1609 loc_network_unref(network);
1610
1611 // Try to return something
1612 *bogon = loc_network_list_pop_first(enumerator->stack);
1613 if (*bogon)
1614 break;
1615 }
1616
9306c68d
MT
1617 return 0;
1618
1619FINISH:
1620
1621 if (!loc_address_all_zeroes(&enumerator->gap6_start)) {
1622 r = loc_address_reset_last(&gap_end, AF_INET6);
1623 if (r)
1624 return r;
1625
c833e45e 1626 if (loc_address_cmp(&enumerator->gap6_start, &gap_end) <= 0) {
9306c68d
MT
1627 r = loc_network_list_summarize(enumerator->ctx,
1628 &enumerator->gap6_start, &gap_end, &enumerator->stack);
1629 if (r)
1630 return r;
1631 }
c0b1f64f
MT
1632
1633 // Reset start
1634 loc_address_reset(&enumerator->gap6_start, AF_INET6);
9306c68d
MT
1635 }
1636
1637 if (!loc_address_all_zeroes(&enumerator->gap4_start)) {
1638 r = loc_address_reset_last(&gap_end, AF_INET);
1639 if (r)
1640 return r;
1641
c833e45e 1642 if (loc_address_cmp(&enumerator->gap4_start, &gap_end) <= 0) {
9306c68d
MT
1643 r = loc_network_list_summarize(enumerator->ctx,
1644 &enumerator->gap4_start, &gap_end, &enumerator->stack);
1645 if (r)
1646 return r;
1647 }
c0b1f64f
MT
1648
1649 // Reset start
1650 loc_address_reset(&enumerator->gap4_start, AF_INET);
9306c68d
MT
1651 }
1652
1653 // Try to return something
1654 *bogon = loc_network_list_pop_first(enumerator->stack);
1655
1656 return 0;
8c37d8a7
MT
1657}
1658
d87fd7a3
MT
1659LOC_EXPORT int loc_database_enumerator_next_network(
1660 struct loc_database_enumerator* enumerator, struct loc_network** network) {
8c37d8a7
MT
1661 switch (enumerator->mode) {
1662 case LOC_DB_ENUMERATE_NETWORKS:
1663 // Flatten output?
1664 if (enumerator->flatten)
1665 return __loc_database_enumerator_next_network_flattened(enumerator, network);
d87fd7a3 1666
8c37d8a7
MT
1667 return __loc_database_enumerator_next_network(enumerator, network, 1);
1668
1669 case LOC_DB_ENUMERATE_BOGONS:
1670 return __loc_database_enumerator_next_bogon(enumerator, network);
d87fd7a3 1671
8c37d8a7
MT
1672 default:
1673 return 0;
1674 }
e3f696c1 1675}
fa9a3663
MT
1676
1677LOC_EXPORT int loc_database_enumerator_next_country(
1678 struct loc_database_enumerator* enumerator, struct loc_country** country) {
1679 *country = NULL;
1680
1681 // Do not do anything if not in country mode
1682 if (enumerator->mode != LOC_DB_ENUMERATE_COUNTRIES)
1683 return 0;
1684
1685 struct loc_database* db = enumerator->db;
1686
18638ad2 1687 while (enumerator->country_index < db->country_objects.count) {
fa9a3663
MT
1688 // Fetch the next country
1689 int r = loc_database_fetch_country(db, country, enumerator->country_index++);
1690 if (r)
1691 return r;
1692
1693 // We do not filter here, so it always is a match
1694 return 0;
1695 }
1696
1697 // Reset the index
1698 enumerator->country_index = 0;
1699
1700 // We have searched through all of them
1701 return 0;
1702}