]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/test-resolved-etc-hosts.c
Merge pull request #10992 from yuwata/follow-up-10948
[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 "fs-util.h"
5 #include "log.h"
6 #include "resolved-etc-hosts.h"
7 #include "tmpfile-util.h"
8
9 static void test_parse_etc_hosts_system(void) {
10 _cleanup_fclose_ FILE *f = NULL;
11
12 f = fopen("/etc/hosts", "re");
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, "re");
31 assert_se(f);
32 } else {
33 fd = mkostemp_safe(t);
34 assert_se(fd >= 0);
35
36 f = fdopen(fd, "r+");
37 assert_se(f);
38 fputs("1.2.3.4 some.where\n", f);
39 fputs("1.2.3.5 some.where\n", f);
40 fputs("::0 some.where some.other\n", f);
41 fputs("0.0.0.0 black.listed\n", f);
42 fputs("::5 some.where some.other foobar.foo.foo\n", f);
43 fputs(" \n", f);
44 fflush(f);
45 rewind(f);
46 }
47
48 _cleanup_(etc_hosts_free) EtcHosts hosts = {};
49 assert_se(etc_hosts_parse(&hosts, f) == 0);
50
51 if (fname)
52 return;
53
54 EtcHostsItemByName *bn;
55 assert_se(bn = hashmap_get(hosts.by_name, "some.where"));
56 assert_se(bn->n_addresses == 3);
57 assert_se(bn->n_allocated >= 3);
58
59 assert_se(bn->addresses[0]->family == AF_INET);
60 assert_se(memcmp(&bn->addresses[0]->address.in,
61 &(struct in_addr) { .s_addr = htobe32(0x01020304) }, 4) == 0);
62 assert_se(bn->addresses[1]->family == AF_INET);
63 assert_se(memcmp(&bn->addresses[1]->address.in,
64 &(struct in_addr) { .s_addr = htobe32(0x01020305) }, 4) == 0);
65 assert_se(bn->addresses[2]->family == AF_INET6);
66 assert_se(memcmp(&bn->addresses[2]->address.in6,
67 &(struct in6_addr) { .s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5} }, 16 ) == 0);
68
69 assert_se(bn = hashmap_get(hosts.by_name, "some.other"));
70 assert_se(bn->n_addresses == 1);
71 assert_se(bn->n_allocated >= 1);
72 assert_se(bn->addresses[0]->family == AF_INET6);
73 assert_se(memcmp(&bn->addresses[0]->address.in6,
74 &(struct in6_addr) { .s6_addr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5} }, 16 ) == 0);
75
76 assert_se( set_contains(hosts.no_address, "some.where"));
77 assert_se( set_contains(hosts.no_address, "some.other"));
78 assert_se( set_contains(hosts.no_address, "black.listed"));
79 assert_se(!set_contains(hosts.no_address, "foobar.foo.foo"));
80 }
81
82 int main(int argc, char **argv) {
83 log_set_max_level(LOG_DEBUG);
84 log_parse_environment();
85 log_open();
86
87 if (argc == 1)
88 test_parse_etc_hosts_system();
89 test_parse_etc_hosts(argv[1]);
90
91 return 0;
92 }