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