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