]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/test-resolved-etc-hosts.c
Merge pull request #8822 from fbuihuu/rfc-tmpfiles-safe-upstream
[thirdparty/systemd.git] / src / resolve / test-resolved-etc-hosts.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "fd-util.h"
4 #include "fileio.h"
5 #include "fs-util.h"
6 #include "log.h"
7 #include "resolved-etc-hosts.h"
8
9 static void test_parse_etc_hosts_system(void) {
10 _cleanup_fclose_ FILE *f = NULL;
11
12 f = fopen("/etc/hosts", "r");
13 if (!f) {
14 assert_se(errno == -ENOENT);
15 return;
16 }
17
18 _cleanup_(etc_hosts_free) EtcHosts hosts = {};
19 assert_se(etc_hosts_parse(&hosts, f) == 0);
20 }
21
22 static void test_parse_etc_hosts(const char *fname) {
23 _cleanup_(unlink_tempfilep) char
24 t[] = "/tmp/test-resolved-etc-hosts.XXXXXX";
25
26 int fd;
27 _cleanup_fclose_ FILE *f;
28
29 if (fname) {
30 f = fopen(fname, "r");
31 assert_se(f);
32 } else {
33 fd = mkostemp_safe(t);
34 assert_se(fd >= 0);
35
36 f = fdopen(fd, "r+");
37 fputs("1.2.3.4 some.where\n", f);
38 fputs("1.2.3.5 some.where\n", f);
39 fputs("::0 some.where some.other\n", f);
40 fputs("0.0.0.0 black.listed\n", f);
41 fputs("::5 some.where some.other foobar.foo.foo\n", f);
42 fputs(" \n", f);
43 fflush(f);
44 rewind(f);
45 }
46
47 _cleanup_(etc_hosts_free) EtcHosts hosts = {};
48 assert_se(etc_hosts_parse(&hosts, f) == 0);
49
50 if (fname)
51 return;
52
53 EtcHostsItemByName *bn;
54 assert_se(bn = hashmap_get(hosts.by_name, "some.where"));
55 assert_se(bn->n_addresses == 3);
56 assert_se(bn->n_allocated >= 3);
57
58 assert_se(bn->addresses[0]->family == AF_INET);
59 assert_se(memcmp(&bn->addresses[0]->address.in,
60 &(struct in_addr) { .s_addr = htobe32(0x01020304) }, 4) == 0);
61 assert_se(bn->addresses[1]->family == AF_INET);
62 assert_se(memcmp(&bn->addresses[1]->address.in,
63 &(struct in_addr) { .s_addr = htobe32(0x01020305) }, 4) == 0);
64 assert_se(bn->addresses[2]->family == AF_INET6);
65 assert_se(memcmp(&bn->addresses[2]->address.in6,
66 &(struct in6_addr) { .s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5} }, 16 ) == 0);
67
68 assert_se(bn = hashmap_get(hosts.by_name, "some.other"));
69 assert_se(bn->n_addresses == 1);
70 assert_se(bn->n_allocated >= 1);
71 assert_se(bn->addresses[0]->family == AF_INET6);
72 assert_se(memcmp(&bn->addresses[0]->address.in6,
73 &(struct in6_addr) { .s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5} }, 16 ) == 0);
74
75 assert_se( set_contains(hosts.no_address, "some.where"));
76 assert_se( set_contains(hosts.no_address, "some.other"));
77 assert_se( set_contains(hosts.no_address, "black.listed"));
78 assert_se(!set_contains(hosts.no_address, "foobar.foo.foo"));
79 }
80
81 int main(int argc, char **argv) {
82 log_set_max_level(LOG_DEBUG);
83 log_parse_environment();
84 log_open();
85
86 if (argc == 1)
87 test_parse_etc_hosts_system();
88 test_parse_etc_hosts(argv[1]);
89
90 return 0;
91 }