1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <netinet/in.h>
12 #include "alloc-util.h"
13 #include "bus-polkit.h"
14 #include "dirent-util.h"
15 #include "dns-domain.h"
16 #include "event-util.h"
19 #include "hostname-util.h"
22 #include "missing_network.h"
23 #include "missing_socket.h"
24 #include "netlink-util.h"
25 #include "ordered-set.h"
26 #include "parse-util.h"
27 #include "random-util.h"
28 #include "resolved-bus.h"
29 #include "resolved-conf.h"
30 #include "resolved-dns-stub.h"
31 #include "resolved-dnssd.h"
32 #include "resolved-etc-hosts.h"
33 #include "resolved-llmnr.h"
34 #include "resolved-manager.h"
35 #include "resolved-mdns.h"
36 #include "resolved-resolv-conf.h"
37 #include "resolved-util.h"
38 #include "resolved-varlink.h"
39 #include "socket-util.h"
40 #include "string-table.h"
41 #include "string-util.h"
44 #define SEND_TIMEOUT_USEC (200 * USEC_PER_MSEC)
46 static int manager_process_link(sd_netlink
*rtnl
, sd_netlink_message
*mm
, void *userdata
) {
47 Manager
*m
= ASSERT_PTR(userdata
);
55 r
= sd_netlink_message_get_type(mm
, &type
);
59 r
= sd_rtnl_message_link_get_ifindex(mm
, &ifindex
);
63 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
71 r
= link_new(m
, &l
, ifindex
);
76 r
= link_process_rtnl(l
, mm
);
85 log_debug("Found new link %i/%s", ifindex
, l
->ifname
);
92 log_debug("Removing link %i/%s", l
->ifindex
, l
->ifname
);
103 log_warning_errno(r
, "Failed to process RTNL link message: %m");
107 static int manager_process_address(sd_netlink
*rtnl
, sd_netlink_message
*mm
, void *userdata
) {
108 Manager
*m
= ASSERT_PTR(userdata
);
109 union in_addr_union address
;
111 int r
, ifindex
, family
;
118 r
= sd_netlink_message_get_type(mm
, &type
);
122 r
= sd_rtnl_message_addr_get_ifindex(mm
, &ifindex
);
126 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
130 r
= sd_rtnl_message_addr_get_family(mm
, &family
);
137 r
= sd_netlink_message_read_in_addr(mm
, IFA_LOCAL
, &address
.in
);
139 r
= sd_netlink_message_read_in_addr(mm
, IFA_ADDRESS
, &address
.in
);
147 r
= sd_netlink_message_read_in6_addr(mm
, IFA_LOCAL
, &address
.in6
);
149 r
= sd_netlink_message_read_in6_addr(mm
, IFA_ADDRESS
, &address
.in6
);
160 a
= link_find_address(l
, family
, &address
);
167 r
= link_address_new(l
, &a
, family
, &address
);
172 r
= link_address_update_rtnl(a
, mm
);
179 link_address_free(a
);
186 log_warning_errno(r
, "Failed to process RTNL address message: %m");
190 static int manager_rtnl_listen(Manager
*m
) {
191 _cleanup_(sd_netlink_message_unrefp
) sd_netlink_message
*req
= NULL
, *reply
= NULL
;
196 /* First, subscribe to interfaces coming and going */
197 r
= sd_netlink_open(&m
->rtnl
);
201 r
= sd_netlink_attach_event(m
->rtnl
, m
->event
, SD_EVENT_PRIORITY_IMPORTANT
);
205 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_NEWLINK
, manager_process_link
, NULL
, m
, "resolve-NEWLINK");
209 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_DELLINK
, manager_process_link
, NULL
, m
, "resolve-DELLINK");
213 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_NEWADDR
, manager_process_address
, NULL
, m
, "resolve-NEWADDR");
217 r
= sd_netlink_add_match(m
->rtnl
, NULL
, RTM_DELADDR
, manager_process_address
, NULL
, m
, "resolve-DELADDR");
221 /* Then, enumerate all links */
222 r
= sd_rtnl_message_new_link(m
->rtnl
, &req
, RTM_GETLINK
, 0);
226 r
= sd_netlink_message_set_request_dump(req
, true);
230 r
= sd_netlink_call(m
->rtnl
, req
, 0, &reply
);
234 for (sd_netlink_message
*i
= reply
; i
; i
= sd_netlink_message_next(i
)) {
235 r
= manager_process_link(m
->rtnl
, i
, m
);
240 req
= sd_netlink_message_unref(req
);
241 reply
= sd_netlink_message_unref(reply
);
243 /* Finally, enumerate all addresses, too */
244 r
= sd_rtnl_message_new_addr(m
->rtnl
, &req
, RTM_GETADDR
, 0, AF_UNSPEC
);
248 r
= sd_netlink_message_set_request_dump(req
, true);
252 r
= sd_netlink_call(m
->rtnl
, req
, 0, &reply
);
256 for (sd_netlink_message
*i
= reply
; i
; i
= sd_netlink_message_next(i
)) {
257 r
= manager_process_address(m
->rtnl
, i
, m
);
265 static int on_network_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
266 Manager
*m
= ASSERT_PTR(userdata
);
270 sd_network_monitor_flush(m
->network_monitor
);
272 HASHMAP_FOREACH(l
, m
->links
) {
275 log_warning_errno(r
, "Failed to update monitor information for %i: %m", l
->ifindex
);
278 (void) manager_write_resolv_conf(m
);
279 (void) manager_send_changed(m
, "DNS");
284 static int manager_network_monitor_listen(Manager
*m
) {
289 r
= sd_network_monitor_new(&m
->network_monitor
, NULL
);
293 fd
= sd_network_monitor_get_fd(m
->network_monitor
);
297 events
= sd_network_monitor_get_events(m
->network_monitor
);
301 r
= sd_event_add_io(m
->event
, &m
->network_event_source
, fd
, events
, &on_network_event
, m
);
305 r
= sd_event_source_set_priority(m
->network_event_source
, SD_EVENT_PRIORITY_IMPORTANT
+5);
309 (void) sd_event_source_set_description(m
->network_event_source
, "network-monitor");
314 static int manager_clock_change_listen(Manager
*m
);
316 static int on_clock_change(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
317 Manager
*m
= ASSERT_PTR(userdata
);
319 /* The clock has changed, let's flush all caches. Why that? That's because DNSSEC validation takes
320 * the system clock into consideration, and if the clock changes the old validations might have been
321 * wrong. Let's redo all validation with the new, correct time.
323 * (Also, this is triggered after system suspend, which is also a good reason to drop caches, since
324 * we might be connected to a different network now without this being visible in a dropped link
327 log_info("Clock change detected. Flushing caches.");
328 manager_flush_caches(m
, LOG_DEBUG
/* downgrade the functions own log message, since we already logged here at LOG_INFO level */);
330 /* The clock change timerfd is unusable after it triggered once, create a new one. */
331 return manager_clock_change_listen(m
);
334 static int manager_clock_change_listen(Manager
*m
) {
339 m
->clock_change_event_source
= sd_event_source_disable_unref(m
->clock_change_event_source
);
341 r
= event_add_time_change(m
->event
, &m
->clock_change_event_source
, on_clock_change
, m
);
343 return log_error_errno(r
, "Failed to create clock change event source: %m");
348 static int determine_hostnames(char **full_hostname
, char **llmnr_hostname
, char **mdns_hostname
) {
349 _cleanup_free_
char *h
= NULL
, *n
= NULL
;
352 assert(full_hostname
);
353 assert(llmnr_hostname
);
354 assert(mdns_hostname
);
356 r
= resolve_system_hostname(&h
, &n
);
360 r
= dns_name_concat(n
, "local", 0, mdns_hostname
);
362 return log_error_errno(r
, "Failed to determine mDNS hostname: %m");
364 *llmnr_hostname
= TAKE_PTR(n
);
365 *full_hostname
= TAKE_PTR(h
);
370 static char* fallback_hostname(void) {
372 /* Determine the fall back hostname. For exposing this system to the outside world, we cannot have it
373 * to be "localhost" even if that's the default hostname. In this case, let's revert to "linux"
376 _cleanup_free_
char *n
= get_default_hostname();
381 return strdup("linux");
386 static int make_fallback_hostnames(char **full_hostname
, char **llmnr_hostname
, char **mdns_hostname
) {
387 _cleanup_free_
char *h
= NULL
, *n
= NULL
, *m
= NULL
;
388 char label
[DNS_LABEL_MAX
];
392 assert(full_hostname
);
393 assert(llmnr_hostname
);
394 assert(mdns_hostname
);
396 p
= h
= fallback_hostname();
400 r
= dns_label_unescape(&p
, label
, sizeof label
, 0);
402 return log_error_errno(r
, "Failed to unescape fallback hostname: %m");
404 assert(r
> 0); /* The fallback hostname must have at least one label */
406 r
= dns_label_escape_new(label
, r
, &n
);
408 return log_error_errno(r
, "Failed to escape fallback hostname: %m");
410 r
= dns_name_concat(n
, "local", 0, &m
);
412 return log_error_errno(r
, "Failed to concatenate mDNS hostname: %m");
414 *llmnr_hostname
= TAKE_PTR(n
);
415 *mdns_hostname
= TAKE_PTR(m
);
416 *full_hostname
= TAKE_PTR(h
);
421 static int on_hostname_change(sd_event_source
*es
, int fd
, uint32_t revents
, void *userdata
) {
422 _cleanup_free_
char *full_hostname
= NULL
, *llmnr_hostname
= NULL
, *mdns_hostname
= NULL
;
423 Manager
*m
= ASSERT_PTR(userdata
);
424 bool llmnr_hostname_changed
;
427 r
= determine_hostnames(&full_hostname
, &llmnr_hostname
, &mdns_hostname
);
429 log_warning_errno(r
, "Failed to determine the local hostname and LLMNR/mDNS names, ignoring: %m");
430 return 0; /* ignore invalid hostnames */
433 llmnr_hostname_changed
= !streq(llmnr_hostname
, m
->llmnr_hostname
);
434 if (streq(full_hostname
, m
->full_hostname
) &&
435 !llmnr_hostname_changed
&&
436 streq(mdns_hostname
, m
->mdns_hostname
))
439 log_info("System hostname changed to '%s'.", full_hostname
);
441 free_and_replace(m
->full_hostname
, full_hostname
);
442 free_and_replace(m
->llmnr_hostname
, llmnr_hostname
);
443 free_and_replace(m
->mdns_hostname
, mdns_hostname
);
445 manager_refresh_rrs(m
);
446 (void) manager_send_changed(m
, "LLMNRHostname");
451 static int manager_watch_hostname(Manager
*m
) {
456 m
->hostname_fd
= open("/proc/sys/kernel/hostname",
457 O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
458 if (m
->hostname_fd
< 0) {
459 log_warning_errno(errno
, "Failed to watch hostname: %m");
463 r
= sd_event_add_io(m
->event
, &m
->hostname_event_source
, m
->hostname_fd
, 0, on_hostname_change
, m
);
466 /* kernels prior to 3.2 don't support polling this file. Ignore the failure. */
467 m
->hostname_fd
= safe_close(m
->hostname_fd
);
469 return log_error_errno(r
, "Failed to add hostname event source: %m");
472 (void) sd_event_source_set_description(m
->hostname_event_source
, "hostname");
474 r
= determine_hostnames(&m
->full_hostname
, &m
->llmnr_hostname
, &m
->mdns_hostname
);
476 _cleanup_free_
char *d
= NULL
;
478 d
= fallback_hostname();
482 log_info("Defaulting to hostname '%s'.", d
);
484 r
= make_fallback_hostnames(&m
->full_hostname
, &m
->llmnr_hostname
, &m
->mdns_hostname
);
488 log_info("Using system hostname '%s'.", m
->full_hostname
);
493 static int manager_sigusr1(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
494 _cleanup_free_
char *buffer
= NULL
;
495 _cleanup_fclose_
FILE *f
= NULL
;
496 Manager
*m
= ASSERT_PTR(userdata
);
503 f
= open_memstream_unlocked(&buffer
, &size
);
507 LIST_FOREACH(scopes
, scope
, m
->dns_scopes
)
508 dns_scope_dump(scope
, f
);
510 LIST_FOREACH(servers
, server
, m
->dns_servers
)
511 dns_server_dump(server
, f
);
512 LIST_FOREACH(servers
, server
, m
->fallback_dns_servers
)
513 dns_server_dump(server
, f
);
514 HASHMAP_FOREACH(l
, m
->links
)
515 LIST_FOREACH(servers
, server
, l
->dns_servers
)
516 dns_server_dump(server
, f
);
518 if (fflush_and_check(f
) < 0)
521 log_dump(LOG_INFO
, buffer
);
525 static int manager_sigusr2(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
526 Manager
*m
= ASSERT_PTR(userdata
);
531 manager_flush_caches(m
, LOG_INFO
);
536 static int manager_sigrtmin1(sd_event_source
*s
, const struct signalfd_siginfo
*si
, void *userdata
) {
537 Manager
*m
= ASSERT_PTR(userdata
);
542 manager_reset_server_features(m
);
546 int manager_new(Manager
**ret
) {
547 _cleanup_(manager_freep
) Manager
*m
= NULL
;
557 .llmnr_ipv4_udp_fd
= -1,
558 .llmnr_ipv6_udp_fd
= -1,
559 .llmnr_ipv4_tcp_fd
= -1,
560 .llmnr_ipv6_tcp_fd
= -1,
565 .llmnr_support
= DEFAULT_LLMNR_MODE
,
566 .mdns_support
= DEFAULT_MDNS_MODE
,
567 .dnssec_mode
= DEFAULT_DNSSEC_MODE
,
568 .dns_over_tls_mode
= DEFAULT_DNS_OVER_TLS_MODE
,
569 .enable_cache
= DNS_CACHE_MODE_YES
,
570 .dns_stub_listener_mode
= DNS_STUB_LISTENER_YES
,
571 .read_resolv_conf
= true,
572 .need_builtin_fallbacks
= true,
573 .etc_hosts_last
= USEC_INFINITY
,
574 .read_etc_hosts
= true,
577 r
= dns_trust_anchor_load(&m
->trust_anchor
);
581 r
= manager_parse_config_file(m
);
583 log_warning_errno(r
, "Failed to parse configuration file: %m");
585 #if ENABLE_DNS_OVER_TLS
586 r
= dnstls_manager_init(m
);
591 r
= sd_event_default(&m
->event
);
595 (void) sd_event_add_signal(m
->event
, NULL
, SIGTERM
, NULL
, NULL
);
596 (void) sd_event_add_signal(m
->event
, NULL
, SIGINT
, NULL
, NULL
);
598 (void) sd_event_set_watchdog(m
->event
, true);
600 r
= manager_watch_hostname(m
);
606 log_warning_errno(r
, "Failed to load DNS-SD configuration files: %m");
608 r
= dns_scope_new(m
, &m
->unicast_scope
, NULL
, DNS_PROTOCOL_DNS
, AF_UNSPEC
);
612 r
= manager_network_monitor_listen(m
);
616 r
= manager_rtnl_listen(m
);
620 r
= manager_clock_change_listen(m
);
624 r
= manager_connect_bus(m
);
628 (void) sd_event_add_signal(m
->event
, &m
->sigusr1_event_source
, SIGUSR1
, manager_sigusr1
, m
);
629 (void) sd_event_add_signal(m
->event
, &m
->sigusr2_event_source
, SIGUSR2
, manager_sigusr2
, m
);
630 (void) sd_event_add_signal(m
->event
, &m
->sigrtmin1_event_source
, SIGRTMIN
+1, manager_sigrtmin1
, m
);
632 manager_cleanup_saved_user(m
);
639 int manager_start(Manager
*m
) {
644 r
= manager_dns_stub_start(m
);
648 r
= manager_varlink_init(m
);
655 Manager
*manager_free(Manager
*m
) {
662 dns_server_unlink_all(m
->dns_servers
);
663 dns_server_unlink_all(m
->fallback_dns_servers
);
664 dns_search_domain_unlink_all(m
->search_domains
);
666 while ((l
= hashmap_first(m
->links
)))
669 while (m
->dns_queries
)
670 dns_query_free(m
->dns_queries
);
672 m
->stub_queries_by_packet
= hashmap_free(m
->stub_queries_by_packet
);
674 dns_scope_free(m
->unicast_scope
);
676 /* At this point only orphaned streams should remain. All others should have been freed already by their
678 while (m
->dns_streams
)
679 dns_stream_unref(m
->dns_streams
);
681 #if ENABLE_DNS_OVER_TLS
682 dnstls_manager_free(m
);
685 hashmap_free(m
->links
);
686 hashmap_free(m
->dns_transactions
);
688 sd_event_source_unref(m
->network_event_source
);
689 sd_network_monitor_unref(m
->network_monitor
);
691 sd_netlink_unref(m
->rtnl
);
692 sd_event_source_unref(m
->rtnl_event_source
);
693 sd_event_source_unref(m
->clock_change_event_source
);
695 manager_llmnr_stop(m
);
696 manager_mdns_stop(m
);
697 manager_dns_stub_stop(m
);
698 manager_varlink_done(m
);
700 manager_socket_graveyard_clear(m
);
702 ordered_set_free(m
->dns_extra_stub_listeners
);
704 bus_verify_polkit_async_registry_free(m
->polkit_registry
);
706 sd_bus_flush_close_unref(m
->bus
);
708 sd_event_source_unref(m
->sigusr1_event_source
);
709 sd_event_source_unref(m
->sigusr2_event_source
);
710 sd_event_source_unref(m
->sigrtmin1_event_source
);
712 dns_resource_key_unref(m
->llmnr_host_ipv4_key
);
713 dns_resource_key_unref(m
->llmnr_host_ipv6_key
);
714 dns_resource_key_unref(m
->mdns_host_ipv4_key
);
715 dns_resource_key_unref(m
->mdns_host_ipv6_key
);
717 sd_event_source_unref(m
->hostname_event_source
);
718 safe_close(m
->hostname_fd
);
720 sd_event_unref(m
->event
);
722 free(m
->full_hostname
);
723 free(m
->llmnr_hostname
);
724 free(m
->mdns_hostname
);
726 while ((s
= hashmap_first(m
->dnssd_services
)))
727 dnssd_service_free(s
);
728 hashmap_free(m
->dnssd_services
);
730 dns_trust_anchor_flush(&m
->trust_anchor
);
731 manager_etc_hosts_flush(m
);
736 int manager_recv(Manager
*m
, int fd
, DnsProtocol protocol
, DnsPacket
**ret
) {
737 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
738 CMSG_BUFFER_TYPE(CMSG_SPACE(MAXSIZE(struct in_pktinfo
, struct in6_pktinfo
))
739 + CMSG_SPACE(int) /* ttl/hoplimit */
740 + EXTRA_CMSG_SPACE
/* kernel appears to require extra buffer space */) control
;
741 union sockaddr_union sa
;
745 .msg_namelen
= sizeof(sa
),
748 .msg_control
= &control
,
749 .msg_controllen
= sizeof(control
),
751 struct cmsghdr
*cmsg
;
759 ms
= next_datagram_size_fd(fd
);
763 r
= dns_packet_new(&p
, protocol
, ms
, DNS_PACKET_SIZE_MAX
);
767 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->allocated
);
769 l
= recvmsg_safe(fd
, &mh
, 0);
771 if (ERRNO_IS_TRANSIENT(l
))
778 assert(!(mh
.msg_flags
& MSG_TRUNC
));
780 p
->size
= (size_t) l
;
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
;
792 return -EAFNOSUPPORT
;
794 p
->timestamp
= now(CLOCK_BOOTTIME
);
796 CMSG_FOREACH(cmsg
, &mh
) {
798 if (cmsg
->cmsg_level
== IPPROTO_IPV6
) {
799 assert(p
->family
== AF_INET6
);
801 switch (cmsg
->cmsg_type
) {
804 struct in6_pktinfo
*i
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
807 p
->ifindex
= i
->ipi6_ifindex
;
809 p
->destination
.in6
= i
->ipi6_addr
;
814 p
->ttl
= *(int *) CMSG_DATA(cmsg
);
817 case IPV6_RECVFRAGSIZE
:
818 p
->fragsize
= *(int *) CMSG_DATA(cmsg
);
821 } else if (cmsg
->cmsg_level
== IPPROTO_IP
) {
822 assert(p
->family
== AF_INET
);
824 switch (cmsg
->cmsg_type
) {
827 struct in_pktinfo
*i
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
830 p
->ifindex
= i
->ipi_ifindex
;
832 p
->destination
.in
= i
->ipi_addr
;
837 p
->ttl
= *(int *) CMSG_DATA(cmsg
);
840 case IP_RECVFRAGSIZE
:
841 p
->fragsize
= *(int *) CMSG_DATA(cmsg
);
847 /* The Linux kernel sets the interface index to the loopback
848 * device if the packet came from the local host since it
849 * avoids the routing table in such a case. Let's unset the
850 * interface index in such a case. */
851 if (p
->ifindex
== LOOPBACK_IFINDEX
)
854 if (protocol
!= DNS_PROTOCOL_DNS
) {
855 /* If we don't know the interface index still, we look for the
856 * first local interface with a matching address. Yuck! */
858 p
->ifindex
= manager_find_ifindex(m
, p
->family
, &p
->destination
);
861 log_debug("Received %s UDP packet of size %zu, ifindex=%i, ttl=%u, fragsize=%zu, sender=%s, destination=%s",
862 dns_protocol_to_string(protocol
), p
->size
, p
->ifindex
, p
->ttl
, p
->fragsize
,
863 IN_ADDR_TO_STRING(p
->family
, &p
->sender
),
864 IN_ADDR_TO_STRING(p
->family
, &p
->destination
));
870 static int sendmsg_loop(int fd
, struct msghdr
*mh
, int flags
) {
877 end
= usec_add(now(CLOCK_MONOTONIC
), SEND_TIMEOUT_USEC
);
880 if (sendmsg(fd
, mh
, flags
) >= 0)
887 r
= fd_wait_for_event(fd
, POLLOUT
, LESS_BY(end
, now(CLOCK_MONOTONIC
)));
889 if (ERRNO_IS_TRANSIENT(r
))
898 static int write_loop(int fd
, void *message
, size_t length
) {
905 end
= usec_add(now(CLOCK_MONOTONIC
), SEND_TIMEOUT_USEC
);
908 if (write(fd
, message
, length
) >= 0)
915 r
= fd_wait_for_event(fd
, POLLOUT
, LESS_BY(end
, now(CLOCK_MONOTONIC
)));
917 if (ERRNO_IS_TRANSIENT(r
))
926 int manager_write(Manager
*m
, int fd
, DnsPacket
*p
) {
929 log_debug("Sending %s%s packet with id %" PRIu16
" of size %zu.",
930 DNS_PACKET_TC(p
) ? "truncated (!) " : "",
931 DNS_PACKET_QR(p
) ? "response" : "query",
935 r
= write_loop(fd
, DNS_PACKET_DATA(p
), p
->size
);
942 static int manager_ipv4_send(
946 const struct in_addr
*destination
,
948 const struct in_addr
*source
,
951 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in_pktinfo
))) control
= {};
952 union sockaddr_union sa
;
958 .msg_namelen
= sizeof(sa
.in
),
967 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->size
);
969 sa
= (union sockaddr_union
) {
970 .in
.sin_family
= AF_INET
,
971 .in
.sin_addr
= *destination
,
972 .in
.sin_port
= htobe16(port
),
976 struct cmsghdr
*cmsg
;
977 struct in_pktinfo
*pi
;
979 mh
.msg_control
= &control
;
980 mh
.msg_controllen
= sizeof(control
);
982 cmsg
= CMSG_FIRSTHDR(&mh
);
983 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in_pktinfo
));
984 cmsg
->cmsg_level
= IPPROTO_IP
;
985 cmsg
->cmsg_type
= IP_PKTINFO
;
987 pi
= (struct in_pktinfo
*) CMSG_DATA(cmsg
);
988 pi
->ipi_ifindex
= ifindex
;
991 pi
->ipi_spec_dst
= *source
;
994 return sendmsg_loop(fd
, &mh
, 0);
997 static int manager_ipv6_send(
1001 const struct in6_addr
*destination
,
1003 const struct in6_addr
*source
,
1006 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct in6_pktinfo
))) control
= {};
1007 union sockaddr_union sa
;
1009 struct msghdr mh
= {
1013 .msg_namelen
= sizeof(sa
.in6
),
1018 assert(destination
);
1022 iov
= IOVEC_MAKE(DNS_PACKET_DATA(p
), p
->size
);
1024 sa
= (union sockaddr_union
) {
1025 .in6
.sin6_family
= AF_INET6
,
1026 .in6
.sin6_addr
= *destination
,
1027 .in6
.sin6_port
= htobe16(port
),
1028 .in6
.sin6_scope_id
= ifindex
,
1032 struct cmsghdr
*cmsg
;
1033 struct in6_pktinfo
*pi
;
1035 mh
.msg_control
= &control
;
1036 mh
.msg_controllen
= sizeof(control
);
1038 cmsg
= CMSG_FIRSTHDR(&mh
);
1039 cmsg
->cmsg_len
= CMSG_LEN(sizeof(struct in6_pktinfo
));
1040 cmsg
->cmsg_level
= IPPROTO_IPV6
;
1041 cmsg
->cmsg_type
= IPV6_PKTINFO
;
1043 pi
= (struct in6_pktinfo
*) CMSG_DATA(cmsg
);
1044 pi
->ipi6_ifindex
= ifindex
;
1047 pi
->ipi6_addr
= *source
;
1050 return sendmsg_loop(fd
, &mh
, 0);
1053 static int dns_question_to_json(DnsQuestion
*q
, JsonVariant
**ret
) {
1054 _cleanup_(json_variant_unrefp
) JsonVariant
*l
= NULL
;
1055 DnsResourceKey
*key
;
1060 DNS_QUESTION_FOREACH(key
, q
) {
1061 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
1063 r
= dns_resource_key_to_json(key
, &v
);
1067 r
= json_variant_append_array(&l
, v
);
1076 int manager_monitor_send(
1081 DnsQuestion
*question_idna
,
1082 DnsQuestion
*question_utf8
,
1083 DnsQuestion
*collected_questions
,
1084 DnsAnswer
*answer
) {
1086 _cleanup_(json_variant_unrefp
) JsonVariant
*jquestion
= NULL
, *jcollected_questions
= NULL
, *janswer
= NULL
;
1087 _cleanup_(dns_question_unrefp
) DnsQuestion
*merged
= NULL
;
1088 Varlink
*connection
;
1094 if (set_isempty(m
->varlink_subscription
))
1097 /* Merge both questions format into one */
1098 r
= dns_question_merge(question_idna
, question_utf8
, &merged
);
1100 return log_error_errno(r
, "Failed to merge UTF8/IDNA questions: %m");
1102 /* Convert the current primary question to JSON */
1103 r
= dns_question_to_json(merged
, &jquestion
);
1105 return log_error_errno(r
, "Failed to convert question to JSON: %m");
1107 /* Generate a JSON array of the questions preceding the current one in the CNAME chain */
1108 r
= dns_question_to_json(collected_questions
, &jcollected_questions
);
1110 return log_error_errno(r
, "Failed to convert question to JSON: %m");
1112 DNS_ANSWER_FOREACH_ITEM(rri
, answer
) {
1113 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
, *w
= NULL
;
1115 r
= dns_resource_record_to_json(rri
->rr
, &v
);
1117 return log_error_errno(r
, "Failed to convert answer resource record to JSON: %m");
1119 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 */
1121 return log_error_errno(r
, "Failed to generate RR wire format: %m");
1123 r
= json_build(&w
, JSON_BUILD_OBJECT(
1124 JSON_BUILD_PAIR_CONDITION(v
, "rr", JSON_BUILD_VARIANT(v
)),
1125 JSON_BUILD_PAIR("raw", JSON_BUILD_BASE64(rri
->rr
->wire_format
, rri
->rr
->wire_format_size
)),
1126 JSON_BUILD_PAIR_CONDITION(rri
->ifindex
> 0, "ifindex", JSON_BUILD_INTEGER(rri
->ifindex
))));
1128 return log_error_errno(r
, "Failed to make answer RR object: %m");
1130 r
= json_variant_append_array(&janswer
, w
);
1132 return log_debug_errno(r
, "Failed to append notification entry to array: %m");
1135 SET_FOREACH(connection
, m
->varlink_subscription
) {
1136 r
= varlink_notifyb(connection
,
1137 JSON_BUILD_OBJECT(JSON_BUILD_PAIR("state", JSON_BUILD_STRING(dns_transaction_state_to_string(state
))),
1138 JSON_BUILD_PAIR_CONDITION(state
== DNS_TRANSACTION_RCODE_FAILURE
, "rcode", JSON_BUILD_INTEGER(rcode
)),
1139 JSON_BUILD_PAIR_CONDITION(state
== DNS_TRANSACTION_ERRNO
, "errno", JSON_BUILD_INTEGER(error
)),
1140 JSON_BUILD_PAIR("question", JSON_BUILD_VARIANT(jquestion
)),
1141 JSON_BUILD_PAIR_CONDITION(jcollected_questions
, "collectedQuestions", JSON_BUILD_VARIANT(jcollected_questions
)),
1142 JSON_BUILD_PAIR_CONDITION(janswer
, "answer", JSON_BUILD_VARIANT(janswer
))));
1144 log_debug_errno(r
, "Failed to send monitor event, ignoring: %m");
1155 const union in_addr_union
*destination
,
1157 const union in_addr_union
*source
,
1162 assert(destination
);
1166 log_debug("Sending %s%s packet with id %" PRIu16
" on interface %i/%s of size %zu.",
1167 DNS_PACKET_TC(p
) ? "truncated (!) " : "",
1168 DNS_PACKET_QR(p
) ? "response" : "query",
1170 ifindex
, af_to_name(family
),
1173 if (family
== AF_INET
)
1174 return manager_ipv4_send(m
, fd
, ifindex
, &destination
->in
, port
, source
? &source
->in
: NULL
, p
);
1175 if (family
== AF_INET6
)
1176 return manager_ipv6_send(m
, fd
, ifindex
, &destination
->in6
, port
, source
? &source
->in6
: NULL
, p
);
1178 return -EAFNOSUPPORT
;
1181 uint32_t manager_find_mtu(Manager
*m
) {
1185 /* If we don't know on which link a DNS packet would be delivered, let's find the largest MTU that
1186 * works on all interfaces we know of that have an IP address associated */
1188 HASHMAP_FOREACH(l
, m
->links
) {
1189 /* Let's filter out links without IP addresses (e.g. AF_CAN links and suchlike) */
1193 /* Safety check: MTU shorter than what we need for the absolutely shortest DNS request? Then
1194 * let's ignore this link. */
1195 if (l
->mtu
< MIN(UDP4_PACKET_HEADER_SIZE
+ DNS_PACKET_HEADER_SIZE
,
1196 UDP6_PACKET_HEADER_SIZE
+ DNS_PACKET_HEADER_SIZE
))
1199 if (mtu
<= 0 || l
->mtu
< mtu
)
1203 if (mtu
== 0) /* found nothing? then let's assume the typical Ethernet MTU for lack of anything more precise */
1209 int manager_find_ifindex(Manager
*m
, int family
, const union in_addr_union
*in_addr
) {
1214 if (!IN_SET(family
, AF_INET
, AF_INET6
))
1220 a
= manager_find_link_address(m
, family
, in_addr
);
1222 return a
->link
->ifindex
;
1227 void manager_refresh_rrs(Manager
*m
) {
1233 m
->llmnr_host_ipv4_key
= dns_resource_key_unref(m
->llmnr_host_ipv4_key
);
1234 m
->llmnr_host_ipv6_key
= dns_resource_key_unref(m
->llmnr_host_ipv6_key
);
1235 m
->mdns_host_ipv4_key
= dns_resource_key_unref(m
->mdns_host_ipv4_key
);
1236 m
->mdns_host_ipv6_key
= dns_resource_key_unref(m
->mdns_host_ipv6_key
);
1238 HASHMAP_FOREACH(l
, m
->links
)
1239 link_add_rrs(l
, true);
1241 if (m
->mdns_support
== RESOLVE_SUPPORT_YES
)
1242 HASHMAP_FOREACH(s
, m
->dnssd_services
)
1243 if (dnssd_update_rrs(s
) < 0)
1244 log_warning("Failed to refresh DNS-SD service '%s'", s
->name
);
1246 HASHMAP_FOREACH(l
, m
->links
)
1247 link_add_rrs(l
, false);
1250 static int manager_next_random_name(const char *old
, char **ret_new
) {
1259 if (!ascii_isdigit(p
[-1]))
1265 if (*p
== 0 || safe_atou64(p
, &u
) < 0 || u
<= 0)
1268 /* Add a random number to the old value. This way we can avoid
1269 * that two hosts pick the same hostname, win on IPv4 and lose
1270 * on IPv6 (or vice versa), and pick the same hostname
1271 * replacement hostname, ad infinitum. We still want the
1272 * numbers to go up monotonically, hence we just add a random
1275 random_bytes(&a
, sizeof(a
));
1278 if (asprintf(&n
, "%.*s%" PRIu64
, (int) (p
- old
), old
, u
) < 0)
1286 int manager_next_hostname(Manager
*m
) {
1287 _cleanup_free_
char *h
= NULL
, *k
= NULL
;
1292 r
= manager_next_random_name(m
->llmnr_hostname
, &h
);
1296 r
= dns_name_concat(h
, "local", 0, &k
);
1300 log_info("Hostname conflict, changing published hostname from '%s' to '%s'.", m
->llmnr_hostname
, h
);
1302 free_and_replace(m
->llmnr_hostname
, h
);
1303 free_and_replace(m
->mdns_hostname
, k
);
1305 manager_refresh_rrs(m
);
1306 (void) manager_send_changed(m
, "LLMNRHostname");
1311 LinkAddress
* manager_find_link_address(Manager
*m
, int family
, const union in_addr_union
*in_addr
) {
1316 if (!IN_SET(family
, AF_INET
, AF_INET6
))
1322 HASHMAP_FOREACH(l
, m
->links
) {
1325 a
= link_find_address(l
, family
, in_addr
);
1333 bool manager_packet_from_local_address(Manager
*m
, DnsPacket
*p
) {
1337 /* Let's see if this packet comes from an IP address we have on any local interface */
1339 return !!manager_find_link_address(m
, p
->family
, &p
->sender
);
1342 bool manager_packet_from_our_transaction(Manager
*m
, DnsPacket
*p
) {
1348 /* Let's see if we have a transaction with a query message with the exact same binary contents as the
1349 * one we just got. If so, it's almost definitely a packet loop of some kind. */
1351 t
= hashmap_get(m
->dns_transactions
, UINT_TO_PTR(DNS_PACKET_ID(p
)));
1355 return t
->sent
&& dns_packet_equal(t
->sent
, p
);
1358 DnsScope
* manager_find_scope(Manager
*m
, DnsPacket
*p
) {
1364 l
= hashmap_get(m
->links
, INT_TO_PTR(p
->ifindex
));
1368 switch (p
->protocol
) {
1369 case DNS_PROTOCOL_LLMNR
:
1370 if (p
->family
== AF_INET
)
1371 return l
->llmnr_ipv4_scope
;
1372 else if (p
->family
== AF_INET6
)
1373 return l
->llmnr_ipv6_scope
;
1377 case DNS_PROTOCOL_MDNS
:
1378 if (p
->family
== AF_INET
)
1379 return l
->mdns_ipv4_scope
;
1380 else if (p
->family
== AF_INET6
)
1381 return l
->mdns_ipv6_scope
;
1392 void manager_verify_all(Manager
*m
) {
1395 LIST_FOREACH(scopes
, s
, m
->dns_scopes
)
1396 dns_zone_verify_all(&s
->zone
);
1399 int manager_is_own_hostname(Manager
*m
, const char *name
) {
1405 if (m
->llmnr_hostname
) {
1406 r
= dns_name_equal(name
, m
->llmnr_hostname
);
1411 if (m
->mdns_hostname
) {
1412 r
= dns_name_equal(name
, m
->mdns_hostname
);
1417 if (m
->full_hostname
)
1418 return dns_name_equal(name
, m
->full_hostname
);
1423 int manager_compile_dns_servers(Manager
*m
, OrderedSet
**dns
) {
1430 r
= ordered_set_ensure_allocated(dns
, &dns_server_hash_ops
);
1434 /* First add the system-wide servers and domains */
1435 LIST_FOREACH(servers
, s
, m
->dns_servers
) {
1436 r
= ordered_set_put(*dns
, s
);
1443 /* Then, add the per-link servers */
1444 HASHMAP_FOREACH(l
, m
->links
) {
1445 LIST_FOREACH(servers
, s
, l
->dns_servers
) {
1446 r
= ordered_set_put(*dns
, s
);
1454 /* If we found nothing, add the fallback servers */
1455 if (ordered_set_isempty(*dns
)) {
1456 LIST_FOREACH(servers
, s
, m
->fallback_dns_servers
) {
1457 r
= ordered_set_put(*dns
, s
);
1468 /* filter_route is a tri-state:
1470 * = 0 or false: return only domains which should be used for searching
1471 * > 0 or true: return only domains which are for routing only
1473 int manager_compile_search_domains(Manager
*m
, OrderedSet
**domains
, int filter_route
) {
1480 r
= ordered_set_ensure_allocated(domains
, &dns_name_hash_ops
);
1484 LIST_FOREACH(domains
, d
, m
->search_domains
) {
1486 if (filter_route
>= 0 &&
1487 d
->route_only
!= !!filter_route
)
1490 r
= ordered_set_put(*domains
, d
->name
);
1497 HASHMAP_FOREACH(l
, m
->links
) {
1499 LIST_FOREACH(domains
, d
, l
->search_domains
) {
1501 if (filter_route
>= 0 &&
1502 d
->route_only
!= !!filter_route
)
1505 r
= ordered_set_put(*domains
, d
->name
);
1516 DnssecMode
manager_get_dnssec_mode(Manager
*m
) {
1519 if (m
->dnssec_mode
!= _DNSSEC_MODE_INVALID
)
1520 return m
->dnssec_mode
;
1525 bool manager_dnssec_supported(Manager
*m
) {
1531 if (manager_get_dnssec_mode(m
) == DNSSEC_NO
)
1534 server
= manager_get_dns_server(m
);
1535 if (server
&& !dns_server_dnssec_supported(server
))
1538 HASHMAP_FOREACH(l
, m
->links
)
1539 if (!link_dnssec_supported(l
))
1545 DnsOverTlsMode
manager_get_dns_over_tls_mode(Manager
*m
) {
1548 if (m
->dns_over_tls_mode
!= _DNS_OVER_TLS_MODE_INVALID
)
1549 return m
->dns_over_tls_mode
;
1551 return DNS_OVER_TLS_NO
;
1554 void manager_dnssec_verdict(Manager
*m
, DnssecVerdict verdict
, const DnsResourceKey
*key
) {
1556 assert(verdict
>= 0);
1557 assert(verdict
< _DNSSEC_VERDICT_MAX
);
1559 if (DEBUG_LOGGING
) {
1560 char s
[DNS_RESOURCE_KEY_STRING_MAX
];
1562 log_debug("Found verdict for lookup %s: %s",
1563 dns_resource_key_to_string(key
, s
, sizeof s
),
1564 dnssec_verdict_to_string(verdict
));
1567 m
->n_dnssec_verdict
[verdict
]++;
1570 bool manager_routable(Manager
*m
) {
1575 /* Returns true if the host has at least one interface with a routable address (regardless if IPv4 or IPv6) */
1577 HASHMAP_FOREACH(l
, m
->links
)
1578 if (link_relevant(l
, AF_UNSPEC
, false))
1584 void manager_flush_caches(Manager
*m
, int log_level
) {
1587 LIST_FOREACH(scopes
, scope
, m
->dns_scopes
)
1588 dns_cache_flush(&scope
->cache
);
1590 log_full(log_level
, "Flushed all caches.");
1593 void manager_reset_server_features(Manager
*m
) {
1596 dns_server_reset_features_all(m
->dns_servers
);
1597 dns_server_reset_features_all(m
->fallback_dns_servers
);
1599 HASHMAP_FOREACH(l
, m
->links
)
1600 dns_server_reset_features_all(l
->dns_servers
);
1602 log_info("Resetting learnt feature levels on all servers.");
1605 void manager_cleanup_saved_user(Manager
*m
) {
1606 _cleanup_closedir_
DIR *d
= NULL
;
1610 /* Clean up all saved per-link files in /run/systemd/resolve/netif/ that don't have a matching interface
1611 * anymore. These files are created to persist settings pushed in by the user via the bus, so that resolved can
1612 * be restarted without losing this data. */
1614 d
= opendir("/run/systemd/resolve/netif/");
1616 if (errno
== ENOENT
)
1619 log_warning_errno(errno
, "Failed to open interface directory: %m");
1623 FOREACH_DIRENT_ALL(de
, d
, log_error_errno(errno
, "Failed to read interface directory: %m")) {
1624 _cleanup_free_
char *p
= NULL
;
1628 if (!IN_SET(de
->d_type
, DT_UNKNOWN
, DT_REG
))
1631 if (dot_or_dot_dot(de
->d_name
))
1634 ifindex
= parse_ifindex(de
->d_name
);
1635 if (ifindex
< 0) /* Probably some temporary file from a previous run. Delete it */
1638 l
= hashmap_get(m
->links
, INT_TO_PTR(ifindex
));
1639 if (!l
) /* link vanished */
1642 if (l
->is_managed
) /* now managed by networkd, hence the bus settings are useless */
1648 p
= path_join("/run/systemd/resolve/netif", de
->d_name
);
1658 bool manager_next_dnssd_names(Manager
*m
) {
1665 HASHMAP_FOREACH(s
, m
->dnssd_services
) {
1666 _cleanup_free_
char * new_name
= NULL
;
1671 r
= manager_next_random_name(s
->name_template
, &new_name
);
1673 log_warning_errno(r
, "Failed to get new name for service '%s': %m", s
->name
);
1677 free_and_replace(s
->name_template
, new_name
);
1679 s
->withdrawn
= false;
1685 manager_refresh_rrs(m
);
1690 bool manager_server_is_stub(Manager
*m
, DnsServer
*s
) {
1691 DnsStubListenerExtra
*l
;
1696 /* Safety check: we generally already skip the main stub when parsing configuration. But let's be
1697 * extra careful, and check here again */
1698 if (s
->family
== AF_INET
&&
1699 s
->address
.in
.s_addr
== htobe32(INADDR_DNS_STUB
) &&
1700 dns_server_port(s
) == 53)
1703 /* Main reason to call this is to check server data against the extra listeners, and filter things
1705 ORDERED_SET_FOREACH(l
, m
->dns_extra_stub_listeners
)
1706 if (s
->family
== l
->family
&&
1707 in_addr_equal(s
->family
, &s
->address
, &l
->address
) &&
1708 dns_server_port(s
) == dns_stub_listener_extra_port(l
))
1714 int socket_disable_pmtud(int fd
, int af
) {
1719 if (af
== AF_UNSPEC
) {
1720 r
= socket_get_family(fd
, &af
);
1728 /* Turn off path MTU discovery, let's rather fragment on the way than to open us up against
1729 * PMTU forgery vulnerabilities.
1731 * There appears to be no documentation about IP_PMTUDISC_OMIT, but it has the effect that
1732 * the "Don't Fragment" bit in the IPv4 header is turned off, thus enforcing fragmentation if
1733 * our datagram size exceeds the MTU of a router in the path, and turning off path MTU
1736 * This helps mitigating the PMTUD vulnerability described here:
1738 * https://blog.apnic.net/2019/07/12/its-time-to-consider-avoiding-ip-fragmentation-in-the-dns/
1740 * Similar logic is in place in most DNS servers.
1742 * There are multiple conflicting goals: we want to allow the largest datagrams possible (for
1743 * efficiency reasons), but not have fragmentation (for security reasons), nor use PMTUD (for
1744 * security reasons, too). Our strategy to deal with this is: use large packets, turn off
1745 * PMTUD, but watch fragmentation taking place, and then size our packets to the max of the
1746 * fragments seen — and if we need larger packets always go to TCP.
1749 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_MTU_DISCOVER
, IP_PMTUDISC_OMIT
);
1757 /* On IPv6 fragmentation only is done by the sender — never by routers on the path. PMTUD is
1758 * mandatory. If we want to turn off PMTUD, the only way is by sending with minimal MTU only,
1759 * so that we apply maximum fragmentation locally already, and thus PMTUD doesn't happen
1760 * because there's nothing that could be fragmented further anymore. */
1762 r
= setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_MTU
, IPV6_MIN_MTU
);
1770 return -EAFNOSUPPORT
;