resolved: move TLS data shared by all servers to manager
[thirdparty/systemd.git] / src / resolve / resolved-manager.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <fcntl.h>
4 #include <netinet/in.h>
5 #include <poll.h>
6 #include <sys/ioctl.h>
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10
11 #if HAVE_LIBIDN2
12 #include <idn2.h>
13 #endif
14
15 #include "af-list.h"
16 #include "alloc-util.h"
17 #include "dirent-util.h"
18 #include "dns-domain.h"
19 #include "fd-util.h"
20 #include "fileio.h"
21 #include "hostname-util.h"
22 #include "io-util.h"
23 #include "missing_network.h"
24 #include "netlink-util.h"
25 #include "network-internal.h"
26 #include "ordered-set.h"
27 #include "parse-util.h"
28 #include "random-util.h"
29 #include "resolved-bus.h"
30 #include "resolved-conf.h"
31 #include "resolved-dns-stub.h"
32 #include "resolved-dnssd.h"
33 #include "resolved-etc-hosts.h"
34 #include "resolved-llmnr.h"
35 #include "resolved-manager.h"
36 #include "resolved-mdns.h"
37 #include "resolved-resolv-conf.h"
38 #include "socket-util.h"
39 #include "string-table.h"
40 #include "string-util.h"
41 #include "utf8.h"
42
43 #define SEND_TIMEOUT_USEC (200 * USEC_PER_MSEC)
44
45 static int manager_process_link(sd_netlink *rtnl, sd_netlink_message *mm, void *userdata) {
46 Manager *m = userdata;
47 uint16_t type;
48 Link *l;
49 int ifindex, r;
50
51 assert(rtnl);
52 assert(m);
53 assert(mm);
54
55 r = sd_netlink_message_get_type(mm, &type);
56 if (r < 0)
57 goto fail;
58
59 r = sd_rtnl_message_link_get_ifindex(mm, &ifindex);
60 if (r < 0)
61 goto fail;
62
63 l = hashmap_get(m->links, INT_TO_PTR(ifindex));
64
65 switch (type) {
66
67 case RTM_NEWLINK:{
68 bool is_new = !l;
69
70 if (!l) {
71 r = link_new(m, &l, ifindex);
72 if (r < 0)
73 goto fail;
74 }
75
76 r = link_process_rtnl(l, mm);
77 if (r < 0)
78 goto fail;
79
80 r = link_update(l);
81 if (r < 0)
82 goto fail;
83
84 if (is_new)
85 log_debug("Found new link %i/%s", ifindex, l->ifname);
86
87 break;
88 }
89
90 case RTM_DELLINK:
91 if (l) {
92 log_debug("Removing link %i/%s", l->ifindex, l->ifname);
93 link_remove_user(l);
94 link_free(l);
95 }
96
97 break;
98 }
99
100 return 0;
101
102 fail:
103 log_warning_errno(r, "Failed to process RTNL link message: %m");
104 return 0;
105 }
106
107 static int manager_process_address(sd_netlink *rtnl, sd_netlink_message *mm, void *userdata) {
108 Manager *m = userdata;
109 union in_addr_union address;
110 uint16_t type;
111 int r, ifindex, family;
112 LinkAddress *a;
113 Link *l;
114
115 assert(rtnl);
116 assert(mm);
117 assert(m);
118
119 r = sd_netlink_message_get_type(mm, &type);
120 if (r < 0)
121 goto fail;
122
123 r = sd_rtnl_message_addr_get_ifindex(mm, &ifindex);
124 if (r < 0)
125 goto fail;
126
127 l = hashmap_get(m->links, INT_TO_PTR(ifindex));
128 if (!l)
129 return 0;
130
131 r = sd_rtnl_message_addr_get_family(mm, &family);
132 if (r < 0)
133 goto fail;
134
135 switch (family) {
136
137 case AF_INET:
138 r = sd_netlink_message_read_in_addr(mm, IFA_LOCAL, &address.in);
139 if (r < 0) {
140 r = sd_netlink_message_read_in_addr(mm, IFA_ADDRESS, &address.in);
141 if (r < 0)
142 goto fail;
143 }
144
145 break;
146
147 case AF_INET6:
148 r = sd_netlink_message_read_in6_addr(mm, IFA_LOCAL, &address.in6);
149 if (r < 0) {
150 r = sd_netlink_message_read_in6_addr(mm, IFA_ADDRESS, &address.in6);
151 if (r < 0)
152 goto fail;
153 }
154
155 break;
156
157 default:
158 return 0;
159 }
160
161 a = link_find_address(l, family, &address);
162
163 switch (type) {
164
165 case RTM_NEWADDR:
166
167 if (!a) {
168 r = link_address_new(l, &a, family, &address);
169 if (r < 0)
170 return r;
171 }
172
173 r = link_address_update_rtnl(a, mm);
174 if (r < 0)
175 return r;
176
177 break;
178
179 case RTM_DELADDR:
180 link_address_free(a);
181 break;
182 }
183
184 return 0;
185
186 fail:
187 log_warning_errno(r, "Failed to process RTNL address message: %m");
188 return 0;
189 }
190
191 static int manager_rtnl_listen(Manager *m) {
192 _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL;
193 sd_netlink_message *i;
194 int r;
195
196 assert(m);
197
198 /* First, subscribe to interfaces coming and going */
199 r = sd_netlink_open(&m->rtnl);
200 if (r < 0)
201 return r;
202
203 r = sd_netlink_attach_event(m->rtnl, m->event, SD_EVENT_PRIORITY_IMPORTANT);
204 if (r < 0)
205 return r;
206
207 r = sd_netlink_add_match(m->rtnl, NULL, RTM_NEWLINK, manager_process_link, NULL, m, "resolve-NEWLINK");
208 if (r < 0)
209 return r;
210
211 r = sd_netlink_add_match(m->rtnl, NULL, RTM_DELLINK, manager_process_link, NULL, m, "resolve-DELLINK");
212 if (r < 0)
213 return r;
214
215 r = sd_netlink_add_match(m->rtnl, NULL, RTM_NEWADDR, manager_process_address, NULL, m, "resolve-NEWADDR");
216 if (r < 0)
217 return r;
218
219 r = sd_netlink_add_match(m->rtnl, NULL, RTM_DELADDR, manager_process_address, NULL, m, "resolve-DELADDR");
220 if (r < 0)
221 return r;
222
223 /* Then, enumerate all links */
224 r = sd_rtnl_message_new_link(m->rtnl, &req, RTM_GETLINK, 0);
225 if (r < 0)
226 return r;
227
228 r = sd_netlink_message_request_dump(req, true);
229 if (r < 0)
230 return r;
231
232 r = sd_netlink_call(m->rtnl, req, 0, &reply);
233 if (r < 0)
234 return r;
235
236 for (i = reply; i; i = sd_netlink_message_next(i)) {
237 r = manager_process_link(m->rtnl, i, m);
238 if (r < 0)
239 return r;
240 }
241
242 req = sd_netlink_message_unref(req);
243 reply = sd_netlink_message_unref(reply);
244
245 /* Finally, enumerate all addresses, too */
246 r = sd_rtnl_message_new_addr(m->rtnl, &req, RTM_GETADDR, 0, AF_UNSPEC);
247 if (r < 0)
248 return r;
249
250 r = sd_netlink_message_request_dump(req, true);
251 if (r < 0)
252 return r;
253
254 r = sd_netlink_call(m->rtnl, req, 0, &reply);
255 if (r < 0)
256 return r;
257
258 for (i = reply; i; i = sd_netlink_message_next(i)) {
259 r = manager_process_address(m->rtnl, i, m);
260 if (r < 0)
261 return r;
262 }
263
264 return r;
265 }
266
267 static int on_network_event(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
268 Manager *m = userdata;
269 Iterator i;
270 Link *l;
271 int r;
272
273 assert(m);
274
275 sd_network_monitor_flush(m->network_monitor);
276
277 HASHMAP_FOREACH(l, m->links, i) {
278 r = link_update(l);
279 if (r < 0)
280 log_warning_errno(r, "Failed to update monitor information for %i: %m", l->ifindex);
281 }
282
283 (void) manager_write_resolv_conf(m);
284
285 return 0;
286 }
287
288 static int manager_network_monitor_listen(Manager *m) {
289 int r, fd, events;
290
291 assert(m);
292
293 r = sd_network_monitor_new(&m->network_monitor, NULL);
294 if (r < 0)
295 return r;
296
297 fd = sd_network_monitor_get_fd(m->network_monitor);
298 if (fd < 0)
299 return fd;
300
301 events = sd_network_monitor_get_events(m->network_monitor);
302 if (events < 0)
303 return events;
304
305 r = sd_event_add_io(m->event, &m->network_event_source, fd, events, &on_network_event, m);
306 if (r < 0)
307 return r;
308
309 r = sd_event_source_set_priority(m->network_event_source, SD_EVENT_PRIORITY_IMPORTANT+5);
310 if (r < 0)
311 return r;
312
313 (void) sd_event_source_set_description(m->network_event_source, "network-monitor");
314
315 return 0;
316 }
317
318 static int determine_hostname(char **full_hostname, char **llmnr_hostname, char **mdns_hostname) {
319 _cleanup_free_ char *h = NULL, *n = NULL;
320 #if HAVE_LIBIDN2
321 _cleanup_free_ char *utf8 = NULL;
322 #elif HAVE_LIBIDN
323 int k;
324 #endif
325 char label[DNS_LABEL_MAX];
326 const char *p, *decoded;
327 int r;
328
329 assert(full_hostname);
330 assert(llmnr_hostname);
331 assert(mdns_hostname);
332
333 /* Extract and normalize the first label of the locally configured hostname, and check it's not "localhost". */
334
335 r = gethostname_strict(&h);
336 if (r < 0)
337 return log_debug_errno(r, "Can't determine system hostname: %m");
338
339 p = h;
340 r = dns_label_unescape(&p, label, sizeof label, 0);
341 if (r < 0)
342 return log_error_errno(r, "Failed to unescape host name: %m");
343 if (r == 0)
344 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
345 "Couldn't find a single label in hostname.");
346
347 #if HAVE_LIBIDN2
348 r = idn2_to_unicode_8z8z(label, &utf8, 0);
349 if (r != IDN2_OK)
350 return log_error("Failed to undo IDNA: %s", idn2_strerror(r));
351 assert(utf8_is_valid(utf8));
352
353 r = strlen(utf8);
354 decoded = utf8;
355 #elif HAVE_LIBIDN
356 k = dns_label_undo_idna(label, r, label, sizeof label);
357 if (k < 0)
358 return log_error_errno(k, "Failed to undo IDNA: %m");
359 if (k > 0)
360 r = k;
361
362 if (!utf8_is_valid(label))
363 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
364 "System hostname is not UTF-8 clean.");
365 decoded = label;
366 #else
367 decoded = label; /* no decoding */
368 #endif
369
370 r = dns_label_escape_new(decoded, r, &n);
371 if (r < 0)
372 return log_error_errno(r, "Failed to escape host name: %m");
373
374 if (is_localhost(n))
375 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
376 "System hostname is 'localhost', ignoring.");
377
378 r = dns_name_concat(n, "local", 0, mdns_hostname);
379 if (r < 0)
380 return log_error_errno(r, "Failed to determine mDNS hostname: %m");
381
382 *llmnr_hostname = TAKE_PTR(n);
383 *full_hostname = TAKE_PTR(h);
384
385 return 0;
386 }
387
388 static const char *fallback_hostname(void) {
389
390 /* Determine the fall back hostname. For exposing this system to the outside world, we cannot have it to be
391 * "localhost" even if that's the compiled in hostname. In this case, let's revert to "linux" instead. */
392
393 if (is_localhost(FALLBACK_HOSTNAME))
394 return "linux";
395
396 return FALLBACK_HOSTNAME;
397 }
398
399 static int make_fallback_hostnames(char **full_hostname, char **llmnr_hostname, char **mdns_hostname) {
400 _cleanup_free_ char *n = NULL, *m = NULL;
401 char label[DNS_LABEL_MAX], *h;
402 const char *p;
403 int r;
404
405 assert(full_hostname);
406 assert(llmnr_hostname);
407 assert(mdns_hostname);
408
409 p = fallback_hostname();
410 r = dns_label_unescape(&p, label, sizeof label, 0);
411 if (r < 0)
412 return log_error_errno(r, "Failed to unescape fallback host name: %m");
413
414 assert(r > 0); /* The fallback hostname must have at least one label */
415
416 r = dns_label_escape_new(label, r, &n);
417 if (r < 0)
418 return log_error_errno(r, "Failed to escape fallback hostname: %m");
419
420 r = dns_name_concat(n, "local", 0, &m);
421 if (r < 0)
422 return log_error_errno(r, "Failed to concatenate mDNS hostname: %m");
423
424 h = strdup(fallback_hostname());
425 if (!h)
426 return log_oom();
427
428 *llmnr_hostname = TAKE_PTR(n);
429 *mdns_hostname = TAKE_PTR(m);
430
431 *full_hostname = h;
432
433 return 0;
434 }
435
436 static int on_hostname_change(sd_event_source *es, int fd, uint32_t revents, void *userdata) {
437 _cleanup_free_ char *full_hostname = NULL, *llmnr_hostname = NULL, *mdns_hostname = NULL;
438 Manager *m = userdata;
439 int r;
440
441 assert(m);
442
443 r = determine_hostname(&full_hostname, &llmnr_hostname, &mdns_hostname);
444 if (r < 0)
445 return 0; /* ignore invalid hostnames */
446
447 if (streq(full_hostname, m->full_hostname) &&
448 streq(llmnr_hostname, m->llmnr_hostname) &&
449 streq(mdns_hostname, m->mdns_hostname))
450 return 0;
451
452 log_info("System hostname changed to '%s'.", full_hostname);
453
454 free_and_replace(m->full_hostname, full_hostname);
455 free_and_replace(m->llmnr_hostname, llmnr_hostname);
456 free_and_replace(m->mdns_hostname, mdns_hostname);
457
458 manager_refresh_rrs(m);
459
460 return 0;
461 }
462
463 static int manager_watch_hostname(Manager *m) {
464 int r;
465
466 assert(m);
467
468 m->hostname_fd = open("/proc/sys/kernel/hostname",
469 O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
470 if (m->hostname_fd < 0) {
471 log_warning_errno(errno, "Failed to watch hostname: %m");
472 return 0;
473 }
474
475 r = sd_event_add_io(m->event, &m->hostname_event_source, m->hostname_fd, 0, on_hostname_change, m);
476 if (r < 0) {
477 if (r == -EPERM)
478 /* kernels prior to 3.2 don't support polling this file. Ignore the failure. */
479 m->hostname_fd = safe_close(m->hostname_fd);
480 else
481 return log_error_errno(r, "Failed to add hostname event source: %m");
482 }
483
484 (void) sd_event_source_set_description(m->hostname_event_source, "hostname");
485
486 r = determine_hostname(&m->full_hostname, &m->llmnr_hostname, &m->mdns_hostname);
487 if (r < 0) {
488 log_info("Defaulting to hostname '%s'.", fallback_hostname());
489
490 r = make_fallback_hostnames(&m->full_hostname, &m->llmnr_hostname, &m->mdns_hostname);
491 if (r < 0)
492 return r;
493 } else
494 log_info("Using system hostname '%s'.", m->full_hostname);
495
496 return 0;
497 }
498
499 static int manager_sigusr1(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
500 _cleanup_free_ char *buffer = NULL;
501 _cleanup_fclose_ FILE *f = NULL;
502 Manager *m = userdata;
503 DnsServer *server;
504 size_t size = 0;
505 DnsScope *scope;
506 Iterator i;
507 Link *l;
508
509 assert(s);
510 assert(si);
511 assert(m);
512
513 f = open_memstream_unlocked(&buffer, &size);
514 if (!f)
515 return log_oom();
516
517 LIST_FOREACH(scopes, scope, m->dns_scopes)
518 dns_scope_dump(scope, f);
519
520 LIST_FOREACH(servers, server, m->dns_servers)
521 dns_server_dump(server, f);
522 LIST_FOREACH(servers, server, m->fallback_dns_servers)
523 dns_server_dump(server, f);
524 HASHMAP_FOREACH(l, m->links, i)
525 LIST_FOREACH(servers, server, l->dns_servers)
526 dns_server_dump(server, f);
527
528 if (fflush_and_check(f) < 0)
529 return log_oom();
530
531 log_dump(LOG_INFO, buffer);
532 return 0;
533 }
534
535 static int manager_sigusr2(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
536 Manager *m = userdata;
537
538 assert(s);
539 assert(si);
540 assert(m);
541
542 manager_flush_caches(m);
543
544 return 0;
545 }
546
547 static int manager_sigrtmin1(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
548 Manager *m = userdata;
549
550 assert(s);
551 assert(si);
552 assert(m);
553
554 manager_reset_server_features(m);
555 return 0;
556 }
557
558 int manager_new(Manager **ret) {
559 _cleanup_(manager_freep) Manager *m = NULL;
560 int r;
561
562 assert(ret);
563
564 m = new(Manager, 1);
565 if (!m)
566 return -ENOMEM;
567
568 *m = (Manager) {
569 .llmnr_ipv4_udp_fd = -1,
570 .llmnr_ipv6_udp_fd = -1,
571 .llmnr_ipv4_tcp_fd = -1,
572 .llmnr_ipv6_tcp_fd = -1,
573 .mdns_ipv4_fd = -1,
574 .mdns_ipv6_fd = -1,
575 .dns_stub_udp_fd = -1,
576 .dns_stub_tcp_fd = -1,
577 .hostname_fd = -1,
578
579 .llmnr_support = RESOLVE_SUPPORT_YES,
580 .mdns_support = RESOLVE_SUPPORT_YES,
581 .dnssec_mode = DEFAULT_DNSSEC_MODE,
582 .dns_over_tls_mode = DEFAULT_DNS_OVER_TLS_MODE,
583 .enable_cache = true,
584 .dns_stub_listener_mode = DNS_STUB_LISTENER_YES,
585 .read_resolv_conf = true,
586 .need_builtin_fallbacks = true,
587 .etc_hosts_last = USEC_INFINITY,
588 .etc_hosts_mtime = USEC_INFINITY,
589 .read_etc_hosts = true,
590 };
591
592 r = dns_trust_anchor_load(&m->trust_anchor);
593 if (r < 0)
594 return r;
595
596 r = manager_parse_config_file(m);
597 if (r < 0)
598 log_warning_errno(r, "Failed to parse configuration file: %m");
599
600 #if ENABLE_DNS_OVER_TLS
601 dnstls_manager_init(m);
602 #endif
603
604 r = sd_event_default(&m->event);
605 if (r < 0)
606 return r;
607
608 (void) sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
609 (void) sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
610
611 (void) sd_event_set_watchdog(m->event, true);
612
613 r = manager_watch_hostname(m);
614 if (r < 0)
615 return r;
616
617 r = dnssd_load(m);
618 if (r < 0)
619 log_warning_errno(r, "Failed to load DNS-SD configuration files: %m");
620
621 r = dns_scope_new(m, &m->unicast_scope, NULL, DNS_PROTOCOL_DNS, AF_UNSPEC);
622 if (r < 0)
623 return r;
624
625 r = manager_network_monitor_listen(m);
626 if (r < 0)
627 return r;
628
629 r = manager_rtnl_listen(m);
630 if (r < 0)
631 return r;
632
633 r = manager_connect_bus(m);
634 if (r < 0)
635 return r;
636
637 (void) sd_event_add_signal(m->event, &m->sigusr1_event_source, SIGUSR1, manager_sigusr1, m);
638 (void) sd_event_add_signal(m->event, &m->sigusr2_event_source, SIGUSR2, manager_sigusr2, m);
639 (void) sd_event_add_signal(m->event, &m->sigrtmin1_event_source, SIGRTMIN+1, manager_sigrtmin1, m);
640
641 manager_cleanup_saved_user(m);
642
643 *ret = TAKE_PTR(m);
644
645 return 0;
646 }
647
648 int manager_start(Manager *m) {
649 int r;
650
651 assert(m);
652
653 r = manager_dns_stub_start(m);
654 if (r < 0)
655 return r;
656
657 return 0;
658 }
659
660 Manager *manager_free(Manager *m) {
661 Link *l;
662 DnssdService *s;
663
664 if (!m)
665 return NULL;
666
667 dns_server_unlink_all(m->dns_servers);
668 dns_server_unlink_all(m->fallback_dns_servers);
669 dns_search_domain_unlink_all(m->search_domains);
670
671 while ((l = hashmap_first(m->links)))
672 link_free(l);
673
674 while (m->dns_queries)
675 dns_query_free(m->dns_queries);
676
677 dns_scope_free(m->unicast_scope);
678
679 /* At this point only orphaned streams should remain. All others should have been freed already by their
680 * owners */
681 while (m->dns_streams)
682 dns_stream_unref(m->dns_streams);
683
684 #if ENABLE_DNS_OVER_TLS
685 dnstls_manager_free(m);
686 #endif
687
688 hashmap_free(m->links);
689 hashmap_free(m->dns_transactions);
690
691 sd_event_source_unref(m->network_event_source);
692 sd_network_monitor_unref(m->network_monitor);
693
694 sd_netlink_unref(m->rtnl);
695 sd_event_source_unref(m->rtnl_event_source);
696
697 manager_llmnr_stop(m);
698 manager_mdns_stop(m);
699 manager_dns_stub_stop(m);
700
701 sd_bus_flush_close_unref(m->bus);
702
703 sd_event_source_unref(m->sigusr1_event_source);
704 sd_event_source_unref(m->sigusr2_event_source);
705 sd_event_source_unref(m->sigrtmin1_event_source);
706
707 sd_event_unref(m->event);
708
709 dns_resource_key_unref(m->llmnr_host_ipv4_key);
710 dns_resource_key_unref(m->llmnr_host_ipv6_key);
711 dns_resource_key_unref(m->mdns_host_ipv4_key);
712 dns_resource_key_unref(m->mdns_host_ipv6_key);
713
714 sd_event_source_unref(m->hostname_event_source);
715 safe_close(m->hostname_fd);
716
717 free(m->full_hostname);
718 free(m->llmnr_hostname);
719 free(m->mdns_hostname);
720
721 while ((s = hashmap_first(m->dnssd_services)))
722 dnssd_service_free(s);
723 hashmap_free(m->dnssd_services);
724
725 dns_trust_anchor_flush(&m->trust_anchor);
726 manager_etc_hosts_flush(m);
727
728 return mfree(m);
729 }
730
731 int manager_recv(Manager *m, int fd, DnsProtocol protocol, DnsPacket **ret) {
732 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
733 union {
734 struct cmsghdr header; /* For alignment */
735 uint8_t buffer[CMSG_SPACE(MAXSIZE(struct in_pktinfo, struct in6_pktinfo))
736 + CMSG_SPACE(int) /* ttl/hoplimit */
737 + EXTRA_CMSG_SPACE /* kernel appears to require extra buffer space */];
738 } control;
739 union sockaddr_union sa;
740 struct iovec iov;
741 struct msghdr mh = {
742 .msg_name = &sa.sa,
743 .msg_namelen = sizeof(sa),
744 .msg_iov = &iov,
745 .msg_iovlen = 1,
746 .msg_control = &control,
747 .msg_controllen = sizeof(control),
748 };
749 struct cmsghdr *cmsg;
750 ssize_t ms, l;
751 int r;
752
753 assert(m);
754 assert(fd >= 0);
755 assert(ret);
756
757 ms = next_datagram_size_fd(fd);
758 if (ms < 0)
759 return ms;
760
761 r = dns_packet_new(&p, protocol, ms, DNS_PACKET_SIZE_MAX);
762 if (r < 0)
763 return r;
764
765 iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->allocated);
766
767 l = recvmsg(fd, &mh, 0);
768 if (l < 0) {
769 if (IN_SET(errno, EAGAIN, EINTR))
770 return 0;
771
772 return -errno;
773 }
774 if (l == 0)
775 return 0;
776
777 assert(!(mh.msg_flags & MSG_CTRUNC));
778 assert(!(mh.msg_flags & MSG_TRUNC));
779
780 p->size = (size_t) l;
781
782 p->family = sa.sa.sa_family;
783 p->ipproto = IPPROTO_UDP;
784 if (p->family == AF_INET) {
785 p->sender.in = sa.in.sin_addr;
786 p->sender_port = be16toh(sa.in.sin_port);
787 } else if (p->family == AF_INET6) {
788 p->sender.in6 = sa.in6.sin6_addr;
789 p->sender_port = be16toh(sa.in6.sin6_port);
790 p->ifindex = sa.in6.sin6_scope_id;
791 } else
792 return -EAFNOSUPPORT;
793
794 CMSG_FOREACH(cmsg, &mh) {
795
796 if (cmsg->cmsg_level == IPPROTO_IPV6) {
797 assert(p->family == AF_INET6);
798
799 switch (cmsg->cmsg_type) {
800
801 case IPV6_PKTINFO: {
802 struct in6_pktinfo *i = (struct in6_pktinfo*) CMSG_DATA(cmsg);
803
804 if (p->ifindex <= 0)
805 p->ifindex = i->ipi6_ifindex;
806
807 p->destination.in6 = i->ipi6_addr;
808 break;
809 }
810
811 case IPV6_HOPLIMIT:
812 p->ttl = *(int *) CMSG_DATA(cmsg);
813 break;
814
815 }
816 } else if (cmsg->cmsg_level == IPPROTO_IP) {
817 assert(p->family == AF_INET);
818
819 switch (cmsg->cmsg_type) {
820
821 case IP_PKTINFO: {
822 struct in_pktinfo *i = (struct in_pktinfo*) CMSG_DATA(cmsg);
823
824 if (p->ifindex <= 0)
825 p->ifindex = i->ipi_ifindex;
826
827 p->destination.in = i->ipi_addr;
828 break;
829 }
830
831 case IP_TTL:
832 p->ttl = *(int *) CMSG_DATA(cmsg);
833 break;
834 }
835 }
836 }
837
838 /* The Linux kernel sets the interface index to the loopback
839 * device if the packet came from the local host since it
840 * avoids the routing table in such a case. Let's unset the
841 * interface index in such a case. */
842 if (p->ifindex == LOOPBACK_IFINDEX)
843 p->ifindex = 0;
844
845 if (protocol != DNS_PROTOCOL_DNS) {
846 /* If we don't know the interface index still, we look for the
847 * first local interface with a matching address. Yuck! */
848 if (p->ifindex <= 0)
849 p->ifindex = manager_find_ifindex(m, p->family, &p->destination);
850 }
851
852 *ret = TAKE_PTR(p);
853
854 return 1;
855 }
856
857 static int sendmsg_loop(int fd, struct msghdr *mh, int flags) {
858 int r;
859
860 assert(fd >= 0);
861 assert(mh);
862
863 for (;;) {
864 if (sendmsg(fd, mh, flags) >= 0)
865 return 0;
866
867 if (errno == EINTR)
868 continue;
869
870 if (errno != EAGAIN)
871 return -errno;
872
873 r = fd_wait_for_event(fd, POLLOUT, SEND_TIMEOUT_USEC);
874 if (r < 0)
875 return r;
876 if (r == 0)
877 return -ETIMEDOUT;
878 }
879 }
880
881 static int write_loop(int fd, void *message, size_t length) {
882 int r;
883
884 assert(fd >= 0);
885 assert(message);
886
887 for (;;) {
888 if (write(fd, message, length) >= 0)
889 return 0;
890
891 if (errno == EINTR)
892 continue;
893
894 if (errno != EAGAIN)
895 return -errno;
896
897 r = fd_wait_for_event(fd, POLLOUT, SEND_TIMEOUT_USEC);
898 if (r < 0)
899 return r;
900 if (r == 0)
901 return -ETIMEDOUT;
902 }
903 }
904
905 int manager_write(Manager *m, int fd, DnsPacket *p) {
906 int r;
907
908 log_debug("Sending %s packet with id %" PRIu16 ".", DNS_PACKET_QR(p) ? "response" : "query", DNS_PACKET_ID(p));
909
910 r = write_loop(fd, DNS_PACKET_DATA(p), p->size);
911 if (r < 0)
912 return r;
913
914 return 0;
915 }
916
917 static int manager_ipv4_send(
918 Manager *m,
919 int fd,
920 int ifindex,
921 const struct in_addr *destination,
922 uint16_t port,
923 const struct in_addr *source,
924 DnsPacket *p) {
925 union {
926 struct cmsghdr header; /* For alignment */
927 uint8_t buffer[CMSG_SPACE(sizeof(struct in_pktinfo))];
928 } control = {};
929 union sockaddr_union sa;
930 struct iovec iov;
931 struct msghdr mh = {
932 .msg_iov = &iov,
933 .msg_iovlen = 1,
934 .msg_name = &sa.sa,
935 .msg_namelen = sizeof(sa.in),
936 };
937
938 assert(m);
939 assert(fd >= 0);
940 assert(destination);
941 assert(port > 0);
942 assert(p);
943
944 iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->size);
945
946 sa = (union sockaddr_union) {
947 .in.sin_family = AF_INET,
948 .in.sin_addr = *destination,
949 .in.sin_port = htobe16(port),
950 };
951
952 if (ifindex > 0) {
953 struct cmsghdr *cmsg;
954 struct in_pktinfo *pi;
955
956 mh.msg_control = &control;
957 mh.msg_controllen = CMSG_LEN(sizeof(struct in_pktinfo));
958
959 cmsg = CMSG_FIRSTHDR(&mh);
960 cmsg->cmsg_len = mh.msg_controllen;
961 cmsg->cmsg_level = IPPROTO_IP;
962 cmsg->cmsg_type = IP_PKTINFO;
963
964 pi = (struct in_pktinfo*) CMSG_DATA(cmsg);
965 pi->ipi_ifindex = ifindex;
966
967 if (source)
968 pi->ipi_spec_dst = *source;
969 }
970
971 return sendmsg_loop(fd, &mh, 0);
972 }
973
974 static int manager_ipv6_send(
975 Manager *m,
976 int fd,
977 int ifindex,
978 const struct in6_addr *destination,
979 uint16_t port,
980 const struct in6_addr *source,
981 DnsPacket *p) {
982
983 union {
984 struct cmsghdr header; /* For alignment */
985 uint8_t buffer[CMSG_SPACE(sizeof(struct in6_pktinfo))];
986 } control = {};
987 union sockaddr_union sa;
988 struct iovec iov;
989 struct msghdr mh = {
990 .msg_iov = &iov,
991 .msg_iovlen = 1,
992 .msg_name = &sa.sa,
993 .msg_namelen = sizeof(sa.in6),
994 };
995
996 assert(m);
997 assert(fd >= 0);
998 assert(destination);
999 assert(port > 0);
1000 assert(p);
1001
1002 iov = IOVEC_MAKE(DNS_PACKET_DATA(p), p->size);
1003
1004 sa = (union sockaddr_union) {
1005 .in6.sin6_family = AF_INET6,
1006 .in6.sin6_addr = *destination,
1007 .in6.sin6_port = htobe16(port),
1008 .in6.sin6_scope_id = ifindex,
1009 };
1010
1011 if (ifindex > 0) {
1012 struct cmsghdr *cmsg;
1013 struct in6_pktinfo *pi;
1014
1015 mh.msg_control = &control;
1016 mh.msg_controllen = CMSG_LEN(sizeof(struct in6_pktinfo));
1017
1018 cmsg = CMSG_FIRSTHDR(&mh);
1019 cmsg->cmsg_len = mh.msg_controllen;
1020 cmsg->cmsg_level = IPPROTO_IPV6;
1021 cmsg->cmsg_type = IPV6_PKTINFO;
1022
1023 pi = (struct in6_pktinfo*) CMSG_DATA(cmsg);
1024 pi->ipi6_ifindex = ifindex;
1025
1026 if (source)
1027 pi->ipi6_addr = *source;
1028 }
1029
1030 return sendmsg_loop(fd, &mh, 0);
1031 }
1032
1033 int manager_send(
1034 Manager *m,
1035 int fd,
1036 int ifindex,
1037 int family,
1038 const union in_addr_union *destination,
1039 uint16_t port,
1040 const union in_addr_union *source,
1041 DnsPacket *p) {
1042
1043 assert(m);
1044 assert(fd >= 0);
1045 assert(destination);
1046 assert(port > 0);
1047 assert(p);
1048
1049 log_debug("Sending %s packet with id %" PRIu16 " on interface %i/%s.", DNS_PACKET_QR(p) ? "response" : "query", DNS_PACKET_ID(p), ifindex, af_to_name(family));
1050
1051 if (family == AF_INET)
1052 return manager_ipv4_send(m, fd, ifindex, &destination->in, port, source ? &source->in : NULL, p);
1053 if (family == AF_INET6)
1054 return manager_ipv6_send(m, fd, ifindex, &destination->in6, port, source ? &source->in6 : NULL, p);
1055
1056 return -EAFNOSUPPORT;
1057 }
1058
1059 uint32_t manager_find_mtu(Manager *m) {
1060 uint32_t mtu = 0;
1061 Link *l;
1062 Iterator i;
1063
1064 /* If we don't know on which link a DNS packet would be
1065 * delivered, let's find the largest MTU that works on all
1066 * interfaces we know of */
1067
1068 HASHMAP_FOREACH(l, m->links, i) {
1069 if (l->mtu <= 0)
1070 continue;
1071
1072 if (mtu <= 0 || l->mtu < mtu)
1073 mtu = l->mtu;
1074 }
1075
1076 return mtu;
1077 }
1078
1079 int manager_find_ifindex(Manager *m, int family, const union in_addr_union *in_addr) {
1080 LinkAddress *a;
1081
1082 assert(m);
1083
1084 a = manager_find_link_address(m, family, in_addr);
1085 if (a)
1086 return a->link->ifindex;
1087
1088 return 0;
1089 }
1090
1091 void manager_refresh_rrs(Manager *m) {
1092 Iterator i;
1093 Link *l;
1094 DnssdService *s;
1095
1096 assert(m);
1097
1098 m->llmnr_host_ipv4_key = dns_resource_key_unref(m->llmnr_host_ipv4_key);
1099 m->llmnr_host_ipv6_key = dns_resource_key_unref(m->llmnr_host_ipv6_key);
1100 m->mdns_host_ipv4_key = dns_resource_key_unref(m->mdns_host_ipv4_key);
1101 m->mdns_host_ipv6_key = dns_resource_key_unref(m->mdns_host_ipv6_key);
1102
1103 if (m->mdns_support == RESOLVE_SUPPORT_YES)
1104 HASHMAP_FOREACH(s, m->dnssd_services, i)
1105 if (dnssd_update_rrs(s) < 0)
1106 log_warning("Failed to refresh DNS-SD service '%s'", s->name);
1107
1108 HASHMAP_FOREACH(l, m->links, i) {
1109 link_add_rrs(l, true);
1110 link_add_rrs(l, false);
1111 }
1112 }
1113
1114 static int manager_next_random_name(const char *old, char **ret_new) {
1115 const char *p;
1116 uint64_t u, a;
1117 char *n;
1118
1119 p = strchr(old, 0);
1120 assert(p);
1121
1122 while (p > old) {
1123 if (!strchr(DIGITS, p[-1]))
1124 break;
1125
1126 p--;
1127 }
1128
1129 if (*p == 0 || safe_atou64(p, &u) < 0 || u <= 0)
1130 u = 1;
1131
1132 /* Add a random number to the old value. This way we can avoid
1133 * that two hosts pick the same hostname, win on IPv4 and lose
1134 * on IPv6 (or vice versa), and pick the same hostname
1135 * replacement hostname, ad infinitum. We still want the
1136 * numbers to go up monotonically, hence we just add a random
1137 * value 1..10 */
1138
1139 random_bytes(&a, sizeof(a));
1140 u += 1 + a % 10;
1141
1142 if (asprintf(&n, "%.*s%" PRIu64, (int) (p - old), old, u) < 0)
1143 return -ENOMEM;
1144
1145 *ret_new = n;
1146
1147 return 0;
1148 }
1149
1150 int manager_next_hostname(Manager *m) {
1151 _cleanup_free_ char *h = NULL, *k = NULL;
1152 int r;
1153
1154 assert(m);
1155
1156 r = manager_next_random_name(m->llmnr_hostname, &h);
1157 if (r < 0)
1158 return r;
1159
1160 r = dns_name_concat(h, "local", 0, &k);
1161 if (r < 0)
1162 return r;
1163
1164 log_info("Hostname conflict, changing published hostname from '%s' to '%s'.", m->llmnr_hostname, h);
1165
1166 free_and_replace(m->llmnr_hostname, h);
1167 free_and_replace(m->mdns_hostname, k);
1168
1169 manager_refresh_rrs(m);
1170
1171 return 0;
1172 }
1173
1174 LinkAddress* manager_find_link_address(Manager *m, int family, const union in_addr_union *in_addr) {
1175 Iterator i;
1176 Link *l;
1177
1178 assert(m);
1179
1180 HASHMAP_FOREACH(l, m->links, i) {
1181 LinkAddress *a;
1182
1183 a = link_find_address(l, family, in_addr);
1184 if (a)
1185 return a;
1186 }
1187
1188 return NULL;
1189 }
1190
1191 bool manager_our_packet(Manager *m, DnsPacket *p) {
1192 assert(m);
1193 assert(p);
1194
1195 return !!manager_find_link_address(m, p->family, &p->sender);
1196 }
1197
1198 DnsScope* manager_find_scope(Manager *m, DnsPacket *p) {
1199 Link *l;
1200
1201 assert(m);
1202 assert(p);
1203
1204 l = hashmap_get(m->links, INT_TO_PTR(p->ifindex));
1205 if (!l)
1206 return NULL;
1207
1208 switch (p->protocol) {
1209 case DNS_PROTOCOL_LLMNR:
1210 if (p->family == AF_INET)
1211 return l->llmnr_ipv4_scope;
1212 else if (p->family == AF_INET6)
1213 return l->llmnr_ipv6_scope;
1214
1215 break;
1216
1217 case DNS_PROTOCOL_MDNS:
1218 if (p->family == AF_INET)
1219 return l->mdns_ipv4_scope;
1220 else if (p->family == AF_INET6)
1221 return l->mdns_ipv6_scope;
1222
1223 break;
1224
1225 default:
1226 break;
1227 }
1228
1229 return NULL;
1230 }
1231
1232 void manager_verify_all(Manager *m) {
1233 DnsScope *s;
1234
1235 assert(m);
1236
1237 LIST_FOREACH(scopes, s, m->dns_scopes)
1238 dns_zone_verify_all(&s->zone);
1239 }
1240
1241 int manager_is_own_hostname(Manager *m, const char *name) {
1242 int r;
1243
1244 assert(m);
1245 assert(name);
1246
1247 if (m->llmnr_hostname) {
1248 r = dns_name_equal(name, m->llmnr_hostname);
1249 if (r != 0)
1250 return r;
1251 }
1252
1253 if (m->mdns_hostname) {
1254 r = dns_name_equal(name, m->mdns_hostname);
1255 if (r != 0)
1256 return r;
1257 }
1258
1259 if (m->full_hostname)
1260 return dns_name_equal(name, m->full_hostname);
1261
1262 return 0;
1263 }
1264
1265 int manager_compile_dns_servers(Manager *m, OrderedSet **dns) {
1266 DnsServer *s;
1267 Iterator i;
1268 Link *l;
1269 int r;
1270
1271 assert(m);
1272 assert(dns);
1273
1274 r = ordered_set_ensure_allocated(dns, &dns_server_hash_ops);
1275 if (r < 0)
1276 return r;
1277
1278 /* First add the system-wide servers and domains */
1279 LIST_FOREACH(servers, s, m->dns_servers) {
1280 r = ordered_set_put(*dns, s);
1281 if (r == -EEXIST)
1282 continue;
1283 if (r < 0)
1284 return r;
1285 }
1286
1287 /* Then, add the per-link servers */
1288 HASHMAP_FOREACH(l, m->links, i) {
1289 LIST_FOREACH(servers, s, l->dns_servers) {
1290 r = ordered_set_put(*dns, s);
1291 if (r == -EEXIST)
1292 continue;
1293 if (r < 0)
1294 return r;
1295 }
1296 }
1297
1298 /* If we found nothing, add the fallback servers */
1299 if (ordered_set_isempty(*dns)) {
1300 LIST_FOREACH(servers, s, m->fallback_dns_servers) {
1301 r = ordered_set_put(*dns, s);
1302 if (r == -EEXIST)
1303 continue;
1304 if (r < 0)
1305 return r;
1306 }
1307 }
1308
1309 return 0;
1310 }
1311
1312 /* filter_route is a tri-state:
1313 * < 0: no filtering
1314 * = 0 or false: return only domains which should be used for searching
1315 * > 0 or true: return only domains which are for routing only
1316 */
1317 int manager_compile_search_domains(Manager *m, OrderedSet **domains, int filter_route) {
1318 DnsSearchDomain *d;
1319 Iterator i;
1320 Link *l;
1321 int r;
1322
1323 assert(m);
1324 assert(domains);
1325
1326 r = ordered_set_ensure_allocated(domains, &dns_name_hash_ops);
1327 if (r < 0)
1328 return r;
1329
1330 LIST_FOREACH(domains, d, m->search_domains) {
1331
1332 if (filter_route >= 0 &&
1333 d->route_only != !!filter_route)
1334 continue;
1335
1336 r = ordered_set_put(*domains, d->name);
1337 if (r == -EEXIST)
1338 continue;
1339 if (r < 0)
1340 return r;
1341 }
1342
1343 HASHMAP_FOREACH(l, m->links, i) {
1344
1345 LIST_FOREACH(domains, d, l->search_domains) {
1346
1347 if (filter_route >= 0 &&
1348 d->route_only != !!filter_route)
1349 continue;
1350
1351 r = ordered_set_put(*domains, d->name);
1352 if (r == -EEXIST)
1353 continue;
1354 if (r < 0)
1355 return r;
1356 }
1357 }
1358
1359 return 0;
1360 }
1361
1362 DnssecMode manager_get_dnssec_mode(Manager *m) {
1363 assert(m);
1364
1365 if (m->dnssec_mode != _DNSSEC_MODE_INVALID)
1366 return m->dnssec_mode;
1367
1368 return DNSSEC_NO;
1369 }
1370
1371 bool manager_dnssec_supported(Manager *m) {
1372 DnsServer *server;
1373 Iterator i;
1374 Link *l;
1375
1376 assert(m);
1377
1378 if (manager_get_dnssec_mode(m) == DNSSEC_NO)
1379 return false;
1380
1381 server = manager_get_dns_server(m);
1382 if (server && !dns_server_dnssec_supported(server))
1383 return false;
1384
1385 HASHMAP_FOREACH(l, m->links, i)
1386 if (!link_dnssec_supported(l))
1387 return false;
1388
1389 return true;
1390 }
1391
1392 DnsOverTlsMode manager_get_dns_over_tls_mode(Manager *m) {
1393 assert(m);
1394
1395 if (m->dns_over_tls_mode != _DNS_OVER_TLS_MODE_INVALID)
1396 return m->dns_over_tls_mode;
1397
1398 return DNS_OVER_TLS_NO;
1399 }
1400
1401 void manager_dnssec_verdict(Manager *m, DnssecVerdict verdict, const DnsResourceKey *key) {
1402
1403 assert(verdict >= 0);
1404 assert(verdict < _DNSSEC_VERDICT_MAX);
1405
1406 if (DEBUG_LOGGING) {
1407 char s[DNS_RESOURCE_KEY_STRING_MAX];
1408
1409 log_debug("Found verdict for lookup %s: %s",
1410 dns_resource_key_to_string(key, s, sizeof s),
1411 dnssec_verdict_to_string(verdict));
1412 }
1413
1414 m->n_dnssec_verdict[verdict]++;
1415 }
1416
1417 bool manager_routable(Manager *m, int family) {
1418 Iterator i;
1419 Link *l;
1420
1421 assert(m);
1422
1423 /* Returns true if the host has at least one interface with a routable address of the specified type */
1424
1425 HASHMAP_FOREACH(l, m->links, i)
1426 if (link_relevant(l, family, false))
1427 return true;
1428
1429 return false;
1430 }
1431
1432 void manager_flush_caches(Manager *m) {
1433 DnsScope *scope;
1434
1435 assert(m);
1436
1437 LIST_FOREACH(scopes, scope, m->dns_scopes)
1438 dns_cache_flush(&scope->cache);
1439
1440 log_info("Flushed all caches.");
1441 }
1442
1443 void manager_reset_server_features(Manager *m) {
1444 Iterator i;
1445 Link *l;
1446
1447 dns_server_reset_features_all(m->dns_servers);
1448 dns_server_reset_features_all(m->fallback_dns_servers);
1449
1450 HASHMAP_FOREACH(l, m->links, i)
1451 dns_server_reset_features_all(l->dns_servers);
1452
1453 log_info("Resetting learnt feature levels on all servers.");
1454 }
1455
1456 void manager_cleanup_saved_user(Manager *m) {
1457 _cleanup_closedir_ DIR *d = NULL;
1458 struct dirent *de;
1459 int r;
1460
1461 assert(m);
1462
1463 /* Clean up all saved per-link files in /run/systemd/resolve/netif/ that don't have a matching interface
1464 * anymore. These files are created to persist settings pushed in by the user via the bus, so that resolved can
1465 * be restarted without losing this data. */
1466
1467 d = opendir("/run/systemd/resolve/netif/");
1468 if (!d) {
1469 if (errno == ENOENT)
1470 return;
1471
1472 log_warning_errno(errno, "Failed to open interface directory: %m");
1473 return;
1474 }
1475
1476 FOREACH_DIRENT_ALL(de, d, log_error_errno(errno, "Failed to read interface directory: %m")) {
1477 _cleanup_free_ char *p = NULL;
1478 int ifindex;
1479 Link *l;
1480
1481 if (!IN_SET(de->d_type, DT_UNKNOWN, DT_REG))
1482 continue;
1483
1484 if (dot_or_dot_dot(de->d_name))
1485 continue;
1486
1487 r = parse_ifindex(de->d_name, &ifindex);
1488 if (r < 0) /* Probably some temporary file from a previous run. Delete it */
1489 goto rm;
1490
1491 l = hashmap_get(m->links, INT_TO_PTR(ifindex));
1492 if (!l) /* link vanished */
1493 goto rm;
1494
1495 if (l->is_managed) /* now managed by networkd, hence the bus settings are useless */
1496 goto rm;
1497
1498 continue;
1499
1500 rm:
1501 p = strappend("/run/systemd/resolve/netif/", de->d_name);
1502 if (!p) {
1503 log_oom();
1504 return;
1505 }
1506
1507 (void) unlink(p);
1508 }
1509 }
1510
1511 bool manager_next_dnssd_names(Manager *m) {
1512 Iterator i;
1513 DnssdService *s;
1514 bool tried = false;
1515 int r;
1516
1517 assert(m);
1518
1519 HASHMAP_FOREACH(s, m->dnssd_services, i) {
1520 _cleanup_free_ char * new_name = NULL;
1521
1522 if (!s->withdrawn)
1523 continue;
1524
1525 r = manager_next_random_name(s->name_template, &new_name);
1526 if (r < 0) {
1527 log_warning_errno(r, "Failed to get new name for service '%s': %m", s->name);
1528 continue;
1529 }
1530
1531 free_and_replace(s->name_template, new_name);
1532
1533 s->withdrawn = false;
1534
1535 tried = true;
1536 }
1537
1538 if (tried)
1539 manager_refresh_rrs(m);
1540
1541 return tried;
1542 }