]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/resolve/resolved-etc-hosts.c
bus: Use OrderedSet for introspection
[thirdparty/systemd.git] / src / resolve / resolved-etc-hosts.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
dd0bc0f1 2
ca78ad1d
ZJS
3#include <sys/stat.h>
4#include <sys/types.h>
5#include <unistd.h>
6
dd0bc0f1
LP
7#include "fd-util.h"
8#include "fileio.h"
9#include "hostname-util.h"
dd0bc0f1 10#include "resolved-dns-synthesize.h"
7c777a77 11#include "resolved-etc-hosts.h"
5c3fa98d 12#include "socket-netlink.h"
36d892b7 13#include "stat-util.h"
dd0bc0f1
LP
14#include "string-util.h"
15#include "strv.h"
16#include "time-util.h"
17
18/* Recheck /etc/hosts at most once every 2s */
19#define ETC_HOSTS_RECHECK_USEC (2*USEC_PER_SEC)
20
a1e92eee 21static void etc_hosts_item_free(EtcHostsItem *item) {
37b7cc8d
ZJS
22 strv_free(item->names);
23 free(item);
24}
dd0bc0f1 25
a1e92eee 26static void etc_hosts_item_by_name_free(EtcHostsItemByName *item) {
37b7cc8d
ZJS
27 free(item->name);
28 free(item->addresses);
29 free(item);
30}
dd0bc0f1 31
78fc21a1 32void etc_hosts_free(EtcHosts *hosts) {
37b7cc8d
ZJS
33 hosts->by_address = hashmap_free_with_destructor(hosts->by_address, etc_hosts_item_free);
34 hosts->by_name = hashmap_free_with_destructor(hosts->by_name, etc_hosts_item_by_name_free);
fd373593 35 hosts->no_address = set_free_free(hosts->no_address);
37b7cc8d 36}
dd0bc0f1 37
37b7cc8d
ZJS
38void manager_etc_hosts_flush(Manager *m) {
39 etc_hosts_free(&m->etc_hosts);
36d892b7 40 m->etc_hosts_stat = (struct stat) {};
dd0bc0f1
LP
41}
42
37b7cc8d 43static int parse_line(EtcHosts *hosts, unsigned nr, const char *line) {
0351eb11
YW
44 _cleanup_free_ char *address_str = NULL;
45 struct in_addr_data address = {};
fd373593 46 bool found = false;
dd0bc0f1 47 EtcHostsItem *item;
dd0bc0f1
LP
48 int r;
49
37b7cc8d 50 assert(hosts);
0351eb11 51 assert(line);
dd0bc0f1 52
0351eb11
YW
53 r = extract_first_word(&line, &address_str, NULL, EXTRACT_RELAX);
54 if (r < 0)
bd005277
ZJS
55 return log_error_errno(r, "/etc/hosts:%u: failed to extract address: %m", nr);
56 assert(r > 0); /* We already checked that the line is not empty, so it should contain *something* */
0351eb11 57
7bf8c3de 58 r = in_addr_ifindex_from_string_auto(address_str, &address.family, &address.address, NULL);
bd005277
ZJS
59 if (r < 0) {
60 log_warning_errno(r, "/etc/hosts:%u: address '%s' is invalid, ignoring: %m", nr, address_str);
61 return 0;
62 }
0351eb11 63
94876904 64 r = in_addr_data_is_null(&address);
bd005277
ZJS
65 if (r < 0) {
66 log_warning_errno(r, "/etc/hosts:%u: address '%s' is invalid, ignoring: %m", nr, address_str);
67 return 0;
68 }
dd0bc0f1
LP
69 if (r > 0)
70 /* This is an 0.0.0.0 or :: item, which we assume means that we shall map the specified hostname to
71 * nothing. */
72 item = NULL;
73 else {
78fc21a1 74 /* If this is a normal address, then simply add entry mapping it to the specified names */
dd0bc0f1 75
37b7cc8d 76 item = hashmap_get(hosts->by_address, &address);
0351eb11 77 if (!item) {
37b7cc8d 78 r = hashmap_ensure_allocated(&hosts->by_address, &in_addr_data_hash_ops);
dd0bc0f1
LP
79 if (r < 0)
80 return log_oom();
81
1ed31408 82 item = new(EtcHostsItem, 1);
dd0bc0f1
LP
83 if (!item)
84 return log_oom();
85
1ed31408
LP
86 *item = (EtcHostsItem) {
87 .address = address,
88 };
dd0bc0f1 89
37b7cc8d 90 r = hashmap_put(hosts->by_address, &item->address, item);
dd0bc0f1
LP
91 if (r < 0) {
92 free(item);
93 return log_oom();
94 }
95 }
96 }
97
0351eb11
YW
98 for (;;) {
99 _cleanup_free_ char *name = NULL;
dd0bc0f1
LP
100 EtcHostsItemByName *bn;
101
0351eb11
YW
102 r = extract_first_word(&line, &name, NULL, EXTRACT_RELAX);
103 if (r < 0)
38b38500 104 return log_error_errno(r, "/etc/hosts:%u: couldn't extract hostname: %m", nr);
0351eb11
YW
105 if (r == 0)
106 break;
107
fd373593
ZJS
108 found = true;
109
7470cc4c 110 r = dns_name_is_valid_ldh(name);
bd005277
ZJS
111 if (r <= 0) {
112 log_warning_errno(r, "/etc/hosts:%u: hostname \"%s\" is not valid, ignoring.", nr, name);
113 continue;
114 }
115
fd373593
ZJS
116 if (!item) {
117 /* Optimize the case where we don't need to store any addresses, by storing
118 * only the name in a dedicated Set instead of the hashmap */
119
ab9dd0b9 120 r = set_ensure_consume(&hosts->no_address, &dns_name_hash_ops, TAKE_PTR(name));
fd373593
ZJS
121 if (r < 0)
122 return r;
123
fd373593 124 continue;
0351eb11
YW
125 }
126
fd373593
ZJS
127 r = strv_extend(&item->names, name);
128 if (r < 0)
129 return log_oom();
130
37b7cc8d 131 bn = hashmap_get(hosts->by_name, name);
dd0bc0f1 132 if (!bn) {
37b7cc8d 133 r = hashmap_ensure_allocated(&hosts->by_name, &dns_name_hash_ops);
dd0bc0f1
LP
134 if (r < 0)
135 return log_oom();
136
137 bn = new0(EtcHostsItemByName, 1);
138 if (!bn)
139 return log_oom();
140
37b7cc8d 141 r = hashmap_put(hosts->by_name, name, bn);
dd0bc0f1 142 if (r < 0) {
dd0bc0f1
LP
143 free(bn);
144 return log_oom();
145 }
0351eb11
YW
146
147 bn->name = TAKE_PTR(name);
dd0bc0f1
LP
148 }
149
319a4f4b 150 if (!GREEDY_REALLOC(bn->addresses, bn->n_addresses + 1))
fd373593 151 return log_oom();
dd0bc0f1 152
fd373593 153 bn->addresses[bn->n_addresses++] = &item->address;
dd0bc0f1
LP
154 }
155
baaa35ad 156 if (!found)
38b38500 157 log_warning("/etc/hosts:%u: line is missing any hostnames", nr);
dd0bc0f1 158
0351eb11 159 return 0;
dd0bc0f1
LP
160}
161
9ca875e8
LP
162static void strip_localhost(EtcHosts *hosts) {
163 static const struct in_addr_data local_in_addrs[] = {
164 {
165 .family = AF_INET,
166#if __BYTE_ORDER == __LITTLE_ENDIAN
167 /* We want constant expressions here, that's why we don't use htole32() here */
168 .address.in.s_addr = UINT32_C(0x0100007F),
169#else
170 .address.in.s_addr = UINT32_C(0x7F000001),
171#endif
172 },
173 {
174 .family = AF_INET6,
175 .address.in6 = IN6ADDR_LOOPBACK_INIT,
176 },
177 };
178
179 EtcHostsItem *item;
180
181 assert(hosts);
182
183 /* Removes the 'localhost' entry from what we loaded. But only if the mapping is exclusively between
184 * 127.0.0.1 and localhost (or aliases to that we recognize). If there's any other name assigned to
185 * it, we leave the entry in.
186 *
187 * This way our regular synthesizing can take over, but only if it would result in the exact same
188 * mappings. */
189
190 for (size_t j = 0; j < ELEMENTSOF(local_in_addrs); j++) {
191 bool all_localhost, in_order;
192 char **i;
193
194 item = hashmap_get(hosts->by_address, local_in_addrs + j);
195 if (!item)
196 continue;
197
198 /* Check whether all hostnames the loopback address points to are localhost ones */
199 all_localhost = true;
200 STRV_FOREACH(i, item->names)
201 if (!is_localhost(*i)) {
202 all_localhost = false;
203 break;
204 }
205
206 if (!all_localhost) /* Not all names are localhost, hence keep the entries for this address. */
207 continue;
208
209 /* Now check if the names listed for this address actually all point back just to this
210 * address (or the other loopback address). If not, let's stay away from this too. */
211 in_order = true;
212 STRV_FOREACH(i, item->names) {
213 EtcHostsItemByName *n;
214 bool all_local_address;
215
216 n = hashmap_get(hosts->by_name, *i);
217 if (!n) /* No reverse entry? Then almost certainly the entry already got deleted from
218 * the previous iteration of this loop, i.e. via the other protocol */
219 break;
220
221 /* Now check if the addresses of this item are all localhost addresses */
222 all_local_address = true;
223 for (size_t m = 0; m < n->n_addresses; m++)
224 if (!in_addr_is_localhost(n->addresses[m]->family, &n->addresses[m]->address)) {
225 all_local_address = false;
226 break;
227 }
228
229 if (!all_local_address) {
230 in_order = false;
231 break;
232 }
233 }
234
235 if (!in_order)
236 continue;
237
238 STRV_FOREACH(i, item->names) {
239 EtcHostsItemByName *n;
240
241 n = hashmap_remove(hosts->by_name, *i);
242 if (n)
243 etc_hosts_item_by_name_free(n);
244 }
245
246 assert_se(hashmap_remove(hosts->by_address, local_in_addrs + j) == item);
247 etc_hosts_item_free(item);
248 }
249}
250
78fc21a1 251int etc_hosts_parse(EtcHosts *hosts, FILE *f) {
37b7cc8d 252 _cleanup_(etc_hosts_free) EtcHosts t = {};
37b7cc8d
ZJS
253 unsigned nr = 0;
254 int r;
255
7c777a77
LP
256 for (;;) {
257 _cleanup_free_ char *line = NULL;
37b7cc8d
ZJS
258 char *l;
259
7c777a77
LP
260 r = read_line(f, LONG_LINE_MAX, &line);
261 if (r < 0)
262 return log_error_errno(r, "Failed to read /etc/hosts: %m");
263 if (r == 0)
264 break;
265
37b7cc8d
ZJS
266 nr++;
267
bd005277
ZJS
268 l = strchr(line, '#');
269 if (l)
270 *l = '\0';
271
37b7cc8d
ZJS
272 l = strstrip(line);
273 if (isempty(l))
274 continue;
37b7cc8d
ZJS
275
276 r = parse_line(&t, nr, l);
277 if (r < 0)
278 return r;
279 }
280
9ca875e8
LP
281 strip_localhost(&t);
282
be19cdf3 283 etc_hosts_free(hosts);
37b7cc8d
ZJS
284 *hosts = t;
285 t = (EtcHosts) {}; /* prevent cleanup */
286 return 0;
287}
288
452ca091 289static int manager_etc_hosts_read(Manager *m) {
dd0bc0f1 290 _cleanup_fclose_ FILE *f = NULL;
dd0bc0f1
LP
291 struct stat st;
292 usec_t ts;
dd0bc0f1
LP
293 int r;
294
295 assert_se(sd_event_now(m->event, clock_boottime_or_monotonic(), &ts) >= 0);
296
297 /* See if we checked /etc/hosts recently already */
298 if (m->etc_hosts_last != USEC_INFINITY && m->etc_hosts_last + ETC_HOSTS_RECHECK_USEC > ts)
299 return 0;
300
301 m->etc_hosts_last = ts;
302
36d892b7 303 if (m->etc_hosts_stat.st_mode != 0) {
dd0bc0f1 304 if (stat("/etc/hosts", &st) < 0) {
37b7cc8d
ZJS
305 if (errno != ENOENT)
306 return log_error_errno(errno, "Failed to stat /etc/hosts: %m");
dd0bc0f1 307
37b7cc8d
ZJS
308 manager_etc_hosts_flush(m);
309 return 0;
dd0bc0f1
LP
310 }
311
aa5408e2 312 /* Did the mtime or ino/dev change? If not, there's no point in re-reading the file. */
36d892b7 313 if (stat_inode_unmodified(&m->etc_hosts_stat, &st))
dd0bc0f1
LP
314 return 0;
315 }
316
317 f = fopen("/etc/hosts", "re");
318 if (!f) {
37b7cc8d
ZJS
319 if (errno != ENOENT)
320 return log_error_errno(errno, "Failed to open /etc/hosts: %m");
dd0bc0f1 321
37b7cc8d
ZJS
322 manager_etc_hosts_flush(m);
323 return 0;
dd0bc0f1
LP
324 }
325
326 /* Take the timestamp at the beginning of processing, so that any changes made later are read on the next
327 * invocation */
328 r = fstat(fileno(f), &st);
329 if (r < 0)
330 return log_error_errno(errno, "Failed to fstat() /etc/hosts: %m");
331
37b7cc8d 332 r = etc_hosts_parse(&m->etc_hosts, f);
be19cdf3 333 if (r < 0)
37b7cc8d 334 return r;
dd0bc0f1 335
36d892b7 336 m->etc_hosts_stat = st;
dd0bc0f1
LP
337 m->etc_hosts_last = ts;
338
339 return 1;
dd0bc0f1
LP
340}
341
342int manager_etc_hosts_lookup(Manager *m, DnsQuestion* q, DnsAnswer **answer) {
343 bool found_a = false, found_aaaa = false;
0351eb11 344 struct in_addr_data k = {};
dd0bc0f1 345 EtcHostsItemByName *bn;
dd0bc0f1
LP
346 DnsResourceKey *t;
347 const char *name;
348 unsigned i;
349 int r;
350
351 assert(m);
352 assert(q);
353 assert(answer);
354
86317087
YW
355 if (!m->read_etc_hosts)
356 return 0;
357
be19cdf3 358 (void) manager_etc_hosts_read(m);
dd0bc0f1
LP
359
360 name = dns_question_first_name(q);
361 if (!name)
362 return 0;
363
364 r = dns_name_address(name, &k.family, &k.address);
365 if (r > 0) {
366 EtcHostsItem *item;
367 DnsResourceKey *found_ptr = NULL;
368
37b7cc8d 369 item = hashmap_get(m->etc_hosts.by_address, &k);
dd0bc0f1
LP
370 if (!item)
371 return 0;
372
373 /* We have an address in /etc/hosts that matches the queried name. Let's return successful. Actual data
374 * we'll only return if the request was for PTR. */
375
376 DNS_QUESTION_FOREACH(t, q) {
377 if (!IN_SET(t->type, DNS_TYPE_PTR, DNS_TYPE_ANY))
378 continue;
379 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
380 continue;
381
1c02e7ba 382 r = dns_name_equal(dns_resource_key_name(t), name);
dd0bc0f1
LP
383 if (r < 0)
384 return r;
385 if (r > 0) {
386 found_ptr = t;
387 break;
388 }
389 }
390
391 if (found_ptr) {
392 char **n;
393
394 r = dns_answer_reserve(answer, strv_length(item->names));
395 if (r < 0)
396 return r;
397
398 STRV_FOREACH(n, item->names) {
399 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
400
401 rr = dns_resource_record_new(found_ptr);
402 if (!rr)
403 return -ENOMEM;
404
405 rr->ptr.name = strdup(*n);
406 if (!rr->ptr.name)
407 return -ENOMEM;
408
04617bf8 409 r = dns_answer_add(*answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
dd0bc0f1
LP
410 if (r < 0)
411 return r;
412 }
413 }
414
415 return 1;
416 }
417
37b7cc8d 418 bn = hashmap_get(m->etc_hosts.by_name, name);
fd373593
ZJS
419 if (bn) {
420 r = dns_answer_reserve(answer, bn->n_addresses);
421 if (r < 0)
422 return r;
423 } else {
424 /* Check if name was listed with no address. If yes, continue to return an answer. */
425 if (!set_contains(m->etc_hosts.no_address, name))
426 return 0;
427 }
dd0bc0f1
LP
428
429 DNS_QUESTION_FOREACH(t, q) {
430 if (!IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_AAAA, DNS_TYPE_ANY))
431 continue;
432 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
433 continue;
434
1c02e7ba 435 r = dns_name_equal(dns_resource_key_name(t), name);
dd0bc0f1
LP
436 if (r < 0)
437 return r;
438 if (r == 0)
439 continue;
440
441 if (IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_ANY))
442 found_a = true;
443 if (IN_SET(t->type, DNS_TYPE_AAAA, DNS_TYPE_ANY))
444 found_aaaa = true;
445
446 if (found_a && found_aaaa)
447 break;
448 }
449
fd373593 450 for (i = 0; bn && i < bn->n_addresses; i++) {
dd0bc0f1
LP
451 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
452
0351eb11
YW
453 if ((!found_a && bn->addresses[i]->family == AF_INET) ||
454 (!found_aaaa && bn->addresses[i]->family == AF_INET6))
dd0bc0f1
LP
455 continue;
456
0351eb11 457 r = dns_resource_record_new_address(&rr, bn->addresses[i]->family, &bn->addresses[i]->address, bn->name);
dd0bc0f1
LP
458 if (r < 0)
459 return r;
460
04617bf8 461 r = dns_answer_add(*answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
dd0bc0f1
LP
462 if (r < 0)
463 return r;
464 }
465
4050e04b 466 return found_a || found_aaaa;
dd0bc0f1 467}