-
Notifications
You must be signed in to change notification settings - Fork 242
/
maxminddb.c
2192 lines (1907 loc) · 73.7 KB
/
maxminddb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "data-pool.h"
#include "maxminddb-compat-util.h"
#include "maxminddb.h"
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#include <ws2ipdef.h>
#ifndef SSIZE_MAX
#define SSIZE_MAX INTPTR_MAX
#endif
typedef ADDRESS_FAMILY sa_family_t;
#else
#include <arpa/inet.h>
#include <sys/mman.h>
#include <unistd.h>
#endif
#define MMDB_DATA_SECTION_SEPARATOR (16)
#define MAXIMUM_DATA_STRUCTURE_DEPTH (512)
#ifdef MMDB_DEBUG
#define DEBUG_MSG(msg) fprintf(stderr, msg "\n")
#define DEBUG_MSGF(fmt, ...) fprintf(stderr, fmt "\n", __VA_ARGS__)
#define DEBUG_BINARY(fmt, byte) \
do { \
char *binary = byte_to_binary(byte); \
if (NULL == binary) { \
fprintf(stderr, "Calloc failed in DEBUG_BINARY\n"); \
abort(); \
} \
fprintf(stderr, fmt "\n", binary); \
free(binary); \
} while (0)
#define DEBUG_NL fprintf(stderr, "\n")
#else
#define DEBUG_MSG(...)
#define DEBUG_MSGF(...)
#define DEBUG_BINARY(...)
#define DEBUG_NL
#endif
#ifdef MMDB_DEBUG
char *byte_to_binary(uint8_t byte) {
char *bits = calloc(9, sizeof(char));
if (NULL == bits) {
return bits;
}
for (uint8_t i = 0; i < 8; i++) {
bits[i] = byte & (128 >> i) ? '1' : '0';
}
bits[8] = '\0';
return bits;
}
char *type_num_to_name(uint8_t num) {
switch (num) {
case 0:
return "extended";
case 1:
return "pointer";
case 2:
return "utf8_string";
case 3:
return "double";
case 4:
return "bytes";
case 5:
return "uint16";
case 6:
return "uint32";
case 7:
return "map";
case 8:
return "int32";
case 9:
return "uint64";
case 10:
return "uint128";
case 11:
return "array";
case 12:
return "container";
case 13:
return "end_marker";
case 14:
return "boolean";
case 15:
return "float";
default:
return "unknown type";
}
}
#endif
/* None of the values we check on the lhs are bigger than uint32_t, so on
* platforms where SIZE_MAX is a 64-bit integer, this would be a no-op, and it
* makes the compiler complain if we do the check anyway. */
#if SIZE_MAX == UINT32_MAX
#define MAYBE_CHECK_SIZE_OVERFLOW(lhs, rhs, error) \
if ((lhs) > (rhs)) { \
return error; \
}
#else
#define MAYBE_CHECK_SIZE_OVERFLOW(...)
#endif
typedef struct record_info_s {
uint16_t record_length;
uint32_t (*left_record_getter)(const uint8_t *);
uint32_t (*right_record_getter)(const uint8_t *);
uint8_t right_record_offset;
} record_info_s;
#define METADATA_MARKER "\xab\xcd\xefMaxMind.com"
/* This is 128kb */
#define METADATA_BLOCK_MAX_SIZE 131072
// 64 leads us to allocating 4 KiB on a 64bit system.
#define MMDB_POOL_INIT_SIZE 64
static int map_file(MMDB_s *const mmdb);
static const uint8_t *find_metadata(const uint8_t *file_content,
ssize_t file_size,
uint32_t *metadata_size);
static int read_metadata(MMDB_s *mmdb);
static MMDB_s make_fake_metadata_db(const MMDB_s *const mmdb);
static int
value_for_key_as_uint16(MMDB_entry_s *start, char *key, uint16_t *value);
static int
value_for_key_as_uint32(MMDB_entry_s *start, char *key, uint32_t *value);
static int
value_for_key_as_uint64(MMDB_entry_s *start, char *key, uint64_t *value);
static int
value_for_key_as_string(MMDB_entry_s *start, char *key, char const **value);
static int populate_languages_metadata(MMDB_s *mmdb,
MMDB_s *metadata_db,
MMDB_entry_s *metadata_start);
static int populate_description_metadata(MMDB_s *mmdb,
MMDB_s *metadata_db,
MMDB_entry_s *metadata_start);
static int resolve_any_address(const char *ipstr, struct addrinfo **addresses);
static int find_address_in_search_tree(const MMDB_s *const mmdb,
uint8_t const *address,
sa_family_t address_family,
MMDB_lookup_result_s *result);
static record_info_s record_info_for_database(const MMDB_s *const mmdb);
static int find_ipv4_start_node(MMDB_s *const mmdb);
static uint8_t record_type(const MMDB_s *const mmdb, uint64_t record);
static uint32_t get_left_28_bit_record(const uint8_t *record);
static uint32_t get_right_28_bit_record(const uint8_t *record);
static uint32_t data_section_offset_for_record(const MMDB_s *const mmdb,
uint64_t record);
static size_t path_length(va_list va_path);
static int lookup_path_in_array(const char *path_elem,
const MMDB_s *const mmdb,
MMDB_entry_data_s *entry_data);
static int lookup_path_in_map(const char *path_elem,
const MMDB_s *const mmdb,
MMDB_entry_data_s *entry_data);
static int skip_map_or_array(const MMDB_s *const mmdb,
MMDB_entry_data_s *entry_data);
static int decode_one_follow(const MMDB_s *const mmdb,
uint32_t offset,
MMDB_entry_data_s *entry_data);
static int decode_one(const MMDB_s *const mmdb,
uint32_t offset,
MMDB_entry_data_s *entry_data);
static int get_ext_type(int raw_ext_type);
static uint32_t
get_ptr_from(uint8_t ctrl, uint8_t const *const ptr, int ptr_size);
static int get_entry_data_list(const MMDB_s *const mmdb,
uint32_t offset,
MMDB_entry_data_list_s *const entry_data_list,
MMDB_data_pool_s *const pool,
int depth);
static float get_ieee754_float(const uint8_t *restrict p);
static double get_ieee754_double(const uint8_t *restrict p);
static uint32_t get_uint32(const uint8_t *p);
static uint32_t get_uint24(const uint8_t *p);
static uint32_t get_uint16(const uint8_t *p);
static uint64_t get_uintX(const uint8_t *p, int length);
static int32_t get_sintX(const uint8_t *p, int length);
static void free_mmdb_struct(MMDB_s *const mmdb);
static void free_languages_metadata(MMDB_s *mmdb);
static void free_descriptions_metadata(MMDB_s *mmdb);
static MMDB_entry_data_list_s *
dump_entry_data_list(FILE *stream,
MMDB_entry_data_list_s *entry_data_list,
int indent,
int *status);
static void print_indentation(FILE *stream, int i);
static char *bytes_to_hex(uint8_t const *bytes, uint32_t size);
#define CHECKED_DECODE_ONE(mmdb, offset, entry_data) \
do { \
int status = decode_one(mmdb, offset, entry_data); \
if (MMDB_SUCCESS != status) { \
DEBUG_MSGF("CHECKED_DECODE_ONE failed." \
" status = %d (%s)", \
status, \
MMDB_strerror(status)); \
return status; \
} \
} while (0)
#define CHECKED_DECODE_ONE_FOLLOW(mmdb, offset, entry_data) \
do { \
int status = decode_one_follow(mmdb, offset, entry_data); \
if (MMDB_SUCCESS != status) { \
DEBUG_MSGF("CHECKED_DECODE_ONE_FOLLOW failed." \
" status = %d (%s)", \
status, \
MMDB_strerror(status)); \
return status; \
} \
} while (0)
#define FREE_AND_SET_NULL(p) \
{ \
free((void *)(p)); \
(p) = NULL; \
}
int MMDB_open(const char *const filename, uint32_t flags, MMDB_s *const mmdb) {
int status = MMDB_SUCCESS;
mmdb->file_content = NULL;
mmdb->data_section = NULL;
mmdb->metadata.database_type = NULL;
mmdb->metadata.languages.count = 0;
mmdb->metadata.languages.names = NULL;
mmdb->metadata.description.count = 0;
mmdb->filename = mmdb_strdup(filename);
if (NULL == mmdb->filename) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
if ((flags & MMDB_MODE_MASK) == 0) {
flags |= MMDB_MODE_MMAP;
}
mmdb->flags = flags;
if (MMDB_SUCCESS != (status = map_file(mmdb))) {
goto cleanup;
}
#ifdef _WIN32
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
#endif
uint32_t metadata_size = 0;
const uint8_t *metadata =
find_metadata(mmdb->file_content, mmdb->file_size, &metadata_size);
if (NULL == metadata) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
mmdb->metadata_section = metadata;
mmdb->metadata_section_size = metadata_size;
status = read_metadata(mmdb);
if (MMDB_SUCCESS != status) {
goto cleanup;
}
if (mmdb->metadata.binary_format_major_version != 2) {
status = MMDB_UNKNOWN_DATABASE_FORMAT_ERROR;
goto cleanup;
}
if (!can_multiply(SSIZE_MAX,
mmdb->metadata.node_count,
mmdb->full_record_byte_size)) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
ssize_t search_tree_size = (ssize_t)mmdb->metadata.node_count *
(ssize_t)mmdb->full_record_byte_size;
mmdb->data_section =
mmdb->file_content + search_tree_size + MMDB_DATA_SECTION_SEPARATOR;
if (mmdb->file_size < MMDB_DATA_SECTION_SEPARATOR ||
search_tree_size > mmdb->file_size - MMDB_DATA_SECTION_SEPARATOR) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
ssize_t data_section_size =
mmdb->file_size - search_tree_size - MMDB_DATA_SECTION_SEPARATOR;
if (data_section_size > UINT32_MAX || data_section_size <= 0) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
mmdb->data_section_size = (uint32_t)data_section_size;
// Although it is likely not possible to construct a database with valid
// valid metadata, as parsed above, and a data_section_size less than 3,
// we do this check as later we assume it is at least three when doing
// bound checks.
if (mmdb->data_section_size < 3) {
status = MMDB_INVALID_DATA_ERROR;
goto cleanup;
}
mmdb->metadata_section = metadata;
mmdb->ipv4_start_node.node_value = 0;
mmdb->ipv4_start_node.netmask = 0;
// We do this immediately as otherwise there is a race to set
// ipv4_start_node.node_value and ipv4_start_node.netmask.
if (mmdb->metadata.ip_version == 6) {
status = find_ipv4_start_node(mmdb);
if (status != MMDB_SUCCESS) {
goto cleanup;
}
}
cleanup:
if (MMDB_SUCCESS != status) {
int saved_errno = errno;
free_mmdb_struct(mmdb);
errno = saved_errno;
}
return status;
}
#ifdef _WIN32
static LPWSTR utf8_to_utf16(const char *utf8_str) {
int wide_chars = MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1, NULL, 0);
wchar_t *utf16_str = (wchar_t *)calloc(wide_chars, sizeof(wchar_t));
if (!utf16_str) {
return NULL;
}
if (MultiByteToWideChar(CP_UTF8, 0, utf8_str, -1, utf16_str, wide_chars) <
1) {
free(utf16_str);
return NULL;
}
return utf16_str;
}
static int map_file(MMDB_s *const mmdb) {
DWORD size;
int status = MMDB_SUCCESS;
HANDLE mmh = NULL;
HANDLE fd = INVALID_HANDLE_VALUE;
LPWSTR utf16_filename = utf8_to_utf16(mmdb->filename);
if (!utf16_filename) {
status = MMDB_FILE_OPEN_ERROR;
goto cleanup;
}
fd = CreateFileW(utf16_filename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (fd == INVALID_HANDLE_VALUE) {
status = MMDB_FILE_OPEN_ERROR;
goto cleanup;
}
size = GetFileSize(fd, NULL);
if (size == INVALID_FILE_SIZE) {
status = MMDB_FILE_OPEN_ERROR;
goto cleanup;
}
mmh = CreateFileMapping(fd, NULL, PAGE_READONLY, 0, size, NULL);
/* Microsoft documentation for CreateFileMapping indicates this returns
NULL not INVALID_HANDLE_VALUE on error */
if (NULL == mmh) {
status = MMDB_IO_ERROR;
goto cleanup;
}
uint8_t *file_content =
(uint8_t *)MapViewOfFile(mmh, FILE_MAP_READ, 0, 0, 0);
if (file_content == NULL) {
status = MMDB_IO_ERROR;
goto cleanup;
}
mmdb->file_size = size;
mmdb->file_content = file_content;
cleanup:;
int saved_errno = errno;
if (INVALID_HANDLE_VALUE != fd) {
CloseHandle(fd);
}
if (NULL != mmh) {
CloseHandle(mmh);
}
errno = saved_errno;
free(utf16_filename);
return status;
}
#else // _WIN32
static int map_file(MMDB_s *const mmdb) {
int status = MMDB_SUCCESS;
int o_flags = O_RDONLY;
#ifdef O_CLOEXEC
o_flags |= O_CLOEXEC;
#endif
int fd = open(mmdb->filename, o_flags);
if (fd < 0) {
status = MMDB_FILE_OPEN_ERROR;
goto cleanup;
}
#if defined(FD_CLOEXEC) && !defined(O_CLOEXEC)
int fd_flags = fcntl(fd, F_GETFD);
if (fd_flags >= 0) {
fcntl(fd, F_SETFD, fd_flags | FD_CLOEXEC);
}
#endif
struct stat s;
if (fstat(fd, &s)) {
status = MMDB_FILE_OPEN_ERROR;
goto cleanup;
}
off_t size = s.st_size;
if (size < 0 || size > SSIZE_MAX) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
uint8_t *file_content =
(uint8_t *)mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED, fd, 0);
if (MAP_FAILED == file_content) {
if (ENOMEM == errno) {
status = MMDB_OUT_OF_MEMORY_ERROR;
} else {
status = MMDB_IO_ERROR;
}
goto cleanup;
}
mmdb->file_size = (ssize_t)size;
mmdb->file_content = file_content;
cleanup:;
int saved_errno = errno;
if (fd >= 0) {
close(fd);
}
errno = saved_errno;
return status;
}
#endif // _WIN32
static const uint8_t *find_metadata(const uint8_t *file_content,
ssize_t file_size,
uint32_t *metadata_size) {
const ssize_t marker_len = sizeof(METADATA_MARKER) - 1;
ssize_t max_size = file_size > METADATA_BLOCK_MAX_SIZE
? METADATA_BLOCK_MAX_SIZE
: file_size;
if (max_size < 0) {
return NULL;
}
uint8_t const *search_area = (file_content + (file_size - max_size));
uint8_t const *start = search_area;
uint8_t const *tmp;
do {
tmp = mmdb_memmem(
search_area, (size_t)max_size, METADATA_MARKER, marker_len);
if (NULL != tmp) {
max_size -= tmp - search_area;
search_area = tmp;
/* Continue searching just after the marker we just read, in case
* there are multiple markers in the same file. This would be odd
* but is certainly not impossible. */
max_size -= marker_len;
search_area += marker_len;
}
} while (NULL != tmp);
if (search_area == start) {
return NULL;
}
*metadata_size = (uint32_t)max_size;
return search_area;
}
static int read_metadata(MMDB_s *mmdb) {
/* We need to create a fake MMDB_s struct in order to decode values from
the metadata. The metadata is basically just like the data section, so we
want to use the same functions we use for the data section to get
metadata values. */
MMDB_s metadata_db = make_fake_metadata_db(mmdb);
MMDB_entry_s metadata_start = {.mmdb = &metadata_db, .offset = 0};
int status = value_for_key_as_uint32(
&metadata_start, "node_count", &mmdb->metadata.node_count);
if (MMDB_SUCCESS != status) {
return status;
}
if (!mmdb->metadata.node_count) {
DEBUG_MSG("could not find node_count value in metadata");
return MMDB_INVALID_METADATA_ERROR;
}
status = value_for_key_as_uint16(
&metadata_start, "record_size", &mmdb->metadata.record_size);
if (MMDB_SUCCESS != status) {
return status;
}
if (!mmdb->metadata.record_size) {
DEBUG_MSG("could not find record_size value in metadata");
return MMDB_INVALID_METADATA_ERROR;
}
if (mmdb->metadata.record_size != 24 && mmdb->metadata.record_size != 28 &&
mmdb->metadata.record_size != 32) {
DEBUG_MSGF("bad record size in metadata: %i",
mmdb->metadata.record_size);
return MMDB_UNKNOWN_DATABASE_FORMAT_ERROR;
}
status = value_for_key_as_uint16(
&metadata_start, "ip_version", &mmdb->metadata.ip_version);
if (MMDB_SUCCESS != status) {
return status;
}
if (!mmdb->metadata.ip_version) {
DEBUG_MSG("could not find ip_version value in metadata");
return MMDB_INVALID_METADATA_ERROR;
}
if (!(mmdb->metadata.ip_version == 4 || mmdb->metadata.ip_version == 6)) {
DEBUG_MSGF("ip_version value in metadata is not 4 or 6 - it was %i",
mmdb->metadata.ip_version);
return MMDB_INVALID_METADATA_ERROR;
}
status = value_for_key_as_string(
&metadata_start, "database_type", &mmdb->metadata.database_type);
if (MMDB_SUCCESS != status) {
DEBUG_MSG("error finding database_type value in metadata");
return status;
}
status = populate_languages_metadata(mmdb, &metadata_db, &metadata_start);
if (MMDB_SUCCESS != status) {
DEBUG_MSG("could not populate languages from metadata");
return status;
}
status =
value_for_key_as_uint16(&metadata_start,
"binary_format_major_version",
&mmdb->metadata.binary_format_major_version);
if (MMDB_SUCCESS != status) {
return status;
}
if (!mmdb->metadata.binary_format_major_version) {
DEBUG_MSG(
"could not find binary_format_major_version value in metadata");
return MMDB_INVALID_METADATA_ERROR;
}
status =
value_for_key_as_uint16(&metadata_start,
"binary_format_minor_version",
&mmdb->metadata.binary_format_minor_version);
if (MMDB_SUCCESS != status) {
return status;
}
status = value_for_key_as_uint64(
&metadata_start, "build_epoch", &mmdb->metadata.build_epoch);
if (MMDB_SUCCESS != status) {
return status;
}
if (!mmdb->metadata.build_epoch) {
DEBUG_MSG("could not find build_epoch value in metadata");
return MMDB_INVALID_METADATA_ERROR;
}
status = populate_description_metadata(mmdb, &metadata_db, &metadata_start);
if (MMDB_SUCCESS != status) {
DEBUG_MSG("could not populate description from metadata");
return status;
}
mmdb->full_record_byte_size = mmdb->metadata.record_size * 2 / 8U;
mmdb->depth = mmdb->metadata.ip_version == 4 ? 32 : 128;
return MMDB_SUCCESS;
}
static MMDB_s make_fake_metadata_db(const MMDB_s *const mmdb) {
MMDB_s fake_metadata_db = {.data_section = mmdb->metadata_section,
.data_section_size =
mmdb->metadata_section_size};
return fake_metadata_db;
}
static int
value_for_key_as_uint16(MMDB_entry_s *start, char *key, uint16_t *value) {
MMDB_entry_data_s entry_data;
const char *path[] = {key, NULL};
int status = MMDB_aget_value(start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_UINT16 != entry_data.type) {
DEBUG_MSGF("expect uint16 for %s but received %s",
key,
type_num_to_name(entry_data.type));
return MMDB_INVALID_METADATA_ERROR;
}
*value = entry_data.uint16;
return MMDB_SUCCESS;
}
static int
value_for_key_as_uint32(MMDB_entry_s *start, char *key, uint32_t *value) {
MMDB_entry_data_s entry_data;
const char *path[] = {key, NULL};
int status = MMDB_aget_value(start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_UINT32 != entry_data.type) {
DEBUG_MSGF("expect uint32 for %s but received %s",
key,
type_num_to_name(entry_data.type));
return MMDB_INVALID_METADATA_ERROR;
}
*value = entry_data.uint32;
return MMDB_SUCCESS;
}
static int
value_for_key_as_uint64(MMDB_entry_s *start, char *key, uint64_t *value) {
MMDB_entry_data_s entry_data;
const char *path[] = {key, NULL};
int status = MMDB_aget_value(start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_UINT64 != entry_data.type) {
DEBUG_MSGF("expect uint64 for %s but received %s",
key,
type_num_to_name(entry_data.type));
return MMDB_INVALID_METADATA_ERROR;
}
*value = entry_data.uint64;
return MMDB_SUCCESS;
}
static int
value_for_key_as_string(MMDB_entry_s *start, char *key, char const **value) {
MMDB_entry_data_s entry_data;
const char *path[] = {key, NULL};
int status = MMDB_aget_value(start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_UTF8_STRING != entry_data.type) {
DEBUG_MSGF("expect string for %s but received %s",
key,
type_num_to_name(entry_data.type));
return MMDB_INVALID_METADATA_ERROR;
}
*value = mmdb_strndup(entry_data.utf8_string, entry_data.data_size);
if (NULL == *value) {
return MMDB_OUT_OF_MEMORY_ERROR;
}
return MMDB_SUCCESS;
}
static int populate_languages_metadata(MMDB_s *mmdb,
MMDB_s *metadata_db,
MMDB_entry_s *metadata_start) {
MMDB_entry_data_s entry_data;
const char *path[] = {"languages", NULL};
int status = MMDB_aget_value(metadata_start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_ARRAY != entry_data.type) {
return MMDB_INVALID_METADATA_ERROR;
}
MMDB_entry_s array_start = {.mmdb = metadata_db,
.offset = entry_data.offset};
MMDB_entry_data_list_s *member;
status = MMDB_get_entry_data_list(&array_start, &member);
if (MMDB_SUCCESS != status) {
return status;
}
MMDB_entry_data_list_s *first_member = member;
uint32_t array_size = member->entry_data.data_size;
MAYBE_CHECK_SIZE_OVERFLOW(
array_size, SIZE_MAX / sizeof(char *), MMDB_INVALID_METADATA_ERROR);
mmdb->metadata.languages.count = 0;
mmdb->metadata.languages.names = calloc(array_size, sizeof(char *));
if (NULL == mmdb->metadata.languages.names) {
MMDB_free_entry_data_list(first_member);
return MMDB_OUT_OF_MEMORY_ERROR;
}
for (uint32_t i = 0; i < array_size; i++) {
member = member->next;
if (MMDB_DATA_TYPE_UTF8_STRING != member->entry_data.type) {
MMDB_free_entry_data_list(first_member);
return MMDB_INVALID_METADATA_ERROR;
}
mmdb->metadata.languages.names[i] = mmdb_strndup(
member->entry_data.utf8_string, member->entry_data.data_size);
if (NULL == mmdb->metadata.languages.names[i]) {
MMDB_free_entry_data_list(first_member);
return MMDB_OUT_OF_MEMORY_ERROR;
}
// We assign this as we go so that if we fail a calloc and need to
// free it, the count is right.
mmdb->metadata.languages.count = i + 1;
}
MMDB_free_entry_data_list(first_member);
return MMDB_SUCCESS;
}
static int populate_description_metadata(MMDB_s *mmdb,
MMDB_s *metadata_db,
MMDB_entry_s *metadata_start) {
MMDB_entry_data_s entry_data;
const char *path[] = {"description", NULL};
int status = MMDB_aget_value(metadata_start, &entry_data, path);
if (MMDB_SUCCESS != status) {
return status;
}
if (MMDB_DATA_TYPE_MAP != entry_data.type) {
DEBUG_MSGF("Unexpected entry_data type: %d", entry_data.type);
return MMDB_INVALID_METADATA_ERROR;
}
MMDB_entry_s map_start = {.mmdb = metadata_db, .offset = entry_data.offset};
MMDB_entry_data_list_s *member;
status = MMDB_get_entry_data_list(&map_start, &member);
if (MMDB_SUCCESS != status) {
DEBUG_MSGF(
"MMDB_get_entry_data_list failed while populating description."
" status = %d (%s)",
status,
MMDB_strerror(status));
return status;
}
MMDB_entry_data_list_s *first_member = member;
uint32_t map_size = member->entry_data.data_size;
mmdb->metadata.description.count = 0;
if (0 == map_size) {
mmdb->metadata.description.descriptions = NULL;
goto cleanup;
}
MAYBE_CHECK_SIZE_OVERFLOW(map_size,
SIZE_MAX / sizeof(MMDB_description_s *),
MMDB_INVALID_METADATA_ERROR);
mmdb->metadata.description.descriptions =
calloc(map_size, sizeof(MMDB_description_s *));
if (NULL == mmdb->metadata.description.descriptions) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
for (uint32_t i = 0; i < map_size; i++) {
mmdb->metadata.description.descriptions[i] =
calloc(1, sizeof(MMDB_description_s));
if (NULL == mmdb->metadata.description.descriptions[i]) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
mmdb->metadata.description.count = i + 1;
mmdb->metadata.description.descriptions[i]->language = NULL;
mmdb->metadata.description.descriptions[i]->description = NULL;
member = member->next;
if (MMDB_DATA_TYPE_UTF8_STRING != member->entry_data.type) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
mmdb->metadata.description.descriptions[i]->language = mmdb_strndup(
member->entry_data.utf8_string, member->entry_data.data_size);
if (NULL == mmdb->metadata.description.descriptions[i]->language) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
member = member->next;
if (MMDB_DATA_TYPE_UTF8_STRING != member->entry_data.type) {
status = MMDB_INVALID_METADATA_ERROR;
goto cleanup;
}
mmdb->metadata.description.descriptions[i]->description = mmdb_strndup(
member->entry_data.utf8_string, member->entry_data.data_size);
if (NULL == mmdb->metadata.description.descriptions[i]->description) {
status = MMDB_OUT_OF_MEMORY_ERROR;
goto cleanup;
}
}
cleanup:
MMDB_free_entry_data_list(first_member);
return status;
}
MMDB_lookup_result_s MMDB_lookup_string(const MMDB_s *const mmdb,
const char *const ipstr,
int *const gai_error,
int *const mmdb_error) {
MMDB_lookup_result_s result = {.found_entry = false,
.netmask = 0,
.entry = {.mmdb = mmdb, .offset = 0}};
struct addrinfo *addresses = NULL;
*gai_error = resolve_any_address(ipstr, &addresses);
if (!*gai_error) {
result = MMDB_lookup_sockaddr(mmdb, addresses->ai_addr, mmdb_error);
}
if (NULL != addresses) {
freeaddrinfo(addresses);
}
return result;
}
static int resolve_any_address(const char *ipstr, struct addrinfo **addresses) {
struct addrinfo hints = {
.ai_family = AF_UNSPEC,
.ai_flags = AI_NUMERICHOST,
// We set ai_socktype so that we only get one result back
.ai_socktype = SOCK_STREAM};
int gai_status = getaddrinfo(ipstr, NULL, &hints, addresses);
if (gai_status) {
return gai_status;
}
return 0;
}
MMDB_lookup_result_s MMDB_lookup_sockaddr(const MMDB_s *const mmdb,
const struct sockaddr *const sockaddr,
int *const mmdb_error) {
MMDB_lookup_result_s result = {.found_entry = false,
.netmask = 0,
.entry = {.mmdb = mmdb, .offset = 0}};
uint8_t mapped_address[16];
uint8_t const *address;
if (mmdb->metadata.ip_version == 4) {
if (sockaddr->sa_family == AF_INET6) {
*mmdb_error = MMDB_IPV6_LOOKUP_IN_IPV4_DATABASE_ERROR;
return result;
}
address = (uint8_t const *)&((struct sockaddr_in const *)sockaddr)
->sin_addr.s_addr;
} else {
if (sockaddr->sa_family == AF_INET6) {
address = (uint8_t const *)&((struct sockaddr_in6 const *)sockaddr)
->sin6_addr.s6_addr;
} else {
address = mapped_address;
memset(mapped_address, 0, 12);
memcpy(mapped_address + 12,
&((struct sockaddr_in const *)sockaddr)->sin_addr.s_addr,
4);
}
}
*mmdb_error = find_address_in_search_tree(
mmdb, address, sockaddr->sa_family, &result);
return result;
}
static int find_address_in_search_tree(const MMDB_s *const mmdb,
uint8_t const *address,
sa_family_t address_family,
MMDB_lookup_result_s *result) {
record_info_s record_info = record_info_for_database(mmdb);
if (record_info.right_record_offset == 0) {
return MMDB_UNKNOWN_DATABASE_FORMAT_ERROR;
}
uint64_t value = 0;
uint16_t current_bit = 0;
if (mmdb->metadata.ip_version == 6 && address_family == AF_INET) {
value = mmdb->ipv4_start_node.node_value;
current_bit = mmdb->ipv4_start_node.netmask;
}
uint32_t node_count = mmdb->metadata.node_count;
const uint8_t *search_tree = mmdb->file_content;
const uint8_t *record_pointer;
for (; current_bit < mmdb->depth && value < node_count; current_bit++) {
uint8_t bit =
1U & (address[current_bit >> 3] >> (7 - (current_bit % 8)));
// Note that value*record_info.record_length can be larger than 2**32
record_pointer = &search_tree[value * record_info.record_length];
if (record_pointer + record_info.record_length > mmdb->data_section) {
return MMDB_CORRUPT_SEARCH_TREE_ERROR;
}
if (bit) {
record_pointer += record_info.right_record_offset;
value = record_info.right_record_getter(record_pointer);
} else {
value = record_info.left_record_getter(record_pointer);
}
}
result->netmask = current_bit;
if (value >= node_count + mmdb->data_section_size) {
// The pointer points off the end of the database.
return MMDB_CORRUPT_SEARCH_TREE_ERROR;
}
if (value == node_count) {
// record is empty
result->found_entry = false;
return MMDB_SUCCESS;
}
result->found_entry = true;
result->entry.offset = data_section_offset_for_record(mmdb, value);
return MMDB_SUCCESS;
}
static record_info_s record_info_for_database(const MMDB_s *const mmdb) {
record_info_s record_info = {.record_length = mmdb->full_record_byte_size,
.right_record_offset = 0};