|
| 1 | +// Required for mkstemp visibility under -D_POSIX_C_SOURCE=200112L on glibc. |
| 2 | +#define _XOPEN_SOURCE 500 |
| 3 | + |
| 4 | +#include "maxminddb_test_helper.h" |
| 5 | + |
| 6 | +#include <errno.h> |
| 7 | +#include <stdio.h> |
| 8 | +#include <string.h> |
| 9 | + |
| 10 | +#ifdef _WIN32 |
| 11 | + #include <io.h> |
| 12 | + #define unlink _unlink |
| 13 | +#else |
| 14 | + #include <unistd.h> |
| 15 | +#endif |
| 16 | + |
| 17 | +static FILE *open_temp_file(char *path, size_t path_size) { |
| 18 | +#ifdef _WIN32 |
| 19 | + errno_t err = tmpnam_s(path, path_size); |
| 20 | + if (err != 0) { |
| 21 | + return NULL; |
| 22 | + } |
| 23 | + return fopen(path, "wb"); |
| 24 | +#else |
| 25 | + snprintf(path, path_size, "./metadata-marker-XXXXXX"); |
| 26 | + int fd = mkstemp(path); |
| 27 | + if (fd < 0) { |
| 28 | + return NULL; |
| 29 | + } |
| 30 | + return fdopen(fd, "wb"); |
| 31 | +#endif |
| 32 | +} |
| 33 | + |
| 34 | +static void test_trailing_metadata_marker(void) { |
| 35 | + char temp_path[64]; |
| 36 | + FILE *temp = open_temp_file(temp_path, sizeof(temp_path)); |
| 37 | + if (!temp) { |
| 38 | + BAIL_OUT("could not create temp file: %s", strerror(errno)); |
| 39 | + } |
| 40 | + |
| 41 | + static const unsigned char metadata_marker[] = "\xab\xcd\xefMaxMind.com"; |
| 42 | + size_t expected = sizeof(metadata_marker) - 1; |
| 43 | + if (fwrite(metadata_marker, 1, expected, temp) != expected) { |
| 44 | + int saved_errno = errno; |
| 45 | + fclose(temp); |
| 46 | + unlink(temp_path); |
| 47 | + BAIL_OUT("fwrite failed: %s", strerror(saved_errno)); |
| 48 | + } |
| 49 | + if (fclose(temp) != 0) { |
| 50 | + int saved_errno = errno; |
| 51 | + unlink(temp_path); |
| 52 | + BAIL_OUT("fclose failed: %s", strerror(saved_errno)); |
| 53 | + } |
| 54 | + |
| 55 | + MMDB_s mmdb; |
| 56 | + int status = MMDB_open(temp_path, MMDB_MODE_MMAP, &mmdb); |
| 57 | + cmp_ok(status, |
| 58 | + "==", |
| 59 | + MMDB_INVALID_METADATA_ERROR, |
| 60 | + "MMDB_open rejects a trailing metadata marker with no metadata"); |
| 61 | + |
| 62 | + if (status == MMDB_SUCCESS) { |
| 63 | + MMDB_close(&mmdb); |
| 64 | + } |
| 65 | + |
| 66 | + unlink(temp_path); |
| 67 | +} |
| 68 | + |
| 69 | +int main(void) { |
| 70 | + plan(NO_PLAN); |
| 71 | + test_trailing_metadata_marker(); |
| 72 | + done_testing(); |
| 73 | +} |
0 commit comments