1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "hostname-util.h"
10 #include "resolved-dns-synthesize.h"
11 #include "resolved-etc-hosts.h"
12 #include "socket-netlink.h"
13 #include "stat-util.h"
14 #include "string-util.h"
16 #include "time-util.h"
18 /* Recheck /etc/hosts at most once every 2s */
19 #define ETC_HOSTS_RECHECK_USEC (2*USEC_PER_SEC)
21 static EtcHostsItemByAddress
*etc_hosts_item_by_address_free(EtcHostsItemByAddress
*item
) {
25 set_free(item
->names
);
29 DEFINE_TRIVIAL_CLEANUP_FUNC(EtcHostsItemByAddress
*, etc_hosts_item_by_address_free
);
31 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
34 in_addr_data_hash_func
,
35 in_addr_data_compare_func
,
36 EtcHostsItemByAddress
,
37 etc_hosts_item_by_address_free
);
39 static EtcHostsItemByName
*etc_hosts_item_by_name_free(EtcHostsItemByName
*item
) {
44 set_free(item
->addresses
);
48 DEFINE_TRIVIAL_CLEANUP_FUNC(EtcHostsItemByName
*, etc_hosts_item_by_name_free
);
50 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
54 dns_name_compare_func
,
56 etc_hosts_item_by_name_free
);
58 void etc_hosts_clear(EtcHosts
*hosts
) {
61 hosts
->by_address
= hashmap_free(hosts
->by_address
);
62 hosts
->by_name
= hashmap_free(hosts
->by_name
);
63 hosts
->no_address
= set_free(hosts
->no_address
);
66 void manager_etc_hosts_flush(Manager
*m
) {
67 etc_hosts_clear(&m
->etc_hosts
);
68 m
->etc_hosts_stat
= (struct stat
) {};
71 static int parse_line(EtcHosts
*hosts
, unsigned nr
, const char *line
) {
72 _cleanup_free_
char *address_str
= NULL
;
73 struct in_addr_data address
= {};
75 EtcHostsItemByAddress
*item
;
81 r
= extract_first_word(&line
, &address_str
, NULL
, EXTRACT_RELAX
);
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* */
86 r
= in_addr_ifindex_from_string_auto(address_str
, &address
.family
, &address
.address
, NULL
);
88 log_warning_errno(r
, "/etc/hosts:%u: address '%s' is invalid, ignoring: %m", nr
, address_str
);
92 r
= in_addr_data_is_null(&address
);
94 log_warning_errno(r
, "/etc/hosts:%u: address '%s' is invalid, ignoring: %m", nr
, address_str
);
98 /* This is an 0.0.0.0 or :: item, which we assume means that we shall map the specified hostname to
102 /* If this is a normal address, then simply add entry mapping it to the specified names */
104 item
= hashmap_get(hosts
->by_address
, &address
);
106 _cleanup_(etc_hosts_item_by_address_freep
) EtcHostsItemByAddress
*new_item
= NULL
;
108 new_item
= new(EtcHostsItemByAddress
, 1);
112 *new_item
= (EtcHostsItemByAddress
) {
116 r
= hashmap_ensure_put(&hosts
->by_address
, &by_address_hash_ops
, &new_item
->address
, new_item
);
120 item
= TAKE_PTR(new_item
);
125 _cleanup_free_
char *name
= NULL
;
126 EtcHostsItemByName
*bn
;
128 r
= extract_first_word(&line
, &name
, NULL
, EXTRACT_RELAX
);
130 return log_error_errno(r
, "/etc/hosts:%u: couldn't extract hostname: %m", nr
);
134 r
= dns_name_is_valid_ldh(name
);
137 log_warning_errno(r
, "/etc/hosts:%u: Failed to check the validity of hostname \"%s\", ignoring: %m", nr
, name
);
139 log_warning("/etc/hosts:%u: hostname \"%s\" is not valid, ignoring.", nr
, name
);
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 */
149 r
= set_ensure_consume(&hosts
->no_address
, &dns_name_hash_ops_free
, TAKE_PTR(name
));
156 bn
= hashmap_get(hosts
->by_name
, name
);
158 _cleanup_(etc_hosts_item_by_name_freep
) EtcHostsItemByName
*new_item
= NULL
;
159 _cleanup_free_
char *name_copy
= NULL
;
161 name_copy
= strdup(name
);
165 new_item
= new(EtcHostsItemByName
, 1);
169 *new_item
= (EtcHostsItemByName
) {
170 .name
= TAKE_PTR(name_copy
),
173 r
= hashmap_ensure_put(&hosts
->by_name
, &by_name_hash_ops
, new_item
->name
, new_item
);
177 bn
= TAKE_PTR(new_item
);
180 if (!set_contains(bn
->addresses
, &address
)) {
181 _cleanup_free_
struct in_addr_data
*address_copy
= NULL
;
183 address_copy
= newdup(struct in_addr_data
, &address
, 1);
187 r
= set_ensure_consume(&bn
->addresses
, &in_addr_data_hash_ops_free
, TAKE_PTR(address_copy
));
192 r
= set_ensure_put(&item
->names
, &dns_name_hash_ops_free
, name
);
195 if (r
== 0) /* the name is already listed */
198 * Keep track of the first name listed for this address.
199 * This name will be used in responses as the canonical name.
201 if (!item
->canonical_name
)
202 item
->canonical_name
= name
;
207 log_warning("/etc/hosts:%u: line is missing any valid hostnames", nr
);
212 static void strip_localhost(EtcHosts
*hosts
) {
213 static const struct in_addr_data local_in_addrs
[] = {
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),
220 .address
.in
.s_addr
= UINT32_C(0x7F000001),
225 .address
.in6
= IN6ADDR_LOOPBACK_INIT
,
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.
235 * This way our regular synthesizing can take over, but only if it would result in the exact same
238 for (size_t j
= 0; j
< ELEMENTSOF(local_in_addrs
); j
++) {
239 bool all_localhost
, all_local_address
;
240 EtcHostsItemByAddress
*item
;
243 item
= hashmap_get(hosts
->by_address
, local_in_addrs
+ j
);
247 /* Check whether all hostnames the loopback address points to are localhost ones */
248 all_localhost
= true;
249 SET_FOREACH(name
, item
->names
)
250 if (!is_localhost(name
)) {
251 all_localhost
= false;
255 if (!all_localhost
) /* Not all names are localhost, hence keep the entries for this address. */
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. */
260 all_local_address
= true;
261 SET_FOREACH(name
, item
->names
) {
262 EtcHostsItemByName
*n
;
263 struct in_addr_data
*a
;
265 n
= hashmap_get(hosts
->by_name
, name
);
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 */
270 /* Now check if the addresses of this item are all localhost addresses */
271 SET_FOREACH(a
, n
->addresses
)
272 if (!in_addr_is_localhost(a
->family
, &a
->address
)) {
273 all_local_address
= false;
277 if (!all_local_address
)
281 if (!all_local_address
)
284 SET_FOREACH(name
, item
->names
)
285 etc_hosts_item_by_name_free(hashmap_remove(hosts
->by_name
, name
));
287 assert_se(hashmap_remove(hosts
->by_address
, local_in_addrs
+ j
) == item
);
288 etc_hosts_item_by_address_free(item
);
292 int etc_hosts_parse(EtcHosts
*hosts
, FILE *f
) {
293 _cleanup_(etc_hosts_clear
) EtcHosts t
= {};
300 _cleanup_free_
char *line
= NULL
;
303 r
= read_line(f
, LONG_LINE_MAX
, &line
);
305 return log_error_errno(r
, "Failed to read /etc/hosts: %m");
311 l
= strchr(line
, '#');
319 r
= parse_line(&t
, nr
, l
);
326 etc_hosts_clear(hosts
);
327 *hosts
= TAKE_STRUCT(t
);
331 static int manager_etc_hosts_read(Manager
*m
) {
332 _cleanup_fclose_
FILE *f
= NULL
;
337 assert_se(sd_event_now(m
->event
, CLOCK_BOOTTIME
, &ts
) >= 0);
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
)
343 m
->etc_hosts_last
= ts
;
345 if (stat_is_set(&m
->etc_hosts_stat
)) {
346 if (stat("/etc/hosts", &st
) < 0) {
348 return log_error_errno(errno
, "Failed to stat /etc/hosts: %m");
350 manager_etc_hosts_flush(m
);
354 /* Did the mtime or ino/dev change? If not, there's no point in re-reading the file. */
355 if (stat_inode_unmodified(&m
->etc_hosts_stat
, &st
))
359 f
= fopen("/etc/hosts", "re");
362 return log_error_errno(errno
, "Failed to open /etc/hosts: %m");
364 manager_etc_hosts_flush(m
);
368 /* Take the timestamp at the beginning of processing, so that any changes made later are read on the next
370 r
= fstat(fileno(f
), &st
);
372 return log_error_errno(errno
, "Failed to fstat() /etc/hosts: %m");
374 r
= etc_hosts_parse(&m
->etc_hosts
, f
);
378 m
->etc_hosts_stat
= st
;
379 m
->etc_hosts_last
= ts
;
384 static int answer_add_ptr(DnsAnswer
*answer
, DnsResourceKey
*key
, const char *name
) {
385 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*rr
= NULL
;
387 rr
= dns_resource_record_new(key
);
391 rr
->ptr
.name
= strdup(name
);
395 return dns_answer_add(answer
, rr
, 0, DNS_ANSWER_AUTHENTICATED
, NULL
);
398 static int answer_add_cname(DnsAnswer
*answer
, const char *name
, const char *cname
) {
399 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*rr
= NULL
;
401 rr
= dns_resource_record_new_full(DNS_CLASS_IN
, DNS_TYPE_CNAME
, name
);
405 rr
->cname
.name
= strdup(cname
);
409 return dns_answer_add(answer
, rr
, 0, DNS_ANSWER_AUTHENTICATED
, NULL
);
412 static int answer_add_addr(DnsAnswer
*answer
, const char *name
, const struct in_addr_data
*a
) {
413 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*rr
= NULL
;
416 r
= dns_resource_record_new_address(&rr
, a
->family
, &a
->address
, name
);
420 return dns_answer_add(answer
, rr
, 0, DNS_ANSWER_AUTHENTICATED
, NULL
);
423 static int etc_hosts_lookup_by_address(
427 const struct in_addr_data
*address
,
428 DnsAnswer
**answer
) {
430 DnsResourceKey
*t
, *found_ptr
= NULL
;
431 EtcHostsItemByAddress
*item
;
440 item
= hashmap_get(hosts
->by_address
, address
);
444 /* We have an address in /etc/hosts that matches the queried name. Let's return successful. Actual data
445 * we'll only return if the request was for PTR. */
447 DNS_QUESTION_FOREACH(t
, q
) {
448 if (!IN_SET(t
->type
, DNS_TYPE_PTR
, DNS_TYPE_ANY
))
450 if (!IN_SET(t
->class, DNS_CLASS_IN
, DNS_CLASS_ANY
))
453 r
= dns_name_equal(dns_resource_key_name(t
), name
);
465 r
= dns_answer_reserve(answer
, set_size(item
->names
));
469 if (item
->canonical_name
) {
470 r
= answer_add_ptr(*answer
, found_ptr
, item
->canonical_name
);
475 SET_FOREACH(n
, item
->names
) {
476 if (n
== item
->canonical_name
)
479 r
= answer_add_ptr(*answer
, found_ptr
, n
);
488 static int etc_hosts_lookup_by_name(
492 DnsAnswer
**answer
) {
494 bool question_for_a
= false, question_for_aaaa
= false;
495 const struct in_addr_data
*a
;
496 EtcHostsItemByName
*item
;
505 item
= hashmap_get(hosts
->by_name
, name
);
507 r
= dns_answer_reserve(answer
, set_size(item
->addresses
));
511 /* Check if name was listed with no address. If yes, continue to return an answer. */
512 if (!set_contains(hosts
->no_address
, name
))
516 /* Determine whether we are looking for A and/or AAAA RRs */
517 DNS_QUESTION_FOREACH(t
, q
) {
518 if (!IN_SET(t
->type
, DNS_TYPE_A
, DNS_TYPE_AAAA
, DNS_TYPE_ANY
))
520 if (!IN_SET(t
->class, DNS_CLASS_IN
, DNS_CLASS_ANY
))
523 r
= dns_name_equal(dns_resource_key_name(t
), name
);
529 if (IN_SET(t
->type
, DNS_TYPE_A
, DNS_TYPE_ANY
))
530 question_for_a
= true;
531 if (IN_SET(t
->type
, DNS_TYPE_AAAA
, DNS_TYPE_ANY
))
532 question_for_aaaa
= true;
534 if (question_for_a
&& question_for_aaaa
)
535 break; /* We are looking for both, no need to continue loop */
538 SET_FOREACH(a
, item
? item
->addresses
: NULL
) {
539 EtcHostsItemByAddress
*item_by_addr
;
540 const char *canonical_name
;
542 if ((!question_for_a
&& a
->family
== AF_INET
) ||
543 (!question_for_aaaa
&& a
->family
== AF_INET6
))
546 item_by_addr
= hashmap_get(hosts
->by_address
, a
);
547 if (item_by_addr
&& item_by_addr
->canonical_name
)
548 canonical_name
= item_by_addr
->canonical_name
;
550 canonical_name
= item
->name
;
552 if (!streq(item
->name
, canonical_name
)) {
553 r
= answer_add_cname(*answer
, item
->name
, canonical_name
);
558 r
= answer_add_addr(*answer
, canonical_name
, a
);
563 return true; /* We consider ourselves authoritative for the whole name, all RR types, not just A/AAAA */
566 int manager_etc_hosts_lookup(Manager
*m
, DnsQuestion
*q
, DnsAnswer
**answer
) {
567 struct in_addr_data k
;
574 if (!m
->read_etc_hosts
)
577 (void) manager_etc_hosts_read(m
);
579 name
= dns_question_first_name(q
);
583 if (dns_name_address(name
, &k
.family
, &k
.address
) > 0)
584 return etc_hosts_lookup_by_address(&m
->etc_hosts
, q
, name
, &k
, answer
);
586 return etc_hosts_lookup_by_name(&m
->etc_hosts
, q
, name
, answer
);