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