]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/resolved-etc-hosts.c
TEST-21-DFUZZER: Fix script name
[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 <sys/types.h>
5 #include <unistd.h>
6
7 #include "fd-util.h"
8 #include "fileio.h"
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"
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
21 static EtcHostsItemByAddress *etc_hosts_item_by_address_free(EtcHostsItemByAddress *item) {
22 if (!item)
23 return NULL;
24
25 set_free(item->names);
26 return mfree(item);
27 }
28
29 DEFINE_TRIVIAL_CLEANUP_FUNC(EtcHostsItemByAddress*, etc_hosts_item_by_address_free);
30
31 DEFINE_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
39 static EtcHostsItemByName *etc_hosts_item_by_name_free(EtcHostsItemByName *item) {
40 if (!item)
41 return NULL;
42
43 free(item->name);
44 set_free(item->addresses);
45 return mfree(item);
46 }
47
48 DEFINE_TRIVIAL_CLEANUP_FUNC(EtcHostsItemByName*, etc_hosts_item_by_name_free);
49
50 DEFINE_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
58 void etc_hosts_clear(EtcHosts *hosts) {
59 assert(hosts);
60
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);
64 }
65
66 void manager_etc_hosts_flush(Manager *m) {
67 etc_hosts_clear(&m->etc_hosts);
68 m->etc_hosts_stat = (struct stat) {};
69 }
70
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 = {};
74 bool found = false;
75 EtcHostsItemByAddress *item;
76 int r;
77
78 assert(hosts);
79 assert(line);
80
81 r = extract_first_word(&line, &address_str, NULL, EXTRACT_RELAX);
82 if (r < 0)
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* */
85
86 r = in_addr_ifindex_from_string_auto(address_str, &address.family, &address.address, NULL);
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 }
91
92 r = in_addr_data_is_null(&address);
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 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 {
102 /* If this is a normal address, then simply add entry mapping it to the specified names */
103
104 item = hashmap_get(hosts->by_address, &address);
105 if (!item) {
106 _cleanup_(etc_hosts_item_by_address_freep) EtcHostsItemByAddress *new_item = NULL;
107
108 new_item = new(EtcHostsItemByAddress, 1);
109 if (!new_item)
110 return log_oom();
111
112 *new_item = (EtcHostsItemByAddress) {
113 .address = address,
114 };
115
116 r = hashmap_ensure_put(&hosts->by_address, &by_address_hash_ops, &new_item->address, new_item);
117 if (r < 0)
118 return log_oom();
119
120 item = TAKE_PTR(new_item);
121 }
122 }
123
124 for (;;) {
125 _cleanup_free_ char *name = NULL;
126 EtcHostsItemByName *bn;
127
128 r = extract_first_word(&line, &name, NULL, EXTRACT_RELAX);
129 if (r < 0)
130 return log_error_errno(r, "/etc/hosts:%u: couldn't extract hostname: %m", nr);
131 if (r == 0)
132 break;
133
134 r = dns_name_is_valid_ldh(name);
135 if (r <= 0) {
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);
140 continue;
141 }
142
143 found = true;
144
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
149 r = set_ensure_consume(&hosts->no_address, &dns_name_hash_ops_free, TAKE_PTR(name));
150 if (r < 0)
151 return log_oom();
152
153 continue;
154 }
155
156 bn = hashmap_get(hosts->by_name, name);
157 if (!bn) {
158 _cleanup_(etc_hosts_item_by_name_freep) EtcHostsItemByName *new_item = NULL;
159 _cleanup_free_ char *name_copy = NULL;
160
161 name_copy = strdup(name);
162 if (!name_copy)
163 return log_oom();
164
165 new_item = new(EtcHostsItemByName, 1);
166 if (!new_item)
167 return log_oom();
168
169 *new_item = (EtcHostsItemByName) {
170 .name = TAKE_PTR(name_copy),
171 };
172
173 r = hashmap_ensure_put(&hosts->by_name, &by_name_hash_ops, new_item->name, new_item);
174 if (r < 0)
175 return log_oom();
176
177 bn = TAKE_PTR(new_item);
178 }
179
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();
186
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
192 r = set_ensure_put(&item->names, &dns_name_hash_ops_free, name);
193 if (r < 0)
194 return log_oom();
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);
204 }
205
206 if (!found)
207 log_warning("/etc/hosts:%u: line is missing any valid hostnames", nr);
208
209 return 0;
210 }
211
212 static 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
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++) {
239 bool all_localhost, all_local_address;
240 EtcHostsItemByAddress *item;
241 const char *name;
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;
249 SET_FOREACH(name, item->names)
250 if (!is_localhost(name)) {
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. */
260 all_local_address = true;
261 SET_FOREACH(name, item->names) {
262 EtcHostsItemByName *n;
263 struct in_addr_data *a;
264
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 */
268 break;
269
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;
274 break;
275 }
276
277 if (!all_local_address)
278 break;
279 }
280
281 if (!all_local_address)
282 continue;
283
284 SET_FOREACH(name, item->names)
285 etc_hosts_item_by_name_free(hashmap_remove(hosts->by_name, name));
286
287 assert_se(hashmap_remove(hosts->by_address, local_in_addrs + j) == item);
288 etc_hosts_item_by_address_free(item);
289 }
290 }
291
292 int etc_hosts_parse(EtcHosts *hosts, FILE *f) {
293 _cleanup_(etc_hosts_clear) EtcHosts t = {};
294 unsigned nr = 0;
295 int r;
296
297 assert(hosts);
298
299 for (;;) {
300 _cleanup_free_ char *line = NULL;
301 char *l;
302
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
309 nr++;
310
311 l = strchr(line, '#');
312 if (l)
313 *l = '\0';
314
315 l = strstrip(line);
316 if (isempty(l))
317 continue;
318
319 r = parse_line(&t, nr, l);
320 if (r < 0)
321 return r;
322 }
323
324 strip_localhost(&t);
325
326 etc_hosts_clear(hosts);
327 *hosts = TAKE_STRUCT(t);
328 return 0;
329 }
330
331 static int manager_etc_hosts_read(Manager *m) {
332 _cleanup_fclose_ FILE *f = NULL;
333 struct stat st;
334 usec_t ts;
335 int r;
336
337 assert_se(sd_event_now(m->event, CLOCK_BOOTTIME, &ts) >= 0);
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
345 if (stat_is_set(&m->etc_hosts_stat)) {
346 if (stat("/etc/hosts", &st) < 0) {
347 if (errno != ENOENT)
348 return log_error_errno(errno, "Failed to stat /etc/hosts: %m");
349
350 manager_etc_hosts_flush(m);
351 return 0;
352 }
353
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))
356 return 0;
357 }
358
359 f = fopen("/etc/hosts", "re");
360 if (!f) {
361 if (errno != ENOENT)
362 return log_error_errno(errno, "Failed to open /etc/hosts: %m");
363
364 manager_etc_hosts_flush(m);
365 return 0;
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
374 r = etc_hosts_parse(&m->etc_hosts, f);
375 if (r < 0)
376 return r;
377
378 m->etc_hosts_stat = st;
379 m->etc_hosts_last = ts;
380
381 return 1;
382 }
383
384 static int answer_add_ptr(DnsAnswer *answer, DnsResourceKey *key, const char *name) {
385 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
386
387 rr = dns_resource_record_new(key);
388 if (!rr)
389 return -ENOMEM;
390
391 rr->ptr.name = strdup(name);
392 if (!rr->ptr.name)
393 return -ENOMEM;
394
395 return dns_answer_add(answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
396 }
397
398 static int answer_add_cname(DnsAnswer *answer, const char *name, const char *cname) {
399 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
400
401 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_CNAME, name);
402 if (!rr)
403 return -ENOMEM;
404
405 rr->cname.name = strdup(cname);
406 if (!rr->cname.name)
407 return -ENOMEM;
408
409 return dns_answer_add(answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
410 }
411
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;
414 int r;
415
416 r = dns_resource_record_new_address(&rr, a->family, &a->address, name);
417 if (r < 0)
418 return r;
419
420 return dns_answer_add(answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
421 }
422
423 static int etc_hosts_lookup_by_address(
424 EtcHosts *hosts,
425 DnsQuestion *q,
426 const char *name,
427 const struct in_addr_data *address,
428 DnsAnswer **answer) {
429
430 DnsResourceKey *t, *found_ptr = NULL;
431 EtcHostsItemByAddress *item;
432 int r;
433
434 assert(hosts);
435 assert(q);
436 assert(name);
437 assert(address);
438 assert(answer);
439
440 item = hashmap_get(hosts->by_address, address);
441 if (!item)
442 return 0;
443
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. */
446
447 DNS_QUESTION_FOREACH(t, q) {
448 if (!IN_SET(t->type, DNS_TYPE_PTR, DNS_TYPE_ANY))
449 continue;
450 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
451 continue;
452
453 r = dns_name_equal(dns_resource_key_name(t), name);
454 if (r < 0)
455 return r;
456 if (r > 0) {
457 found_ptr = t;
458 break;
459 }
460 }
461
462 if (found_ptr) {
463 const char *n;
464
465 r = dns_answer_reserve(answer, set_size(item->names));
466 if (r < 0)
467 return r;
468
469 if (item->canonical_name) {
470 r = answer_add_ptr(*answer, found_ptr, item->canonical_name);
471 if (r < 0)
472 return r;
473 }
474
475 SET_FOREACH(n, item->names) {
476 if (n == item->canonical_name)
477 continue;
478
479 r = answer_add_ptr(*answer, found_ptr, n);
480 if (r < 0)
481 return r;
482 }
483 }
484
485 return 1;
486 }
487
488 static int etc_hosts_lookup_by_name(
489 EtcHosts *hosts,
490 DnsQuestion *q,
491 const char *name,
492 DnsAnswer **answer) {
493
494 bool question_for_a = false, question_for_aaaa = false;
495 const struct in_addr_data *a;
496 EtcHostsItemByName *item;
497 DnsResourceKey *t;
498 int r;
499
500 assert(hosts);
501 assert(q);
502 assert(name);
503 assert(answer);
504
505 item = hashmap_get(hosts->by_name, name);
506 if (item) {
507 r = dns_answer_reserve(answer, set_size(item->addresses));
508 if (r < 0)
509 return r;
510 } else {
511 /* Check if name was listed with no address. If yes, continue to return an answer. */
512 if (!set_contains(hosts->no_address, name))
513 return 0;
514 }
515
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))
519 continue;
520 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
521 continue;
522
523 r = dns_name_equal(dns_resource_key_name(t), name);
524 if (r < 0)
525 return r;
526 if (r == 0)
527 continue;
528
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;
533
534 if (question_for_a && question_for_aaaa)
535 break; /* We are looking for both, no need to continue loop */
536 }
537
538 SET_FOREACH(a, item ? item->addresses : NULL) {
539 EtcHostsItemByAddress *item_by_addr;
540 const char *canonical_name;
541
542 if ((!question_for_a && a->family == AF_INET) ||
543 (!question_for_aaaa && a->family == AF_INET6))
544 continue;
545
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;
549 else
550 canonical_name = item->name;
551
552 if (!streq(item->name, canonical_name)) {
553 r = answer_add_cname(*answer, item->name, canonical_name);
554 if (r < 0)
555 return r;
556 }
557
558 r = answer_add_addr(*answer, canonical_name, a);
559 if (r < 0)
560 return r;
561 }
562
563 return true; /* We consider ourselves authoritative for the whole name, all RR types, not just A/AAAA */
564 }
565
566 int manager_etc_hosts_lookup(Manager *m, DnsQuestion *q, DnsAnswer **answer) {
567 struct in_addr_data k;
568 const char *name;
569
570 assert(m);
571 assert(q);
572 assert(answer);
573
574 if (!m->read_etc_hosts)
575 return 0;
576
577 (void) manager_etc_hosts_read(m);
578
579 name = dns_question_first_name(q);
580 if (!name)
581 return 0;
582
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);
585
586 return etc_hosts_lookup_by_name(&m->etc_hosts, q, name, answer);
587 }