Debian Codegraph @

src/resolve/resolved-etc-hosts.c

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