1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/ipv6.h>
5 #include <netinet/in.h>
10 #include "sd-netlink.h"
11 #include "sd-network.h"
14 #include "alloc-util.h"
15 #include "daemon-util.h"
16 #include "dirent-util.h"
17 #include "dns-domain.h"
18 #include "errno-util.h"
19 #include "event-util.h"
21 #include "hostname-setup.h"
22 #include "hostname-util.h"
24 #include "iovec-util.h"
25 #include "json-util.h"
26 #include "memstream-util.h"
27 #include "missing-network.h"
28 #include "ordered-set.h"
29 #include "parse-util.h"
30 #include "random-util.h"
31 #include "resolved-bus.h"
32 #include "resolved-conf.h"
33 #include "resolved-dns-answer.h"
34 #include "resolved-dns-delegate.h"
35 #include "resolved-dns-packet.h"
36 #include "resolved-dns-query.h"
37 #include "resolved-dns-question.h"
38 #include "resolved-dns-rr.h"
39 #include "resolved-dns-scope.h"
40 #include "resolved-dns-search-domain.h"
41 #include "resolved-dns-server.h"
42 #include "resolved-dns-stub.h"
43 #include "resolved-dns-transaction.h"
44 #include "resolved-dnssd.h"
45 #include "resolved-etc-hosts.h"
46 #include "resolved-link.h"
47 #include "resolved-llmnr.h"
48 #include "resolved-manager.h"
49 #include "resolved-mdns.h"
50 #include "resolved-resolv-conf.h"
51 #include "resolved-socket-graveyard.h"
52 #include "resolved-util.h"
53 #include "resolved-varlink.h"
55 #include "socket-util.h"
56 #include "string-util.h"
57 #include "time-util.h"
58 #include "varlink-util.h"
60 #define SEND_TIMEOUT_USEC (200 * USEC_PER_MSEC)
62 static int manager_process_link(sd_netlink
*rtnl
, sd_netlink_message
*mm
, void *userdata
) {
63 Manager
*m
= ASSERT_PTR(userdata
);
71 r
= sd_netlink_message_get_type(mm
, &type
);
75 r
= sd_rtnl_message_link_get_ifindex(mm
, &ifindex
);
79 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
87 r
= link_new(m
, &l
, ifindex
);
92 r
= link_process_rtnl(l
, mm
);
101 log_debug("Found new link %i/%s", ifindex
, l
->ifname
);
108 log_debug("Removing link %i/%s", l
->ifindex
, l
->ifname
);
112 /* Make sure DNS servers are dropped from written resolv.conf if their link goes away */
113 manager_write_resolv_conf(m
);
119 /* Now check all the links, and if mDNS/llmr are disabled everywhere, stop them globally too. */
120 manager_llmnr_maybe_stop(m
);
121 manager_mdns_maybe_stop(m
);
123 /* The accessible flag on link DNS servers will have been reset by
124 * link_update(). Just reset the global DNS servers. */
125 (void) manager_send_dns_configuration_changed(m
, NULL
, /* reset= */ true);
130 log_warning_errno(r
, "Failed to process RTNL link message: %m");
134 static int manager_process_address(sd_netlink
*rtnl
, sd_netlink_message
*mm
, void *userdata
) {
135 Manager
*m
= ASSERT_PTR(userdata
);
136 union in_addr_union address
, broadcast
= {};
138 int r
, ifindex
, family
;
145 r
= sd_netlink_message_get_type(mm
, &type
);
149 r
= sd_rtnl_message_addr_get_ifindex(mm
, &ifindex
);
153 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
157 r
= sd_rtnl_message_addr_get_family(mm
, &family
);
164 sd_netlink_message_read_in_addr(mm
, IFA_BROADCAST
, &broadcast
.in
);
165 r
= sd_netlink_message_read_in_addr(mm
, IFA_LOCAL
, &address
.in
);
167 r
= sd_netlink_message_read_in_addr(mm
, IFA_ADDRESS
, &address
.in
);
175 r
= sd_netlink_message_read_in6_addr(mm
, IFA_LOCAL
, &address
.in6
);
177 r
= sd_netlink_message_read_in6_addr(mm
, IFA_ADDRESS
, &address
.in6
);
188 a
= link_find_address(l
, family
, &address
);
195 r
= link_address_new(l
, &a
, family
, &address
, &broadcast
);
200 r
= link_address_update_rtnl(a
, mm
);
207 link_address_free(a
);
211 (void) manager_send_dns_configuration_changed(m
, l
, /* reset= */ true);
216 log_warning_errno(r
, "Failed to process RTNL address message: %m");
220 static int manager_process_route(sd_netlink
*rtnl
, sd_netlink_message
*mm
, void *userdata
) {
221 Manager
*m
= ASSERT_PTR(userdata
);
224 uint32_t ifindex
= 0;
230 r
= sd_netlink_message_get_type(mm
, &type
);
232 log_warning_errno(r
, "Failed to get rtnl message type, ignoring: %m");
236 if (!IN_SET(type
, RTM_NEWROUTE
, RTM_DELROUTE
)) {
237 log_warning("Unexpected message type %u when processing route, ignoring.", type
);
241 r
= sd_netlink_message_read_u32(mm
, RTA_OIF
, &ifindex
);
243 log_full_errno(r
== -ENODATA
? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to get route ifindex, ignoring: %m");
245 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
247 (void) manager_send_dns_configuration_changed(m
, l
, /* reset= */ true);
252 static int manager_rtnl_listen(Manager
*m
) {
253 _cleanup_(sd_netlink_message_unrefp
) sd_netlink_message
*req
= NULL
, *reply
= NULL
;
258 /* First, subscribe to interfaces coming and going */
259 r
= sd_netlink_open(&m
->rtnl
);
263 r
= sd_netlink_attach_event(m
->rtnl
, m
->event
, SD_EVENT_PRIORITY_IMPORTANT
);
267 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_NEWLINK
, manager_process_link
, NULL
, m
, "resolve-NEWLINK");
271 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_DELLINK
, manager_process_link
, NULL
, m
, "resolve-DELLINK");
275 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_NEWADDR
, manager_process_address
, NULL
, m
, "resolve-NEWADDR");
279 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_DELADDR
, manager_process_address
, NULL
, m
, "resolve-DELADDR");
283 /* Then, enumerate all links */
284 r
= sd_rtnl_message_new_link(m
->rtnl
, &req
, RTM_GETLINK
, 0);
288 r
= sd_netlink_message_set_request_dump(req
, true);
292 r
= sd_netlink_call(m
->rtnl
, req
, 0, &reply
);
296 for (sd_netlink_message
*i
= reply
; i
; i
= sd_netlink_message_next(i
)) {
297 r
= manager_process_link(m
->rtnl
, i
, m
);
302 req
= sd_netlink_message_unref(req
);
303 reply
= sd_netlink_message_unref(reply
);
305 /* Finally, enumerate all addresses, too */
306 r
= sd_rtnl_message_new_addr(m
->rtnl
, &req
, RTM_GETADDR
, 0, AF_UNSPEC
);
310 r
= sd_netlink_message_set_request_dump(req
, true);
314 r
= sd_netlink_call(m
->rtnl
, req
, 0, &reply
);
318 for (sd_netlink_message
*i
= reply
; i
; i
= sd_netlink_message_next(i
)) {
319 r
= manager_process_address(m
->rtnl
, i
, m
);
327 static int on_network_event(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
328 Manager
*m
= ASSERT_PTR(userdata
);
332 sd_network_monitor_flush(m
->network_monitor
);
334 HASHMAP_FOREACH(l
, m
->links
) {
337 log_warning_errno(r
, "Failed to update monitor information for %i: %m", l
->ifindex
);
340 (void) manager_write_resolv_conf(m
);
341 (void) manager_send_changed(m
, "DNS");
342 (void) manager_send_dns_configuration_changed(m
, NULL
, /* reset= */ true);
344 /* Now check all the links, and if mDNS/llmr are disabled everywhere, stop them globally too. */
345 manager_llmnr_maybe_stop(m
);
346 manager_mdns_maybe_stop(m
);
350 static int manager_network_monitor_listen(Manager
*m
) {
355 r
= sd_network_monitor_new(&m
->network_monitor
, NULL
);
359 fd
= sd_network_monitor_get_fd(m
->network_monitor
);
363 events
= sd_network_monitor_get_events(m
->network_monitor
);
367 r
= sd_event_add_io(m
->event
, &m
->network_event_source
, fd
, events
, &on_network_event
, m
);
371 r
= sd_event_source_set_priority(m
->network_event_source
, SD_EVENT_PRIORITY_IMPORTANT
+5);
375 (void) sd_event_source_set_description(m
->network_event_source
, "network-monitor");
380 static int manager_clock_change_listen(Manager
*m
);
382 static int on_clock_change(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
383 Manager
*m
= ASSERT_PTR(userdata
);
385 /* The clock has changed, let's flush all caches. Why that? That's because DNSSEC validation takes
386 * the system clock into consideration, and if the clock changes the old validations might have been
387 * wrong. Let's redo all validation with the new, correct time.
389 * (Also, this is triggered after system suspend, which is also a good reason to drop caches, since
390 * we might be connected to a different network now without this being visible in a dropped link
393 log_info("Clock change detected. Flushing caches.");
394 manager_flush_caches(m
, LOG_DEBUG
/* downgrade the functions own log message, since we already logged here at LOG_INFO level */);
396 /* The clock change timerfd is unusable after it triggered once, create a new one. */
397 return manager_clock_change_listen(m
);
400 static int manager_clock_change_listen(Manager
*m
) {
405 m
->clock_change_event_source
= sd_event_source_disable_unref(m
->clock_change_event_source
);
407 r
= event_add_time_change(m
->event
, &m
->clock_change_event_source
, on_clock_change
, m
);
409 return log_error_errno(r
, "Failed to create clock change event source: %m");
414 static int determine_hostnames(char **full_hostname
, char **llmnr_hostname
, char **mdns_hostname
) {
415 _cleanup_free_
char *h
= NULL
, *n
= NULL
;
418 assert(full_hostname
);
419 assert(llmnr_hostname
);
420 assert(mdns_hostname
);
422 r
= resolve_system_hostname(&h
, &n
);
426 r
= dns_name_concat(n
, "local", 0, mdns_hostname
);
428 return log_error_errno(r
, "Failed to determine mDNS hostname: %m");
430 *llmnr_hostname
= TAKE_PTR(n
);
431 *full_hostname
= TAKE_PTR(h
);
436 static char* fallback_hostname(void) {
438 /* Determine the fall back hostname. For exposing this system to the outside world, we cannot have it
439 * to be "localhost" even if that's the default hostname. In this case, let's revert to "linux"
442 _cleanup_free_
char *n
= get_default_hostname();
447 return strdup("linux");
452 static int make_fallback_hostnames(char **full_hostname
, char **llmnr_hostname
, char **mdns_hostname
) {
453 _cleanup_free_
char *h
= NULL
, *n
= NULL
, *m
= NULL
;
454 char label
[DNS_LABEL_MAX
+1];
458 assert(full_hostname
);
459 assert(llmnr_hostname
);
460 assert(mdns_hostname
);
462 p
= h
= fallback_hostname();
466 r
= dns_label_unescape(&p
, label
, sizeof label
, 0);
468 return log_error_errno(r
, "Failed to unescape fallback hostname: %m");
470 assert(r
> 0); /* The fallback hostname must have at least one label */
472 r
= dns_label_escape_new(label
, r
, &n
);
474 return log_error_errno(r
, "Failed to escape fallback hostname: %m");
476 r
= dns_name_concat(n
, "local", 0, &m
);
478 return log_error_errno(r
, "Failed to concatenate mDNS hostname: %m");
480 *llmnr_hostname
= TAKE_PTR(n
);
481 *mdns_hostname
= TAKE_PTR(m
);
482 *full_hostname
= TAKE_PTR(h
);
487 static int on_hostname_change(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
488 _cleanup_free_
char *full_hostname
= NULL
, *llmnr_hostname
= NULL
, *mdns_hostname
= NULL
;
489 Manager
*m
= ASSERT_PTR(userdata
);
490 bool llmnr_hostname_changed
;
493 r
= determine_hostnames(&full_hostname
, &llmnr_hostname
, &mdns_hostname
);
495 log_warning_errno(r
, "Failed to determine the local hostname and LLMNR/mDNS names, ignoring: %m");
496 return 0; /* ignore invalid hostnames */
499 llmnr_hostname_changed
= !streq(llmnr_hostname
, m
->llmnr_hostname
);
500 if (streq(full_hostname
, m
->full_hostname
) &&
501 !llmnr_hostname_changed
&&
502 streq(mdns_hostname
, m
->mdns_hostname
))
505 log_info("System hostname changed to '%s'.", full_hostname
);
507 free_and_replace(m
->full_hostname
, full_hostname
);
508 free_and_replace(m
->llmnr_hostname
, llmnr_hostname
);
509 free_and_replace(m
->mdns_hostname
, mdns_hostname
);
511 manager_refresh_rrs(m
);
512 (void) manager_send_changed(m
, "LLMNRHostname");
517 static int manager_watch_hostname(Manager
*m
) {
522 m
->hostname_fd
= open("/proc/sys/kernel/hostname",
523 O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
524 if (m
->hostname_fd
< 0) {
525 log_warning_errno(errno
, "Failed to watch hostname: %m");
529 r
= sd_event_add_io(m
->event
, &m
->hostname_event_source
, m
->hostname_fd
, 0, on_hostname_change
, m
);
531 return log_error_errno(r
, "Failed to add hostname event source: %m");
533 (void) sd_event_source_set_description(m
->hostname_event_source
, "hostname");
535 r
= determine_hostnames(&m
->full_hostname
, &m
->llmnr_hostname
, &m
->mdns_hostname
);
537 _cleanup_free_
char *d
= NULL
;
539 d
= fallback_hostname();
543 log_info("Defaulting to hostname '%s'.", d
);
545 r
= make_fallback_hostnames(&m
->full_hostname
, &m
->llmnr_hostname
, &m
->mdns_hostname
);
549 log_info("Using system hostname '%s'.", m
->full_hostname
);
554 static int manager_sigusr1(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
555 _cleanup_(memstream_done
) MemStream ms
= {};
556 Manager
*m
= ASSERT_PTR(userdata
);
563 f
= memstream_init(&ms
);
567 LIST_FOREACH(scopes
, scope
, m
->dns_scopes
)
568 dns_scope_dump(scope
, f
);
570 LIST_FOREACH(servers
, server
, m
->dns_servers
)
571 dns_server_dump(server
, f
);
572 LIST_FOREACH(servers
, server
, m
->fallback_dns_servers
)
573 dns_server_dump(server
, f
);
574 HASHMAP_FOREACH(l
, m
->links
)
575 LIST_FOREACH(servers
, server
, l
->dns_servers
)
576 dns_server_dump(server
, f
);
577 DnsDelegate
*delegate
;
578 HASHMAP_FOREACH(delegate
, m
->delegates
)
579 LIST_FOREACH(servers
, server
, delegate
->dns_servers
)
580 dns_server_dump(server
, f
);
582 return memstream_dump(LOG_INFO
, &ms
);
585 static int manager_sigusr2(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
586 Manager
*m
= ASSERT_PTR(userdata
);
591 manager_flush_caches(m
, LOG_INFO
);
596 static int manager_sigrtmin1(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
597 Manager
*m
= ASSERT_PTR(userdata
);
602 manager_reset_server_features(m
);
606 static int manager_memory_pressure(sd_event_source
*s
, void *userdata
) {
607 Manager
*m
= ASSERT_PTR(userdata
);
609 log_info("Under memory pressure, flushing caches.");
611 manager_flush_caches(m
, LOG_INFO
);
612 sd_event_trim_memory();
617 static int manager_memory_pressure_listen(Manager
*m
) {
622 r
= sd_event_add_memory_pressure(m
->event
, NULL
, manager_memory_pressure
, m
);
624 log_full_errno(ERRNO_IS_NOT_SUPPORTED(r
) || ERRNO_IS_PRIVILEGE(r
) || (r
== -EHOSTDOWN
)? LOG_DEBUG
: LOG_NOTICE
, r
,
625 "Failed to install memory pressure event source, ignoring: %m");
630 static void manager_set_defaults(Manager
*m
) {
633 m
->llmnr_support
= DEFAULT_LLMNR_MODE
;
634 m
->mdns_support
= DEFAULT_MDNS_MODE
;
635 m
->dnssec_mode
= DEFAULT_DNSSEC_MODE
;
636 m
->dns_over_tls_mode
= DEFAULT_DNS_OVER_TLS_MODE
;
637 m
->enable_cache
= DNS_CACHE_MODE_YES
;
638 m
->dns_stub_listener_mode
= DNS_STUB_LISTENER_YES
;
639 m
->read_etc_hosts
= true;
640 m
->resolve_unicast_single_label
= false;
641 m
->cache_from_localhost
= false;
642 m
->stale_retention_usec
= 0;
643 m
->refuse_record_types
= set_free(m
->refuse_record_types
);
646 static int manager_dispatch_reload_signal(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
647 Manager
*m
= ASSERT_PTR(userdata
);
651 (void) notify_reloading();
653 dns_server_unlink_on_reload(m
->dns_servers
);
654 dns_server_unlink_on_reload(m
->fallback_dns_servers
);
655 m
->dns_extra_stub_listeners
= ordered_set_free(m
->dns_extra_stub_listeners
);
656 manager_dns_stub_stop(m
);
657 dnssd_registered_service_clear_on_reload(m
->dnssd_registered_services
);
658 m
->unicast_scope
= dns_scope_free(m
->unicast_scope
);
659 m
->delegates
= hashmap_free(m
->delegates
);
660 dns_trust_anchor_flush(&m
->trust_anchor
);
662 manager_set_defaults(m
);
664 r
= dns_trust_anchor_load(&m
->trust_anchor
);
666 return sd_event_exit(sd_event_source_get_event(s
), r
);
668 r
= manager_parse_config_file(m
);
670 log_warning_errno(r
, "Failed to parse configuration file on reload, ignoring: %m");
672 log_info("Config file reloaded.");
674 (void) dnssd_load(m
);
675 (void) manager_load_delegates(m
);
677 /* The default scope configuration is influenced by the manager's configuration (modes, etc.), so
678 * recreate it on reload. */
679 r
= dns_scope_new(m
, &m
->unicast_scope
, DNS_SCOPE_GLOBAL
, /* link= */ NULL
, /* delegate= */ NULL
, DNS_PROTOCOL_DNS
, AF_UNSPEC
);
681 return sd_event_exit(sd_event_source_get_event(s
), r
);
683 /* A link's unicast scope may also be influenced by the manager's configuration. I.e., DNSSEC= and DNSOverTLS=
684 * from the manager will be used if not explicitly configured on the link. Free the scopes here so that
685 * link_allocate_scopes() in on_network_event() re-creates them. */
686 HASHMAP_FOREACH(l
, m
->links
)
687 l
->unicast_scope
= dns_scope_free(l
->unicast_scope
);
689 /* The configuration has changed, so reload the per-interface configuration too in order to take
690 * into account any changes (e.g.: enable/disable DNSSEC). */
691 r
= on_network_event(/* source= */ NULL
, -EBADF
, /* revents= */ 0, m
);
693 log_warning_errno(r
, "Failed to update network information on reload, ignoring: %m");
695 /* We have new configuration, which means potentially new servers, so close all connections and drop
696 * all caches, so that we can start fresh. */
697 (void) dns_stream_disconnect_all(m
);
698 manager_flush_caches(m
, LOG_INFO
);
699 manager_verify_all(m
);
701 r
= manager_dns_stub_start(m
);
703 return sd_event_exit(sd_event_source_get_event(s
), r
);
705 (void) sd_notify(/* unset_environment= */ false, NOTIFY_READY_MESSAGE
);
709 int manager_new(Manager
**ret
) {
710 _cleanup_(manager_freep
) Manager
*m
= NULL
;
720 .llmnr_ipv4_udp_fd
= -EBADF
,
721 .llmnr_ipv6_udp_fd
= -EBADF
,
722 .llmnr_ipv4_tcp_fd
= -EBADF
,
723 .llmnr_ipv6_tcp_fd
= -EBADF
,
724 .mdns_ipv4_fd
= -EBADF
,
725 .mdns_ipv6_fd
= -EBADF
,
726 .hostname_fd
= -EBADF
,
728 .read_resolv_conf
= true,
729 .need_builtin_fallbacks
= true,
730 .etc_hosts_last
= USEC_INFINITY
,
732 .sigrtmin18_info
.memory_pressure_handler
= manager_memory_pressure
,
733 .sigrtmin18_info
.memory_pressure_userdata
= m
,
736 manager_set_defaults(m
);
738 r
= dns_trust_anchor_load(&m
->trust_anchor
);
742 r
= manager_parse_config_file(m
);
744 log_warning_errno(r
, "Failed to parse configuration file, ignoring: %m");
746 #if ENABLE_DNS_OVER_TLS
747 r
= dnstls_manager_init(m
);
752 r
= sd_event_default(&m
->event
);
756 r
= sd_event_set_signal_exit(m
->event
, true);
760 (void) sd_event_set_watchdog(m
->event
, true);
762 r
= manager_watch_hostname(m
);
766 (void) dnssd_load(m
);
767 (void) manager_load_delegates(m
);
769 r
= dns_scope_new(m
, &m
->unicast_scope
, DNS_SCOPE_GLOBAL
, /* link= */ NULL
, /* delegate= */ NULL
, DNS_PROTOCOL_DNS
, AF_UNSPEC
);
773 r
= manager_network_monitor_listen(m
);
777 r
= manager_rtnl_listen(m
);
781 r
= manager_clock_change_listen(m
);
785 r
= manager_memory_pressure_listen(m
);
789 r
= manager_connect_bus(m
);
793 r
= sd_event_add_signal(m
->event
, /* ret= */ NULL
, SIGHUP
| SD_EVENT_SIGNAL_PROCMASK
, manager_dispatch_reload_signal
, m
);
795 return log_debug_errno(r
, "Failed to install SIGHUP handler: %m");
797 r
= sd_event_add_signal(m
->event
, /* ret= */ NULL
, SIGUSR1
| SD_EVENT_SIGNAL_PROCMASK
, manager_sigusr1
, m
);
799 return log_debug_errno(r
, "Failed to install SIGUSR1 handler: %m");
801 r
= sd_event_add_signal(m
->event
, /* ret= */ NULL
, SIGUSR2
| SD_EVENT_SIGNAL_PROCMASK
, manager_sigusr2
, m
);
803 return log_debug_errno(r
, "Failed to install SIGUSR2 handler: %m");
805 r
= sd_event_add_signal(m
->event
, /* ret= */ NULL
, (SIGRTMIN
+1) | SD_EVENT_SIGNAL_PROCMASK
, manager_sigrtmin1
, m
);
807 return log_debug_errno(r
, "Failed to install SIGRTMIN+1 handler: %m");
809 r
= sd_event_add_signal(m
->event
, /* ret= */ NULL
, (SIGRTMIN
+18) | SD_EVENT_SIGNAL_PROCMASK
, sigrtmin18_handler
, &m
->sigrtmin18_info
);
811 return log_debug_errno(r
, "Failed to install SIGRTMIN+18 handler: %m");
813 manager_cleanup_saved_user(m
);
820 int manager_start(Manager
*m
) {
825 r
= manager_dns_stub_start(m
);
829 r
= manager_varlink_init(m
);
836 Manager
* manager_free(Manager
*m
) {
838 DnssdRegisteredService
*s
;
839 DnsServiceBrowser
*sb
;
844 dns_server_unlink_all(m
->dns_servers
);
845 dns_server_unlink_all(m
->fallback_dns_servers
);
846 dns_search_domain_unlink_all(m
->search_domains
);
848 while ((l
= hashmap_first(m
->links
)))
851 m
->delegates
= hashmap_free(m
->delegates
);
853 while (m
->dns_queries
)
854 dns_query_free(m
->dns_queries
);
856 m
->stub_queries_by_packet
= hashmap_free(m
->stub_queries_by_packet
);
857 m
->unicast_scope
= dns_scope_free(m
->unicast_scope
);
859 /* At this point only orphaned streams should remain. All others should have been freed already by their
861 while (m
->dns_streams
)
862 dns_stream_unref(m
->dns_streams
);
864 #if ENABLE_DNS_OVER_TLS
865 dnstls_manager_free(m
);
868 set_free(m
->refuse_record_types
);
869 hashmap_free(m
->links
);
870 hashmap_free(m
->dns_transactions
);
872 sd_event_source_unref(m
->network_event_source
);
873 sd_network_monitor_unref(m
->network_monitor
);
875 sd_netlink_slot_unref(m
->netlink_new_route_slot
);
876 sd_netlink_slot_unref(m
->netlink_del_route_slot
);
877 sd_netlink_unref(m
->rtnl
);
878 sd_event_source_unref(m
->rtnl_event_source
);
879 sd_event_source_unref(m
->clock_change_event_source
);
881 sd_json_variant_unref(m
->dns_configuration_json
);
883 manager_llmnr_stop(m
);
884 manager_mdns_stop(m
);
885 manager_dns_stub_stop(m
);
886 manager_varlink_done(m
);
888 manager_socket_graveyard_clear(m
);
890 ordered_set_free(m
->dns_extra_stub_listeners
);
892 hashmap_free(m
->polkit_registry
);
894 sd_bus_flush_close_unref(m
->bus
);
896 dns_resource_key_unref(m
->llmnr_host_ipv4_key
);
897 dns_resource_key_unref(m
->llmnr_host_ipv6_key
);
898 dns_resource_key_unref(m
->mdns_host_ipv4_key
);
899 dns_resource_key_unref(m
->mdns_host_ipv6_key
);
901 sd_event_source_unref(m
->hostname_event_source
);
902 safe_close(m
->hostname_fd
);
904 sd_event_unref(m
->event
);
906 free(m
->full_hostname
);
907 free(m
->llmnr_hostname
);
908 free(m
->mdns_hostname
);
910 while ((s
= hashmap_first(m
->dnssd_registered_services
)))
911 dnssd_registered_service_free(s
);
912 hashmap_free(m
->dnssd_registered_services
);
914 dns_trust_anchor_flush(&m
->trust_anchor
);
915 manager_etc_hosts_flush(m
);
917 while ((sb
= hashmap_first(m
->dns_service_browsers
)))
918 dns_service_browser_free(sb
);
919 hashmap_free(m
->dns_service_browsers
);
924 int manager_recv(Manager
*m
, int fd
, DnsProtocol protocol
, DnsPacket
**ret
) {
925 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
926 CMSG_BUFFER_TYPE(CMSG_SPACE(MAXSIZE(struct in_pktinfo
, struct in6_pktinfo
))
927 + CMSG_SPACE(int) /* ttl/hoplimit */
928 + EXTRA_CMSG_SPACE
/* kernel appears to require extra buffer space */) control
;
929 union sockaddr_union sa
;
933 .msg_namelen
= sizeof(sa
),
936 .msg_control
= &control
,
937 .msg_controllen
= sizeof(control
),
939 struct cmsghdr
*cmsg
;
947 ms
= next_datagram_size_fd(fd
);
951 r
= dns_packet_new(&p
, protocol
, ms
, DNS_PACKET_SIZE_MAX
);
955 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->allocated
);
957 l
= recvmsg_safe(fd
, &mh
, 0);
958 if (ERRNO_IS_NEG_TRANSIENT(l
))
963 p
->size
= (size_t) l
;
965 p
->family
= sa
.sa
.sa_family
;
966 p
->ipproto
= IPPROTO_UDP
;
967 if (p
->family
== AF_INET
) {
968 p
->sender
.in
= sa
.in
.sin_addr
;
969 p
->sender_port
= be16toh(sa
.in
.sin_port
);
970 } else if (p
->family
== AF_INET6
) {
971 p
->sender
.in6
= sa
.in6
.sin6_addr
;
972 p
->sender_port
= be16toh(sa
.in6
.sin6_port
);
973 p
->ifindex
= sa
.in6
.sin6_scope_id
;
975 return -EAFNOSUPPORT
;
977 p
->timestamp
= now(CLOCK_BOOTTIME
);
979 CMSG_FOREACH(cmsg
, &mh
) {
981 if (cmsg
->cmsg_level
== IPPROTO_IPV6
) {
982 assert(p
->family
== AF_INET6
);
984 switch (cmsg
->cmsg_type
) {
987 struct in6_pktinfo
*i
= CMSG_TYPED_DATA(cmsg
, struct in6_pktinfo
);
990 p
->ifindex
= i
->ipi6_ifindex
;
992 p
->destination
.in6
= i
->ipi6_addr
;
997 p
->ttl
= *CMSG_TYPED_DATA(cmsg
, int);
1000 case IPV6_RECVFRAGSIZE
:
1001 p
->fragsize
= *CMSG_TYPED_DATA(cmsg
, int);
1004 } else if (cmsg
->cmsg_level
== IPPROTO_IP
) {
1005 assert(p
->family
== AF_INET
);
1007 switch (cmsg
->cmsg_type
) {
1010 struct in_pktinfo
*i
= CMSG_TYPED_DATA(cmsg
, struct in_pktinfo
);
1012 if (p
->ifindex
<= 0)
1013 p
->ifindex
= i
->ipi_ifindex
;
1015 p
->destination
.in
= i
->ipi_addr
;
1020 p
->ttl
= *CMSG_TYPED_DATA(cmsg
, int);
1023 case IP_RECVFRAGSIZE
:
1024 p
->fragsize
= *CMSG_TYPED_DATA(cmsg
, int);
1030 /* The Linux kernel sets the interface index to the loopback
1031 * device if the packet came from the local host since it
1032 * avoids the routing table in such a case. Let's unset the
1033 * interface index in such a case. */
1034 if (p
->ifindex
== LOOPBACK_IFINDEX
)
1037 if (protocol
!= DNS_PROTOCOL_DNS
) {
1038 /* If we don't know the interface index still, we look for the
1039 * first local interface with a matching address. Yuck! */
1040 if (p
->ifindex
<= 0)
1041 p
->ifindex
= manager_find_ifindex(m
, p
->family
, &p
->destination
);
1044 log_debug("Received %s UDP packet of size %zu, ifindex=%i, ttl=%u, fragsize=%zu, sender=%s, destination=%s",
1045 dns_protocol_to_string(protocol
), p
->size
, p
->ifindex
, p
->ttl
, p
->fragsize
,
1046 IN_ADDR_TO_STRING(p
->family
, &p
->sender
),
1047 IN_ADDR_TO_STRING(p
->family
, &p
->destination
));
1053 int sendmsg_loop(int fd
, struct msghdr
*mh
, int flags
) {
1060 end
= usec_add(now(CLOCK_MONOTONIC
), SEND_TIMEOUT_USEC
);
1063 if (sendmsg(fd
, mh
, flags
) >= 0)
1067 if (errno
!= EAGAIN
)
1070 r
= fd_wait_for_event(fd
, POLLOUT
, LESS_BY(end
, now(CLOCK_MONOTONIC
)));
1071 if (ERRNO_IS_NEG_TRANSIENT(r
))
1080 static int write_loop(int fd
, void *message
, size_t length
) {
1087 end
= usec_add(now(CLOCK_MONOTONIC
), SEND_TIMEOUT_USEC
);
1090 if (write(fd
, message
, length
) >= 0)
1094 if (errno
!= EAGAIN
)
1097 r
= fd_wait_for_event(fd
, POLLOUT
, LESS_BY(end
, now(CLOCK_MONOTONIC
)));
1098 if (ERRNO_IS_NEG_TRANSIENT(r
))
1107 int manager_write(Manager
*m
, int fd
, DnsPacket
*p
) {
1110 log_debug("Sending %s%s packet with id %" PRIu16
" of size %zu.",
1111 DNS_PACKET_TC(p
) ? "truncated (!) " : "",
1112 DNS_PACKET_QR(p
) ? "response" : "query",
1116 r
= write_loop(fd
, DNS_PACKET_DATA(p
), p
->size
);
1123 static int manager_ipv4_send(
1127 const struct in_addr
*destination
,
1129 const struct in_addr
*source
,
1132 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in_pktinfo
))) control
= {};
1133 union sockaddr_union sa
;
1135 struct msghdr mh
= {
1139 .msg_namelen
= sizeof(sa
.in
),
1144 assert(destination
);
1148 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->size
);
1150 sa
= (union sockaddr_union
) {
1151 .in
.sin_family
= AF_INET
,
1152 .in
.sin_addr
= *destination
,
1153 .in
.sin_port
= htobe16(port
),
1157 struct cmsghdr
*cmsg
;
1158 struct in_pktinfo
*pi
;
1160 mh
.msg_control
= &control
;
1161 mh
.msg_controllen
= sizeof(control
);
1163 cmsg
= CMSG_FIRSTHDR(&mh
);
1164 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
1165 cmsg
->cmsg_level
= IPPROTO_IP
;
1166 cmsg
->cmsg_type
= IP_PKTINFO
;
1168 pi
= CMSG_TYPED_DATA(cmsg
, struct in_pktinfo
);
1169 pi
->ipi_ifindex
= ifindex
;
1172 pi
->ipi_spec_dst
= *source
;
1175 return sendmsg_loop(fd
, &mh
, 0);
1178 static int manager_ipv6_send(
1182 const struct in6_addr
*destination
,
1184 const struct in6_addr
*source
,
1187 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in6_pktinfo
))) control
= {};
1188 union sockaddr_union sa
;
1190 struct msghdr mh
= {
1194 .msg_namelen
= sizeof(sa
.in6
),
1199 assert(destination
);
1203 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->size
);
1205 sa
= (union sockaddr_union
) {
1206 .in6
.sin6_family
= AF_INET6
,
1207 .in6
.sin6_addr
= *destination
,
1208 .in6
.sin6_port
= htobe16(port
),
1209 .in6
.sin6_scope_id
= ifindex
,
1213 struct cmsghdr
*cmsg
;
1214 struct in6_pktinfo
*pi
;
1216 mh
.msg_control
= &control
;
1217 mh
.msg_controllen
= sizeof(control
);
1219 cmsg
= CMSG_FIRSTHDR(&mh
);
1220 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
1221 cmsg
->cmsg_level
= IPPROTO_IPV6
;
1222 cmsg
->cmsg_type
= IPV6_PKTINFO
;
1224 pi
= CMSG_TYPED_DATA(cmsg
, struct in6_pktinfo
);
1225 pi
->ipi6_ifindex
= ifindex
;
1228 pi
->ipi6_addr
= *source
;
1231 return sendmsg_loop(fd
, &mh
, 0);
1234 static int dns_question_to_json(DnsQuestion
*q
, sd_json_variant
**ret
) {
1235 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*l
= NULL
;
1236 DnsResourceKey
*key
;
1241 DNS_QUESTION_FOREACH(key
, q
) {
1242 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
1244 r
= dns_resource_key_to_json(key
, &v
);
1248 r
= sd_json_variant_append_array(&l
, v
);
1257 int manager_monitor_send(Manager
*m
, DnsQuery
*q
) {
1258 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*jquestion
= NULL
, *jcollected_questions
= NULL
, *janswer
= NULL
;
1259 _cleanup_(dns_question_unrefp
) DnsQuestion
*merged
= NULL
;
1265 if (set_isempty(m
->varlink_query_results_subscription
))
1268 /* Merge all questions into one */
1269 r
= dns_question_merge(q
->question_idna
, q
->question_utf8
, &merged
);
1271 return log_error_errno(r
, "Failed to merge UTF8/IDNA questions: %m");
1273 if (q
->question_bypass
) {
1274 _cleanup_(dns_question_unrefp
) DnsQuestion
*merged2
= NULL
;
1276 r
= dns_question_merge(merged
, q
->question_bypass
->question
, &merged2
);
1278 return log_error_errno(r
, "Failed to merge UTF8/IDNA questions and DNS packet question: %m");
1280 dns_question_unref(merged
);
1281 merged
= TAKE_PTR(merged2
);
1284 /* Convert the current primary question to JSON */
1285 r
= dns_question_to_json(merged
, &jquestion
);
1287 return log_error_errno(r
, "Failed to convert question to JSON: %m");
1289 /* Generate a JSON array of the questions preceding the current one in the CNAME chain */
1290 r
= dns_question_to_json(q
->collected_questions
, &jcollected_questions
);
1292 return log_error_errno(r
, "Failed to convert question to JSON: %m");
1294 DNS_ANSWER_FOREACH_ITEM(rri
, q
->answer
) {
1295 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
1297 r
= dns_resource_record_to_json(rri
->rr
, &v
);
1299 return log_error_errno(r
, "Failed to convert answer resource record to JSON: %m");
1301 r
= dns_resource_record_to_wire_format(rri
->rr
, /* canonical= */ false); /* don't use DNSSEC canonical format, since it removes casing, but we want that for DNS_SD compat */
1303 return log_error_errno(r
, "Failed to generate RR wire format: %m");
1305 r
= sd_json_variant_append_arraybo(
1307 SD_JSON_BUILD_PAIR_CONDITION(!!v
, "rr", SD_JSON_BUILD_VARIANT(v
)),
1308 SD_JSON_BUILD_PAIR("raw", SD_JSON_BUILD_BASE64(rri
->rr
->wire_format
, rri
->rr
->wire_format_size
)),
1309 SD_JSON_BUILD_PAIR_CONDITION(rri
->ifindex
> 0, "ifindex", SD_JSON_BUILD_INTEGER(rri
->ifindex
)));
1311 return log_debug_errno(r
, "Failed to append notification entry to array: %m");
1314 r
= varlink_many_notifybo(
1315 m
->varlink_query_results_subscription
,
1316 SD_JSON_BUILD_PAIR("state", SD_JSON_BUILD_STRING(dns_transaction_state_to_string(q
->state
))),
1317 SD_JSON_BUILD_PAIR_CONDITION(q
->state
== DNS_TRANSACTION_DNSSEC_FAILED
,
1318 "result", SD_JSON_BUILD_STRING(dnssec_result_to_string(q
->answer_dnssec_result
))),
1319 SD_JSON_BUILD_PAIR_CONDITION(q
->state
== DNS_TRANSACTION_RCODE_FAILURE
,
1320 "rcode", SD_JSON_BUILD_INTEGER(q
->answer_rcode
)),
1321 SD_JSON_BUILD_PAIR_CONDITION(q
->state
== DNS_TRANSACTION_ERRNO
,
1322 "errno", SD_JSON_BUILD_INTEGER(q
->answer_errno
)),
1323 SD_JSON_BUILD_PAIR_CONDITION(IN_SET(q
->state
,
1324 DNS_TRANSACTION_DNSSEC_FAILED
,
1325 DNS_TRANSACTION_RCODE_FAILURE
) &&
1326 q
->answer_ede_rcode
>= 0,
1327 "extendedDNSErrorCode", SD_JSON_BUILD_INTEGER(q
->answer_ede_rcode
)),
1328 SD_JSON_BUILD_PAIR_CONDITION(IN_SET(q
->state
,
1329 DNS_TRANSACTION_DNSSEC_FAILED
,
1330 DNS_TRANSACTION_RCODE_FAILURE
) &&
1331 q
->answer_ede_rcode
>= 0 && !isempty(q
->answer_ede_msg
),
1332 "extendedDNSErrorMessage", SD_JSON_BUILD_STRING(q
->answer_ede_msg
)),
1333 SD_JSON_BUILD_PAIR("question", SD_JSON_BUILD_VARIANT(jquestion
)),
1334 SD_JSON_BUILD_PAIR_CONDITION(!!jcollected_questions
,
1335 "collectedQuestions", SD_JSON_BUILD_VARIANT(jcollected_questions
)),
1336 SD_JSON_BUILD_PAIR_CONDITION(!!janswer
,
1337 "answer", SD_JSON_BUILD_VARIANT(janswer
)));
1339 log_debug_errno(r
, "Failed to send monitor event, ignoring: %m");
1349 const union in_addr_union
*destination
,
1351 const union in_addr_union
*source
,
1356 assert(destination
);
1360 /* For mDNS, it is natural that the packet have truncated flag when we have many known answers. */
1361 bool truncated
= DNS_PACKET_TC(p
) && (p
->protocol
!= DNS_PROTOCOL_MDNS
|| !p
->more
);
1363 log_debug("Sending %s%s packet with id %" PRIu16
" on interface %i/%s of size %zu.",
1364 truncated
? "truncated (!) " : "",
1365 DNS_PACKET_QR(p
) ? "response" : "query",
1367 ifindex
, af_to_name(family
),
1370 if (family
== AF_INET
)
1371 return manager_ipv4_send(m
, fd
, ifindex
, &destination
->in
, port
, source
? &source
->in
: NULL
, p
);
1372 if (family
== AF_INET6
)
1373 return manager_ipv6_send(m
, fd
, ifindex
, &destination
->in6
, port
, source
? &source
->in6
: NULL
, p
);
1375 return -EAFNOSUPPORT
;
1378 uint32_t manager_find_mtu(Manager
*m
) {
1382 /* If we don't know on which link a DNS packet would be delivered, let's find the largest MTU that
1383 * works on all interfaces we know of that have an IP address associated */
1385 HASHMAP_FOREACH(l
, m
->links
) {
1386 /* Let's filter out links without IP addresses (e.g. AF_CAN links and suchlike) */
1390 /* Safety check: MTU shorter than what we need for the absolutely shortest DNS request? Then
1391 * let's ignore this link. */
1392 if (l
->mtu
< MIN(UDP4_PACKET_HEADER_SIZE
+ DNS_PACKET_HEADER_SIZE
,
1393 UDP6_PACKET_HEADER_SIZE
+ DNS_PACKET_HEADER_SIZE
))
1396 if (mtu
<= 0 || l
->mtu
< mtu
)
1400 if (mtu
== 0) /* found nothing? then let's assume the typical Ethernet MTU for lack of anything more precise */
1406 int manager_find_ifindex(Manager
*m
, int family
, const union in_addr_union
*in_addr
) {
1411 if (!IN_SET(family
, AF_INET
, AF_INET6
))
1417 a
= manager_find_link_address(m
, family
, in_addr
);
1419 return a
->link
->ifindex
;
1424 void manager_refresh_rrs(Manager
*m
) {
1426 DnssdRegisteredService
*s
;
1430 m
->llmnr_host_ipv4_key
= dns_resource_key_unref(m
->llmnr_host_ipv4_key
);
1431 m
->llmnr_host_ipv6_key
= dns_resource_key_unref(m
->llmnr_host_ipv6_key
);
1432 m
->mdns_host_ipv4_key
= dns_resource_key_unref(m
->mdns_host_ipv4_key
);
1433 m
->mdns_host_ipv6_key
= dns_resource_key_unref(m
->mdns_host_ipv6_key
);
1435 HASHMAP_FOREACH(l
, m
->links
)
1436 link_add_rrs(l
, true);
1438 if (m
->mdns_support
== RESOLVE_SUPPORT_YES
)
1439 HASHMAP_FOREACH(s
, m
->dnssd_registered_services
)
1440 if (dnssd_update_rrs(s
) < 0)
1441 log_warning("Failed to refresh DNS-SD service '%s'", s
->id
);
1443 HASHMAP_FOREACH(l
, m
->links
)
1444 link_add_rrs(l
, false);
1447 static int manager_next_random_name(const char *old
, char **ret_new
) {
1456 if (!ascii_isdigit(p
[-1]))
1462 if (*p
== 0 || safe_atou64(p
, &u
) < 0 || u
<= 0)
1465 /* Add a random number to the old value. This way we can avoid
1466 * that two hosts pick the same hostname, win on IPv4 and lose
1467 * on IPv6 (or vice versa), and pick the same hostname
1468 * replacement hostname, ad infinitum. We still want the
1469 * numbers to go up monotonically, hence we just add a random
1472 random_bytes(&a
, sizeof(a
));
1475 if (asprintf(&n
, "%.*s%" PRIu64
, (int) (p
- old
), old
, u
) < 0)
1483 int manager_next_hostname(Manager
*m
) {
1484 _cleanup_free_
char *h
= NULL
, *k
= NULL
;
1489 r
= manager_next_random_name(m
->llmnr_hostname
, &h
);
1493 r
= dns_name_concat(h
, "local", 0, &k
);
1497 log_info("Hostname conflict, changing published hostname from '%s' to '%s'.", m
->llmnr_hostname
, h
);
1499 free_and_replace(m
->llmnr_hostname
, h
);
1500 free_and_replace(m
->mdns_hostname
, k
);
1502 manager_refresh_rrs(m
);
1503 (void) manager_send_changed(m
, "LLMNRHostname");
1508 LinkAddress
* manager_find_link_address(Manager
*m
, int family
, const union in_addr_union
*in_addr
) {
1513 if (!IN_SET(family
, AF_INET
, AF_INET6
))
1519 HASHMAP_FOREACH(l
, m
->links
) {
1522 a
= link_find_address(l
, family
, in_addr
);
1530 bool manager_packet_from_local_address(Manager
*m
, DnsPacket
*p
) {
1534 /* Let's see if this packet comes from an IP address we have on any local interface */
1536 return !!manager_find_link_address(m
, p
->family
, &p
->sender
);
1539 bool manager_packet_from_our_transaction(Manager
*m
, DnsPacket
*p
) {
1545 /* Let's see if we have a transaction with a query message with the exact same binary contents as the
1546 * one we just got. If so, it's almost definitely a packet loop of some kind. */
1548 t
= hashmap_get(m
->dns_transactions
, UINT_TO_PTR(DNS_PACKET_ID(p
)));
1552 return t
->sent
&& dns_packet_equal(t
->sent
, p
);
1555 DnsScope
* manager_find_scope_from_protocol(Manager
*m
, int ifindex
, DnsProtocol protocol
, int family
) {
1560 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
1565 case DNS_PROTOCOL_LLMNR
:
1566 if (family
== AF_INET
)
1567 return l
->llmnr_ipv4_scope
;
1568 else if (family
== AF_INET6
)
1569 return l
->llmnr_ipv6_scope
;
1573 case DNS_PROTOCOL_MDNS
:
1574 if (family
== AF_INET
)
1575 return l
->mdns_ipv4_scope
;
1576 else if (family
== AF_INET6
)
1577 return l
->mdns_ipv6_scope
;
1588 void manager_verify_all(Manager
*m
) {
1591 LIST_FOREACH(scopes
, s
, m
->dns_scopes
)
1592 dns_zone_verify_all(&s
->zone
);
1595 int manager_is_own_hostname(Manager
*m
, const char *name
) {
1601 if (m
->llmnr_hostname
) {
1602 r
= dns_name_equal(name
, m
->llmnr_hostname
);
1607 if (m
->mdns_hostname
) {
1608 r
= dns_name_equal(name
, m
->mdns_hostname
);
1613 if (m
->full_hostname
)
1614 return dns_name_equal(name
, m
->full_hostname
);
1619 int manager_compile_dns_servers(Manager
*m
, OrderedSet
**dns
) {
1626 r
= ordered_set_ensure_allocated(dns
, &dns_server_hash_ops
);
1630 /* First add the system-wide servers and domains */
1631 LIST_FOREACH(servers
, s
, m
->dns_servers
) {
1632 r
= ordered_set_put(*dns
, s
);
1639 /* Then, add the per-link servers */
1640 HASHMAP_FOREACH(l
, m
->links
)
1641 LIST_FOREACH(servers
, s
, l
->dns_servers
) {
1642 r
= ordered_set_put(*dns
, s
);
1649 /* Third, add the delegate servers and domains */
1651 HASHMAP_FOREACH(d
, m
->delegates
)
1652 LIST_FOREACH(servers
, s
, d
->dns_servers
) {
1653 r
= ordered_set_put(*dns
, s
);
1660 /* If we found nothing, add the fallback servers */
1661 if (ordered_set_isempty(*dns
)) {
1662 LIST_FOREACH(servers
, s
, m
->fallback_dns_servers
) {
1663 r
= ordered_set_put(*dns
, s
);
1674 /* filter_route is a tri-state:
1676 * = 0 or false: return only domains which should be used for searching
1677 * > 0 or true: return only domains which are for routing only
1679 int manager_compile_search_domains(Manager
*m
, OrderedSet
**domains
, int filter_route
) {
1685 r
= ordered_set_ensure_allocated(domains
, &dns_name_hash_ops
);
1689 LIST_FOREACH(domains
, d
, m
->search_domains
) {
1691 if (filter_route
>= 0 &&
1692 d
->route_only
!= !!filter_route
)
1695 r
= ordered_set_put(*domains
, d
->name
);
1702 DnsDelegate
*delegate
;
1703 HASHMAP_FOREACH(delegate
, m
->delegates
)
1704 LIST_FOREACH(domains
, d
, delegate
->search_domains
) {
1706 if (filter_route
>= 0 &&
1707 d
->route_only
!= !!filter_route
)
1710 r
= ordered_set_put(*domains
, d
->name
);
1718 HASHMAP_FOREACH(l
, m
->links
)
1719 LIST_FOREACH(domains
, d
, l
->search_domains
) {
1721 if (filter_route
>= 0 &&
1722 d
->route_only
!= !!filter_route
)
1725 r
= ordered_set_put(*domains
, d
->name
);
1735 DnssecMode
manager_get_dnssec_mode(Manager
*m
) {
1738 if (m
->dnssec_mode
!= _DNSSEC_MODE_INVALID
)
1739 return m
->dnssec_mode
;
1744 bool manager_dnssec_supported(Manager
*m
) {
1750 if (manager_get_dnssec_mode(m
) == DNSSEC_NO
)
1753 server
= manager_get_dns_server(m
);
1754 if (server
&& !dns_server_dnssec_supported(server
))
1757 HASHMAP_FOREACH(l
, m
->links
)
1758 if (!link_dnssec_supported(l
))
1764 DnsOverTlsMode
manager_get_dns_over_tls_mode(Manager
*m
) {
1767 if (m
->dns_over_tls_mode
!= _DNS_OVER_TLS_MODE_INVALID
)
1768 return m
->dns_over_tls_mode
;
1770 return DNS_OVER_TLS_NO
;
1773 void manager_dnssec_verdict(Manager
*m
, DnssecVerdict verdict
, const DnsResourceKey
*key
) {
1775 assert(verdict
>= 0);
1776 assert(verdict
< _DNSSEC_VERDICT_MAX
);
1778 if (DEBUG_LOGGING
) {
1779 char s
[DNS_RESOURCE_KEY_STRING_MAX
];
1781 log_debug("Found verdict for lookup %s: %s",
1782 dns_resource_key_to_string(key
, s
, sizeof s
),
1783 dnssec_verdict_to_string(verdict
));
1786 m
->n_dnssec_verdict
[verdict
]++;
1789 bool manager_routable(Manager
*m
) {
1794 /* Returns true if the host has at least one interface with a routable address (regardless if IPv4 or IPv6) */
1796 HASHMAP_FOREACH(l
, m
->links
)
1797 if (link_relevant(l
, AF_UNSPEC
, false))
1803 void manager_flush_caches(Manager
*m
, int log_level
) {
1806 LIST_FOREACH(scopes
, scope
, m
->dns_scopes
)
1807 dns_cache_flush(&scope
->cache
);
1809 dns_browse_services_purge(m
, AF_UNSPEC
); /* Clear records of DNS service browse subscriber, since caches are flushed */
1810 dns_browse_services_restart(m
);
1812 log_full(log_level
, "Flushed all caches.");
1815 void manager_reset_server_features(Manager
*m
) {
1817 dns_server_reset_features_all(m
->dns_servers
);
1818 dns_server_reset_features_all(m
->fallback_dns_servers
);
1821 HASHMAP_FOREACH(l
, m
->links
)
1822 dns_server_reset_features_all(l
->dns_servers
);
1825 HASHMAP_FOREACH(d
, m
->delegates
)
1826 dns_server_reset_features_all(d
->dns_servers
);
1828 log_info("Resetting learnt feature levels on all servers.");
1831 void manager_cleanup_saved_user(Manager
*m
) {
1832 _cleanup_closedir_
DIR *d
= NULL
;
1836 /* Clean up all saved per-link files in /run/systemd/resolve/netif/ that don't have a matching interface
1837 * anymore. These files are created to persist settings pushed in by the user via the bus, so that resolved can
1838 * be restarted without losing this data. */
1840 d
= opendir("/run/systemd/resolve/netif/");
1842 if (errno
== ENOENT
)
1845 log_warning_errno(errno
, "Failed to open interface directory: %m");
1849 FOREACH_DIRENT_ALL(de
, d
, log_error_errno(errno
, "Failed to read interface directory: %m")) {
1853 if (!IN_SET(de
->d_type
, DT_UNKNOWN
, DT_REG
))
1856 if (dot_or_dot_dot(de
->d_name
))
1859 ifindex
= parse_ifindex(de
->d_name
);
1860 if (ifindex
< 0) /* Probably some temporary file from a previous run. Delete it */
1863 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
1864 if (!l
) /* link vanished */
1867 if (l
->is_managed
) /* now managed by networkd, hence the bus settings are useless */
1873 if (unlinkat(dirfd(d
), de
->d_name
, 0) < 0)
1874 log_warning_errno(errno
, "Failed to remove left-over interface configuration file '%s', ignoring: %m", de
->d_name
);
1878 bool manager_next_dnssd_names(Manager
*m
) {
1879 DnssdRegisteredService
*s
;
1885 HASHMAP_FOREACH(s
, m
->dnssd_registered_services
) {
1886 _cleanup_free_
char * new_name
= NULL
;
1891 r
= manager_next_random_name(s
->name_template
, &new_name
);
1893 log_warning_errno(r
, "Failed to get new name for service '%s': %m", s
->id
);
1897 free_and_replace(s
->name_template
, new_name
);
1899 s
->withdrawn
= false;
1905 manager_refresh_rrs(m
);
1910 bool manager_server_is_stub(Manager
*m
, DnsServer
*s
) {
1911 DnsStubListenerExtra
*l
;
1916 /* Safety check: we generally already skip the main stub when parsing configuration. But let's be
1917 * extra careful, and check here again */
1918 if (s
->family
== AF_INET
&&
1919 s
->address
.in
.s_addr
== htobe32(INADDR_DNS_STUB
) &&
1920 dns_server_port(s
) == 53)
1923 /* Main reason to call this is to check server data against the extra listeners, and filter things
1925 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
)
1926 if (s
->family
== l
->family
&&
1927 in_addr_equal(s
->family
, &s
->address
, &l
->address
) &&
1928 dns_server_port(s
) == dns_stub_listener_extra_port(l
))
1934 int socket_disable_pmtud(int fd
, int af
) {
1939 if (af
== AF_UNSPEC
) {
1940 af
= socket_get_family(fd
);
1948 /* Turn off path MTU discovery, let's rather fragment on the way than to open us up against
1949 * PMTU forgery vulnerabilities.
1951 * There appears to be no documentation about IP_PMTUDISC_OMIT, but it has the effect that
1952 * the "Don't Fragment" bit in the IPv4 header is turned off, thus enforcing fragmentation if
1953 * our datagram size exceeds the MTU of a router in the path, and turning off path MTU
1956 * This helps mitigating the PMTUD vulnerability described here:
1958 * https://blog.apnic.net/2019/07/12/its-time-to-consider-avoiding-ip-fragmentation-in-the-dns/
1960 * Similar logic is in place in most DNS servers.
1962 * There are multiple conflicting goals: we want to allow the largest datagrams possible (for
1963 * efficiency reasons), but not have fragmentation (for security reasons), nor use PMTUD (for
1964 * security reasons, too). Our strategy to deal with this is: use large packets, turn off
1965 * PMTUD, but watch fragmentation taking place, and then size our packets to the max of the
1966 * fragments seen — and if we need larger packets always go to TCP.
1969 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_MTU_DISCOVER
, IP_PMTUDISC_OMIT
);
1977 /* On IPv6 fragmentation only is done by the sender — never by routers on the path. PMTUD is
1978 * mandatory. If we want to turn off PMTUD, the only way is by sending with minimal MTU only,
1979 * so that we apply maximum fragmentation locally already, and thus PMTUD doesn't happen
1980 * because there's nothing that could be fragmented further anymore. */
1982 r
= setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_MTU
, IPV6_MIN_MTU
);
1990 return -EAFNOSUPPORT
;
1994 int dns_manager_dump_statistics_json(Manager
*m
, sd_json_variant
**ret
) {
1995 uint64_t size
= 0, hit
= 0, miss
= 0;
2000 LIST_FOREACH(scopes
, s
, m
->dns_scopes
) {
2001 size
+= dns_cache_size(&s
->cache
);
2002 hit
+= s
->cache
.n_hit
;
2003 miss
+= s
->cache
.n_miss
;
2006 return sd_json_buildo(ret
,
2007 SD_JSON_BUILD_PAIR("transactions", SD_JSON_BUILD_OBJECT(
2008 SD_JSON_BUILD_PAIR_UNSIGNED("currentTransactions", hashmap_size(m
->dns_transactions
)),
2009 SD_JSON_BUILD_PAIR_UNSIGNED("totalTransactions", m
->n_transactions_total
),
2010 SD_JSON_BUILD_PAIR_UNSIGNED("totalTimeouts", m
->n_timeouts_total
),
2011 SD_JSON_BUILD_PAIR_UNSIGNED("totalTimeoutsServedStale", m
->n_timeouts_served_stale_total
),
2012 SD_JSON_BUILD_PAIR_UNSIGNED("totalFailedResponses", m
->n_failure_responses_total
),
2013 SD_JSON_BUILD_PAIR_UNSIGNED("totalFailedResponsesServedStale", m
->n_failure_responses_served_stale_total
)
2015 SD_JSON_BUILD_PAIR("cache", SD_JSON_BUILD_OBJECT(
2016 SD_JSON_BUILD_PAIR_UNSIGNED("size", size
),
2017 SD_JSON_BUILD_PAIR_UNSIGNED("hits", hit
),
2018 SD_JSON_BUILD_PAIR_UNSIGNED("misses", miss
)
2020 SD_JSON_BUILD_PAIR("dnssec", SD_JSON_BUILD_OBJECT(
2021 SD_JSON_BUILD_PAIR_UNSIGNED("secure", m
->n_dnssec_verdict
[DNSSEC_SECURE
]),
2022 SD_JSON_BUILD_PAIR_UNSIGNED("insecure", m
->n_dnssec_verdict
[DNSSEC_INSECURE
]),
2023 SD_JSON_BUILD_PAIR_UNSIGNED("bogus", m
->n_dnssec_verdict
[DNSSEC_BOGUS
]),
2024 SD_JSON_BUILD_PAIR_UNSIGNED("indeterminate", m
->n_dnssec_verdict
[DNSSEC_INDETERMINATE
])
2028 void dns_manager_reset_statistics(Manager
*m
) {
2032 LIST_FOREACH(scopes
, s
, m
->dns_scopes
)
2033 s
->cache
.n_hit
= s
->cache
.n_miss
= 0;
2035 m
->n_transactions_total
= 0;
2036 m
->n_timeouts_total
= 0;
2037 m
->n_timeouts_served_stale_total
= 0;
2038 m
->n_failure_responses_total
= 0;
2039 m
->n_failure_responses_served_stale_total
= 0;
2040 zero(m
->n_dnssec_verdict
);
2043 static int dns_configuration_json_append(
2047 DnsServer
*current_dns_server
,
2048 DnsServer
*dns_servers
,
2049 DnsSearchDomain
*search_domains
,
2050 sd_json_variant
**configuration
) {
2052 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*dns_servers_json
= NULL
,
2053 *search_domains_json
= NULL
,
2054 *current_dns_server_json
= NULL
;
2057 assert(configuration
);
2060 r
= sd_json_variant_new_array(&dns_servers_json
, NULL
, 0);
2065 if (search_domains
) {
2066 r
= sd_json_variant_new_array(&search_domains_json
, NULL
, 0);
2071 if (current_dns_server
) {
2072 r
= dns_server_dump_configuration_to_json(current_dns_server
, ¤t_dns_server_json
);
2077 LIST_FOREACH(servers
, s
, dns_servers
) {
2078 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
2080 assert(dns_servers_json
);
2082 r
= dns_server_dump_configuration_to_json(s
, &v
);
2086 r
= sd_json_variant_append_array(&dns_servers_json
, v
);
2091 LIST_FOREACH(domains
, d
, search_domains
) {
2092 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*v
= NULL
;
2094 assert(search_domains_json
);
2096 r
= dns_search_domain_dump_to_json(d
, &v
);
2100 r
= sd_json_variant_append_array(&search_domains_json
, v
);
2105 return sd_json_variant_append_arraybo(
2107 JSON_BUILD_PAIR_STRING_NON_EMPTY("ifname", ifname
),
2108 SD_JSON_BUILD_PAIR_CONDITION(ifindex
> 0, "ifindex", SD_JSON_BUILD_UNSIGNED(ifindex
)),
2109 SD_JSON_BUILD_PAIR_CONDITION(ifindex
> 0, "defaultRoute", SD_JSON_BUILD_BOOLEAN(default_route
> 0)),
2110 JSON_BUILD_PAIR_VARIANT_NON_NULL("currentServer", current_dns_server_json
),
2111 JSON_BUILD_PAIR_VARIANT_NON_NULL("servers", dns_servers_json
),
2112 JSON_BUILD_PAIR_VARIANT_NON_NULL("searchDomains", search_domains_json
));
2115 int manager_dump_dns_configuration_json(Manager
*m
, sd_json_variant
**ret
) {
2116 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*configuration
= NULL
;
2123 /* Global DNS configuration */
2124 r
= dns_configuration_json_append(
2125 /* ifname = */ NULL
,
2127 /* default_route = */ 0,
2128 manager_get_dns_server(m
),
2135 /* Append configuration for each link */
2136 HASHMAP_FOREACH(l
, m
->links
) {
2137 r
= dns_configuration_json_append(
2140 link_get_default_route(l
),
2141 link_get_dns_server(l
),
2149 return sd_json_buildo(ret
, SD_JSON_BUILD_PAIR_VARIANT("configuration", configuration
));
2152 int manager_send_dns_configuration_changed(Manager
*m
, Link
*l
, bool reset
) {
2153 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*configuration
= NULL
;
2158 if (set_isempty(m
->varlink_dns_configuration_subscription
))
2162 dns_server_reset_accessible_all(m
->dns_servers
);
2165 dns_server_reset_accessible_all(l
->dns_servers
);
2168 r
= manager_dump_dns_configuration_json(m
, &configuration
);
2170 return log_warning_errno(r
, "Failed to dump DNS configuration json: %m");
2172 if (sd_json_variant_equal(configuration
, m
->dns_configuration_json
))
2175 JSON_VARIANT_REPLACE(m
->dns_configuration_json
, TAKE_PTR(configuration
));
2177 r
= varlink_many_notify(m
->varlink_dns_configuration_subscription
, m
->dns_configuration_json
);
2179 return log_warning_errno(r
, "Failed to send DNS configuration event: %m");
2184 int manager_start_dns_configuration_monitor(Manager
*m
) {
2189 assert(!m
->dns_configuration_json
);
2190 assert(!m
->netlink_new_route_slot
);
2191 assert(!m
->netlink_del_route_slot
);
2193 dns_server_reset_accessible_all(m
->dns_servers
);
2195 HASHMAP_FOREACH(l
, m
->links
)
2196 dns_server_reset_accessible_all(l
->dns_servers
);
2198 r
= manager_dump_dns_configuration_json(m
, &m
->dns_configuration_json
);
2202 r
= sd_netlink_add_match(m
->rtnl
, &m
->netlink_new_route_slot
, RTM_NEWROUTE
, manager_process_route
, NULL
, m
, "resolve-NEWROUTE");
2206 r
= sd_netlink_add_match(m
->rtnl
, &m
->netlink_del_route_slot
, RTM_DELROUTE
, manager_process_route
, NULL
, m
, "resolve-DELROUTE");
2213 void manager_stop_dns_configuration_monitor(Manager
*m
) {
2216 m
->dns_configuration_json
= sd_json_variant_unref(m
->dns_configuration_json
);
2217 m
->netlink_new_route_slot
= sd_netlink_slot_unref(m
->netlink_new_route_slot
);
2218 m
->netlink_del_route_slot
= sd_netlink_slot_unref(m
->netlink_del_route_slot
);