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