]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/resolved-etc-hosts.c
Merge pull request #27113 from keszybz/variable-expansion-rework
[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_consume(&item->names, &dns_name_hash_ops_free, TAKE_PTR(name));
193 if (r < 0)
194 return log_oom();
195 }
196
197 if (!found)
198 log_warning("/etc/hosts:%u: line is missing any valid hostnames", nr);
199
200 return 0;
201 }
202
203 static void strip_localhost(EtcHosts *hosts) {
204 static const struct in_addr_data local_in_addrs[] = {
205 {
206 .family = AF_INET,
207 #if __BYTE_ORDER == __LITTLE_ENDIAN
208 /* We want constant expressions here, that's why we don't use htole32() here */
209 .address.in.s_addr = UINT32_C(0x0100007F),
210 #else
211 .address.in.s_addr = UINT32_C(0x7F000001),
212 #endif
213 },
214 {
215 .family = AF_INET6,
216 .address.in6 = IN6ADDR_LOOPBACK_INIT,
217 },
218 };
219
220 assert(hosts);
221
222 /* Removes the 'localhost' entry from what we loaded. But only if the mapping is exclusively between
223 * 127.0.0.1 and localhost (or aliases to that we recognize). If there's any other name assigned to
224 * it, we leave the entry in.
225 *
226 * This way our regular synthesizing can take over, but only if it would result in the exact same
227 * mappings. */
228
229 for (size_t j = 0; j < ELEMENTSOF(local_in_addrs); j++) {
230 bool all_localhost, all_local_address;
231 EtcHostsItemByAddress *item;
232 const char *name;
233
234 item = hashmap_get(hosts->by_address, local_in_addrs + j);
235 if (!item)
236 continue;
237
238 /* Check whether all hostnames the loopback address points to are localhost ones */
239 all_localhost = true;
240 SET_FOREACH(name, item->names)
241 if (!is_localhost(name)) {
242 all_localhost = false;
243 break;
244 }
245
246 if (!all_localhost) /* Not all names are localhost, hence keep the entries for this address. */
247 continue;
248
249 /* Now check if the names listed for this address actually all point back just to this
250 * address (or the other loopback address). If not, let's stay away from this too. */
251 all_local_address = true;
252 SET_FOREACH(name, item->names) {
253 EtcHostsItemByName *n;
254 struct in_addr_data *a;
255
256 n = hashmap_get(hosts->by_name, name);
257 if (!n) /* No reverse entry? Then almost certainly the entry already got deleted from
258 * the previous iteration of this loop, i.e. via the other protocol */
259 break;
260
261 /* Now check if the addresses of this item are all localhost addresses */
262 SET_FOREACH(a, n->addresses)
263 if (!in_addr_is_localhost(a->family, &a->address)) {
264 all_local_address = false;
265 break;
266 }
267
268 if (!all_local_address)
269 break;
270 }
271
272 if (!all_local_address)
273 continue;
274
275 SET_FOREACH(name, item->names)
276 etc_hosts_item_by_name_free(hashmap_remove(hosts->by_name, name));
277
278 assert_se(hashmap_remove(hosts->by_address, local_in_addrs + j) == item);
279 etc_hosts_item_by_address_free(item);
280 }
281 }
282
283 int etc_hosts_parse(EtcHosts *hosts, FILE *f) {
284 _cleanup_(etc_hosts_clear) EtcHosts t = {};
285 unsigned nr = 0;
286 int r;
287
288 assert(hosts);
289
290 for (;;) {
291 _cleanup_free_ char *line = NULL;
292 char *l;
293
294 r = read_line(f, LONG_LINE_MAX, &line);
295 if (r < 0)
296 return log_error_errno(r, "Failed to read /etc/hosts: %m");
297 if (r == 0)
298 break;
299
300 nr++;
301
302 l = strchr(line, '#');
303 if (l)
304 *l = '\0';
305
306 l = strstrip(line);
307 if (isempty(l))
308 continue;
309
310 r = parse_line(&t, nr, l);
311 if (r < 0)
312 return r;
313 }
314
315 strip_localhost(&t);
316
317 etc_hosts_clear(hosts);
318 *hosts = TAKE_STRUCT(t);
319 return 0;
320 }
321
322 static int manager_etc_hosts_read(Manager *m) {
323 _cleanup_fclose_ FILE *f = NULL;
324 struct stat st;
325 usec_t ts;
326 int r;
327
328 assert_se(sd_event_now(m->event, CLOCK_BOOTTIME, &ts) >= 0);
329
330 /* See if we checked /etc/hosts recently already */
331 if (m->etc_hosts_last != USEC_INFINITY && m->etc_hosts_last + ETC_HOSTS_RECHECK_USEC > ts)
332 return 0;
333
334 m->etc_hosts_last = ts;
335
336 if (m->etc_hosts_stat.st_mode != 0) {
337 if (stat("/etc/hosts", &st) < 0) {
338 if (errno != ENOENT)
339 return log_error_errno(errno, "Failed to stat /etc/hosts: %m");
340
341 manager_etc_hosts_flush(m);
342 return 0;
343 }
344
345 /* Did the mtime or ino/dev change? If not, there's no point in re-reading the file. */
346 if (stat_inode_unmodified(&m->etc_hosts_stat, &st))
347 return 0;
348 }
349
350 f = fopen("/etc/hosts", "re");
351 if (!f) {
352 if (errno != ENOENT)
353 return log_error_errno(errno, "Failed to open /etc/hosts: %m");
354
355 manager_etc_hosts_flush(m);
356 return 0;
357 }
358
359 /* Take the timestamp at the beginning of processing, so that any changes made later are read on the next
360 * invocation */
361 r = fstat(fileno(f), &st);
362 if (r < 0)
363 return log_error_errno(errno, "Failed to fstat() /etc/hosts: %m");
364
365 r = etc_hosts_parse(&m->etc_hosts, f);
366 if (r < 0)
367 return r;
368
369 m->etc_hosts_stat = st;
370 m->etc_hosts_last = ts;
371
372 return 1;
373 }
374
375 static int etc_hosts_lookup_by_address(
376 EtcHosts *hosts,
377 DnsQuestion *q,
378 const char *name,
379 const struct in_addr_data *address,
380 DnsAnswer **answer) {
381
382 DnsResourceKey *t, *found_ptr = NULL;
383 EtcHostsItemByAddress *item;
384 int r;
385
386 assert(hosts);
387 assert(q);
388 assert(name);
389 assert(address);
390 assert(answer);
391
392 item = hashmap_get(hosts->by_address, address);
393 if (!item)
394 return 0;
395
396 /* We have an address in /etc/hosts that matches the queried name. Let's return successful. Actual data
397 * we'll only return if the request was for PTR. */
398
399 DNS_QUESTION_FOREACH(t, q) {
400 if (!IN_SET(t->type, DNS_TYPE_PTR, DNS_TYPE_ANY))
401 continue;
402 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
403 continue;
404
405 r = dns_name_equal(dns_resource_key_name(t), name);
406 if (r < 0)
407 return r;
408 if (r > 0) {
409 found_ptr = t;
410 break;
411 }
412 }
413
414 if (found_ptr) {
415 const char *n;
416
417 r = dns_answer_reserve(answer, set_size(item->names));
418 if (r < 0)
419 return r;
420
421 SET_FOREACH(n, item->names) {
422 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
423
424 rr = dns_resource_record_new(found_ptr);
425 if (!rr)
426 return -ENOMEM;
427
428 rr->ptr.name = strdup(n);
429 if (!rr->ptr.name)
430 return -ENOMEM;
431
432 r = dns_answer_add(*answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
433 if (r < 0)
434 return r;
435 }
436 }
437
438 return 1;
439 }
440
441 static int etc_hosts_lookup_by_name(
442 EtcHosts *hosts,
443 DnsQuestion *q,
444 const char *name,
445 DnsAnswer **answer) {
446
447 bool found_a = false, found_aaaa = false;
448 const struct in_addr_data *a;
449 EtcHostsItemByName *item;
450 DnsResourceKey *t;
451 int r;
452
453 assert(hosts);
454 assert(q);
455 assert(name);
456 assert(answer);
457
458 item = hashmap_get(hosts->by_name, name);
459 if (item) {
460 r = dns_answer_reserve(answer, set_size(item->addresses));
461 if (r < 0)
462 return r;
463 } else {
464 /* Check if name was listed with no address. If yes, continue to return an answer. */
465 if (!set_contains(hosts->no_address, name))
466 return 0;
467 }
468
469 DNS_QUESTION_FOREACH(t, q) {
470 if (!IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_AAAA, DNS_TYPE_ANY))
471 continue;
472 if (!IN_SET(t->class, DNS_CLASS_IN, DNS_CLASS_ANY))
473 continue;
474
475 r = dns_name_equal(dns_resource_key_name(t), name);
476 if (r < 0)
477 return r;
478 if (r == 0)
479 continue;
480
481 if (IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_ANY))
482 found_a = true;
483 if (IN_SET(t->type, DNS_TYPE_AAAA, DNS_TYPE_ANY))
484 found_aaaa = true;
485
486 if (found_a && found_aaaa)
487 break;
488 }
489
490 SET_FOREACH(a, item ? item->addresses : NULL) {
491 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
492
493 if ((!found_a && a->family == AF_INET) ||
494 (!found_aaaa && a->family == AF_INET6))
495 continue;
496
497 r = dns_resource_record_new_address(&rr, a->family, &a->address, item->name);
498 if (r < 0)
499 return r;
500
501 r = dns_answer_add(*answer, rr, 0, DNS_ANSWER_AUTHENTICATED, NULL);
502 if (r < 0)
503 return r;
504 }
505
506 return found_a || found_aaaa;
507 }
508
509 int manager_etc_hosts_lookup(Manager *m, DnsQuestion *q, DnsAnswer **answer) {
510 struct in_addr_data k;
511 const char *name;
512
513 assert(m);
514 assert(q);
515 assert(answer);
516
517 if (!m->read_etc_hosts)
518 return 0;
519
520 (void) manager_etc_hosts_read(m);
521
522 name = dns_question_first_name(q);
523 if (!name)
524 return 0;
525
526 if (dns_name_address(name, &k.family, &k.address) > 0)
527 return etc_hosts_lookup_by_address(&m->etc_hosts, q, name, &k, answer);
528
529 return etc_hosts_lookup_by_name(&m->etc_hosts, q, name, answer);
530 }