1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <netinet/tcp.h>
9 #include "alloc-util.h"
10 #include "dns-domain.h"
12 #include "errno-util.h"
14 #include "hostname-util.h"
16 #include "random-util.h"
17 #include "resolved-dns-answer.h"
18 #include "resolved-dns-delegate.h"
19 #include "resolved-dns-packet.h"
20 #include "resolved-dns-query.h"
21 #include "resolved-dns-question.h"
22 #include "resolved-dns-rr.h"
23 #include "resolved-dns-scope.h"
24 #include "resolved-dns-search-domain.h"
25 #include "resolved-dns-server.h"
26 #include "resolved-dns-synthesize.h"
27 #include "resolved-dns-transaction.h"
28 #include "resolved-dns-zone.h"
29 #include "resolved-dnssd.h"
30 #include "resolved-link.h"
31 #include "resolved-llmnr.h"
32 #include "resolved-manager.h"
33 #include "resolved-mdns.h"
34 #include "resolved-timeouts.h"
36 #include "socket-util.h"
37 #include "string-table.h"
39 #define MULTICAST_RATELIMIT_INTERVAL_USEC (1*USEC_PER_SEC)
40 #define MULTICAST_RATELIMIT_BURST 1000
42 /* After how much time to repeat LLMNR requests, see RFC 4795 Section 7 */
43 #define MULTICAST_RESEND_TIMEOUT_MIN_USEC (100 * USEC_PER_MSEC)
44 #define MULTICAST_RESEND_TIMEOUT_MAX_USEC (1 * USEC_PER_SEC)
49 DnsScopeOrigin origin
,
51 DnsDelegate
*delegate
,
60 assert(origin
< _DNS_SCOPE_ORIGIN_MAX
);
62 assert(!!link
== (origin
== DNS_SCOPE_LINK
));
63 assert(!!delegate
== (origin
== DNS_SCOPE_DELEGATE
));
76 .resend_timeout
= MULTICAST_RESEND_TIMEOUT_MIN_USEC
,
78 /* Enforce ratelimiting for the multicast protocols */
79 .ratelimit
= { MULTICAST_RATELIMIT_INTERVAL_USEC
, MULTICAST_RATELIMIT_BURST
},
82 if (protocol
== DNS_PROTOCOL_DNS
) {
83 /* Copy DNSSEC mode from the link if it is set there,
84 * otherwise take the manager's DNSSEC mode. Note that
85 * we copy this only at scope creation time, and do
86 * not update it from the on, even if the setting
90 s
->dnssec_mode
= link_get_dnssec_mode(link
);
91 s
->dns_over_tls_mode
= link_get_dns_over_tls_mode(link
);
93 s
->dnssec_mode
= manager_get_dnssec_mode(m
);
94 s
->dns_over_tls_mode
= manager_get_dns_over_tls_mode(m
);
98 s
->dnssec_mode
= DNSSEC_NO
;
99 s
->dns_over_tls_mode
= DNS_OVER_TLS_NO
;
102 LIST_PREPEND(scopes
, m
->dns_scopes
, s
);
104 dns_scope_llmnr_membership(s
, true);
105 dns_scope_mdns_membership(s
, true);
107 log_debug("New scope on link %s, protocol %s, family %s, origin %s, delegate %s",
108 link
? link
->ifname
: "*",
109 dns_protocol_to_string(protocol
),
110 family
== AF_UNSPEC
? "*" : af_to_name(family
),
111 dns_scope_origin_to_string(origin
),
112 s
->delegate
? s
->delegate
->id
: "n/a");
118 static void dns_scope_abort_transactions(DnsScope
*s
) {
121 while (s
->transactions
) {
122 DnsTransaction
*t
= s
->transactions
;
124 /* Abort the transaction, but make sure it is not
125 * freed while we still look at it */
128 if (DNS_TRANSACTION_IS_LIVE(t
->state
))
129 dns_transaction_complete(t
, DNS_TRANSACTION_ABORTED
);
132 dns_transaction_free(t
);
136 DnsScope
* dns_scope_free(DnsScope
*s
) {
140 log_debug("Removing scope on link %s, protocol %s, family %s, origin %s, delegate %s",
141 s
->link
? s
->link
->ifname
: "*",
142 dns_protocol_to_string(s
->protocol
),
143 s
->family
== AF_UNSPEC
? "*" : af_to_name(s
->family
),
144 dns_scope_origin_to_string(s
->origin
),
145 s
->delegate
? s
->delegate
->id
: "n/a");
147 dns_scope_llmnr_membership(s
, false);
148 dns_scope_mdns_membership(s
, false);
149 dns_scope_abort_transactions(s
);
151 while (s
->query_candidates
)
152 dns_query_candidate_unref(s
->query_candidates
);
154 hashmap_free(s
->transactions_by_key
);
156 ordered_hashmap_free(s
->conflict_queue
);
157 sd_event_source_disable_unref(s
->conflict_event_source
);
159 sd_event_source_disable_unref(s
->announce_event_source
);
161 sd_event_source_disable_unref(s
->mdns_goodbye_event_source
);
163 dns_cache_flush(&s
->cache
);
164 dns_zone_flush(&s
->zone
);
166 LIST_REMOVE(scopes
, s
->manager
->dns_scopes
, s
);
170 DnsServer
*dns_scope_get_dns_server(DnsScope
*s
) {
173 if (s
->protocol
!= DNS_PROTOCOL_DNS
)
177 assert(!s
->delegate
);
178 return link_get_dns_server(s
->link
);
179 } else if (s
->delegate
)
180 return dns_delegate_get_dns_server(s
->delegate
);
182 return manager_get_dns_server(s
->manager
);
185 unsigned dns_scope_get_n_dns_servers(DnsScope
*s
) {
188 if (s
->protocol
!= DNS_PROTOCOL_DNS
)
192 assert(!s
->delegate
);
193 return s
->link
->n_dns_servers
;
194 } else if (s
->delegate
)
195 return s
->delegate
->n_dns_servers
;
197 return s
->manager
->n_dns_servers
;
200 void dns_scope_next_dns_server(DnsScope
*s
, DnsServer
*if_current
) {
203 if (s
->protocol
!= DNS_PROTOCOL_DNS
)
206 /* Changes to the next DNS server in the list. If 'if_current' is passed will do so only if the
207 * current DNS server still matches it. */
210 link_next_dns_server(s
->link
, if_current
);
211 else if (s
->delegate
)
212 dns_delegate_next_dns_server(s
->delegate
, if_current
);
214 manager_next_dns_server(s
->manager
, if_current
);
217 void dns_scope_packet_received(DnsScope
*s
, usec_t rtt
) {
220 if (rtt
<= s
->max_rtt
)
224 s
->resend_timeout
= MIN(MAX(MULTICAST_RESEND_TIMEOUT_MIN_USEC
, s
->max_rtt
* 2), MULTICAST_RESEND_TIMEOUT_MAX_USEC
);
227 void dns_scope_packet_lost(DnsScope
*s
, usec_t usec
) {
230 if (s
->resend_timeout
<= usec
)
231 s
->resend_timeout
= MIN(s
->resend_timeout
* 2, MULTICAST_RESEND_TIMEOUT_MAX_USEC
);
234 static int dns_scope_emit_one(DnsScope
*s
, int fd
, int family
, DnsPacket
*p
) {
239 assert(p
->protocol
== s
->protocol
);
241 if (family
== AF_UNSPEC
) {
242 if (s
->family
== AF_UNSPEC
)
243 return -EAFNOSUPPORT
;
248 switch (s
->protocol
) {
250 case DNS_PROTOCOL_DNS
: {
251 size_t mtu
, udp_size
, min_mtu
, socket_mtu
= 0;
255 if (DNS_PACKET_QDCOUNT(p
) > 1) /* Classic DNS only allows one question per packet */
258 if (p
->size
> DNS_PACKET_UNICAST_SIZE_MAX
)
261 /* Determine the local most accurate MTU */
265 mtu
= manager_find_mtu(s
->manager
);
267 /* Acquire the socket's PMDU MTU */
268 r
= socket_get_mtu(fd
, family
, &socket_mtu
);
269 if (r
< 0 && !ERRNO_IS_DISCONNECT(r
)) /* Will return ENOTCONN if no information is available yet */
270 return log_debug_errno(r
, "Failed to read socket MTU: %m");
272 /* Determine the appropriate UDP header size */
273 udp_size
= udp_header_size(family
);
274 min_mtu
= udp_size
+ DNS_PACKET_HEADER_SIZE
;
276 log_debug("Emitting UDP, link MTU is %zu, socket MTU is %zu, minimal MTU is %zu",
277 mtu
, socket_mtu
, min_mtu
);
279 /* Clamp by the kernel's idea of the (path) MTU */
280 if (socket_mtu
!= 0 && socket_mtu
< mtu
)
283 /* Put a lower limit, in case all MTU data we acquired was rubbish */
287 /* Now check our packet size against the MTU we determined */
288 if (udp_size
+ p
->size
> mtu
)
289 return -EMSGSIZE
; /* This means: try TCP instead */
291 r
= manager_write(s
->manager
, fd
, p
);
298 case DNS_PROTOCOL_LLMNR
: {
299 union in_addr_union addr
;
303 if (DNS_PACKET_QDCOUNT(p
) > 1)
306 if (!ratelimit_below(&s
->ratelimit
))
309 if (family
== AF_INET
) {
310 addr
.in
= LLMNR_MULTICAST_IPV4_ADDRESS
;
311 fd
= manager_llmnr_ipv4_udp_fd(s
->manager
);
312 } else if (family
== AF_INET6
) {
313 addr
.in6
= LLMNR_MULTICAST_IPV6_ADDRESS
;
314 fd
= manager_llmnr_ipv6_udp_fd(s
->manager
);
316 return -EAFNOSUPPORT
;
321 r
= manager_send(s
->manager
, fd
, s
->link
->ifindex
, family
, &addr
, LLMNR_PORT
, NULL
, p
);
328 case DNS_PROTOCOL_MDNS
: {
329 union in_addr_union addr
;
332 if (!ratelimit_below(&s
->ratelimit
))
335 if (family
== AF_INET
) {
336 if (in4_addr_is_null(&p
->destination
.in
))
337 addr
.in
= MDNS_MULTICAST_IPV4_ADDRESS
;
339 addr
= p
->destination
;
340 fd
= manager_mdns_ipv4_fd(s
->manager
);
341 } else if (family
== AF_INET6
) {
342 if (in6_addr_is_null(&p
->destination
.in6
))
343 addr
.in6
= MDNS_MULTICAST_IPV6_ADDRESS
;
345 addr
= p
->destination
;
346 fd
= manager_mdns_ipv6_fd(s
->manager
);
348 return -EAFNOSUPPORT
;
353 r
= manager_send(s
->manager
, fd
, s
->link
->ifindex
, family
, &addr
, p
->destination_port
?: MDNS_PORT
, NULL
, p
);
361 return -EAFNOSUPPORT
;
367 int dns_scope_emit_udp(DnsScope
*s
, int fd
, int af
, DnsPacket
*p
) {
372 assert(p
->protocol
== s
->protocol
);
373 assert((s
->protocol
== DNS_PROTOCOL_DNS
) == (fd
>= 0));
376 /* If there are multiple linked packets, set the TC bit in all but the last of them */
378 assert(p
->protocol
== DNS_PROTOCOL_MDNS
);
379 dns_packet_set_flags(p
, true, true);
382 r
= dns_scope_emit_one(s
, fd
, af
, p
);
392 static int dns_scope_socket(
396 const union in_addr_union
*address
,
399 union sockaddr_union
*ret_socket_address
) {
401 _cleanup_close_
int fd
= -EBADF
;
402 union sockaddr_union sa
;
409 assert(family
== AF_UNSPEC
);
412 ifindex
= dns_server_ifindex(server
);
414 switch (server
->family
) {
416 sa
= (union sockaddr_union
) {
417 .in
.sin_family
= server
->family
,
418 .in
.sin_port
= htobe16(port
),
419 .in
.sin_addr
= server
->address
.in
,
421 salen
= sizeof(sa
.in
);
424 sa
= (union sockaddr_union
) {
425 .in6
.sin6_family
= server
->family
,
426 .in6
.sin6_port
= htobe16(port
),
427 .in6
.sin6_addr
= server
->address
.in6
,
428 .in6
.sin6_scope_id
= ifindex
,
430 salen
= sizeof(sa
.in6
);
433 return -EAFNOSUPPORT
;
436 assert(family
!= AF_UNSPEC
);
439 ifindex
= dns_scope_ifindex(s
);
443 sa
= (union sockaddr_union
) {
444 .in
.sin_family
= family
,
445 .in
.sin_port
= htobe16(port
),
446 .in
.sin_addr
= address
->in
,
448 salen
= sizeof(sa
.in
);
451 sa
= (union sockaddr_union
) {
452 .in6
.sin6_family
= family
,
453 .in6
.sin6_port
= htobe16(port
),
454 .in6
.sin6_addr
= address
->in6
,
455 .in6
.sin6_scope_id
= ifindex
,
457 salen
= sizeof(sa
.in6
);
460 return -EAFNOSUPPORT
;
464 fd
= socket(sa
.sa
.sa_family
, type
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, 0);
468 if (type
== SOCK_STREAM
) {
469 r
= setsockopt_int(fd
, IPPROTO_TCP
, TCP_NODELAY
, true);
474 bool addr_is_nonlocal
= s
->link
&&
475 !manager_find_link_address(s
->manager
, sa
.sa
.sa_family
, sockaddr_in_addr(&sa
.sa
)) &&
476 in_addr_is_localhost(sa
.sa
.sa_family
, sockaddr_in_addr(&sa
.sa
)) == 0;
478 if (addr_is_nonlocal
&& ifindex
!= 0) {
479 /* As a special exception we don't use UNICAST_IF if we notice that the specified IP address
480 * is on the local host. Otherwise, destination addresses on the local host result in
481 * EHOSTUNREACH, since Linux won't send the packets out of the specified interface, but
482 * delivers them directly to the local socket. */
483 r
= socket_set_unicast_if(fd
, sa
.sa
.sa_family
, ifindex
);
488 if (s
->protocol
== DNS_PROTOCOL_LLMNR
) {
489 /* RFC 4795, section 2.5 requires the TTL to be set to 1 */
490 r
= socket_set_ttl(fd
, sa
.sa
.sa_family
, 1);
495 if (type
== SOCK_DGRAM
) {
496 /* Set IP_RECVERR or IPV6_RECVERR to get ICMP error feedback. See discussion in #10345. */
497 r
= socket_set_recverr(fd
, sa
.sa
.sa_family
, true);
501 r
= socket_set_recvpktinfo(fd
, sa
.sa
.sa_family
, true);
505 /* Turn of path MTU discovery for security reasons */
506 r
= socket_disable_pmtud(fd
, sa
.sa
.sa_family
);
508 log_debug_errno(r
, "Failed to disable UDP PMTUD, ignoring: %m");
510 /* Learn about fragmentation taking place */
511 r
= socket_set_recvfragsize(fd
, sa
.sa
.sa_family
, true);
513 log_debug_errno(r
, "Failed to enable fragment size reception, ignoring: %m");
516 if (ret_socket_address
)
517 *ret_socket_address
= sa
;
521 /* Let's temporarily bind the socket to the specified ifindex. Older kernels only take
522 * the SO_BINDTODEVICE/SO_BINDTOINDEX ifindex into account when making routing decisions
523 * in connect() — and not IP_UNICAST_IF. We don't really want any of the other semantics of
524 * SO_BINDTODEVICE/SO_BINDTOINDEX, hence we immediately unbind the socket after the fact
527 if (addr_is_nonlocal
) {
528 r
= socket_bind_to_ifindex(fd
, ifindex
);
535 r
= connect(fd
, &sa
.sa
, salen
);
536 if (r
< 0 && errno
!= EINPROGRESS
)
540 r
= socket_bind_to_ifindex(fd
, 0);
549 int dns_scope_socket_udp(DnsScope
*s
, DnsServer
*server
) {
550 return dns_scope_socket(s
, SOCK_DGRAM
, AF_UNSPEC
, NULL
, server
, dns_server_port(server
), NULL
);
553 int dns_scope_socket_tcp(DnsScope
*s
, int family
, const union in_addr_union
*address
, DnsServer
*server
, uint16_t port
, union sockaddr_union
*ret_socket_address
) {
554 /* If ret_socket_address is not NULL, the caller is responsible
555 * for calling connect() or sendmsg(). This is required by TCP
556 * Fast Open, to be able to send the initial SYN packet along
557 * with the first data packet. */
558 return dns_scope_socket(s
, SOCK_STREAM
, family
, address
, server
, port
, ret_socket_address
);
561 static DnsScopeMatch
match_link_local_reverse_lookups(const char *domain
) {
564 if (dns_name_endswith(domain
, "254.169.in-addr.arpa") > 0)
565 return DNS_SCOPE_YES_BASE
+ 4; /* 4 labels match */
567 if (dns_name_endswith(domain
, "8.e.f.ip6.arpa") > 0 ||
568 dns_name_endswith(domain
, "9.e.f.ip6.arpa") > 0 ||
569 dns_name_endswith(domain
, "a.e.f.ip6.arpa") > 0 ||
570 dns_name_endswith(domain
, "b.e.f.ip6.arpa") > 0)
571 return DNS_SCOPE_YES_BASE
+ 5; /* 5 labels match */
573 return _DNS_SCOPE_MATCH_INVALID
;
576 static DnsScopeMatch
match_subnet_reverse_lookups(
581 union in_addr_union ia
;
587 /* Checks whether the specified domain is a reverse address domain (i.e. in the .in-addr.arpa or
588 * .ip6.arpa area), and if so, whether the address matches any of the local subnets of the link the
589 * scope is associated with. If so, our scope should consider itself relevant for any lookup in the
590 * domain, since it apparently refers to hosts on this link's subnet.
592 * If 'exclude_own' is true this will return DNS_SCOPE_NO for any IP addresses assigned locally. This
593 * is useful for LLMNR/mDNS as we never want to look up our own hostname on LLMNR/mDNS but always use
594 * the locally synthesized one. */
597 return _DNS_SCOPE_MATCH_INVALID
; /* No link, hence no local addresses to check */
599 r
= dns_name_address(domain
, &f
, &ia
);
601 log_debug_errno(r
, "Failed to determine whether '%s' is an address domain: %m", domain
);
603 return _DNS_SCOPE_MATCH_INVALID
;
605 if (s
->family
!= AF_UNSPEC
&& f
!= s
->family
)
606 return _DNS_SCOPE_MATCH_INVALID
; /* Don't look for IPv4 addresses on LLMNR/mDNS over IPv6 and vice versa */
608 if (in_addr_is_null(f
, &ia
))
611 LIST_FOREACH(addresses
, a
, s
->link
->addresses
) {
616 /* Equals our own address? nah, let's not use this scope. The local synthesizer will pick it up for us. */
618 in_addr_equal(f
, &a
->in_addr
, &ia
) > 0)
621 if (a
->prefixlen
== UCHAR_MAX
) /* don't know subnet mask */
624 /* Don't send mDNS queries for the IPv4 broadcast address */
625 if (f
== AF_INET
&& in_addr_equal(f
, &a
->in_addr_broadcast
, &ia
) > 0)
628 /* Check if the address is in the local subnet */
629 r
= in_addr_prefix_covers(f
, &a
->in_addr
, a
->prefixlen
, &ia
);
631 log_debug_errno(r
, "Failed to determine whether link address covers lookup address '%s': %m", domain
);
633 /* Note that we only claim zero labels match. This is so that this is at the same
634 * priority a DNS scope with "." as routing domain is. */
635 return DNS_SCOPE_YES_BASE
+ 0;
638 return _DNS_SCOPE_MATCH_INVALID
;
641 /* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml */
642 /* https://www.iana.org/assignments/locally-served-dns-zones/locally-served-dns-zones.xhtml */
643 static bool dns_refuse_special_use_domain(const char *domain
, DnsQuestion
*question
) {
644 /* RFC9462 § 6.4: resolvers SHOULD respond to queries of any type other than SVCB for
645 * _dns.resolver.arpa. with NODATA and queries of any type for any domain name under
646 * resolver.arpa with NODATA. */
647 if (dns_name_equal(domain
, "_dns.resolver.arpa") > 0) {
650 /* Only SVCB is permitted to _dns.resolver.arpa */
651 DNS_QUESTION_FOREACH(t
, question
)
652 if (t
->type
== DNS_TYPE_SVCB
)
658 if (dns_name_endswith(domain
, "resolver.arpa") > 0)
664 DnsScopeMatch
dns_scope_good_domain(
667 uint64_t query_flags
) {
669 DnsQuestion
*question
;
674 /* This returns the following return values:
676 * DNS_SCOPE_NO → This scope is not suitable for lookups of this domain, at all
677 * DNS_SCOPE_LAST_RESORT→ This scope is not suitable, unless we have no alternative
678 * DNS_SCOPE_MAYBE → This scope is suitable, but only if nothing else wants it
679 * DNS_SCOPE_YES_BASE+n → This scope is suitable, and 'n' suffix labels match
681 * (The idea is that the caller will only use the scopes with the longest 'n' returned. If no scopes return
682 * DNS_SCOPE_YES_BASE+n, then it should use those which returned DNS_SCOPE_MAYBE. It should never use those
683 * which returned DNS_SCOPE_NO.)
689 question
= dns_query_question_for_protocol(q
, s
->protocol
);
693 domain
= dns_question_first_name(question
);
697 ifindex
= q
->ifindex
;
700 /* Checks if the specified domain is something to look up on this scope. Note that this accepts
701 * non-qualified hostnames, i.e. those without any search path suffixed. */
703 if (ifindex
!= 0 && (!s
->link
|| s
->link
->ifindex
!= ifindex
))
706 if ((SD_RESOLVED_FLAGS_MAKE(s
->protocol
, s
->family
, false, false) & flags
) == 0)
709 /* Never resolve any loopback hostname or IP address via DNS, LLMNR or mDNS. Instead, always rely on
710 * synthesized RRs for these. */
711 if (is_localhost(domain
) ||
712 dns_name_endswith(domain
, "127.in-addr.arpa") > 0 ||
713 dns_name_equal(domain
, "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa") > 0)
716 /* Never respond to some of the domains listed in RFC6303 + RFC6761 */
717 if (dns_name_dont_resolve(domain
))
720 /* Avoid asking invalid questions of some special use domains */
721 if (dns_refuse_special_use_domain(domain
, question
))
724 /* Never go to network for the _gateway, _outbound, _localdnsstub, _localdnsproxy domain — they're something special, synthesized locally. */
725 if (is_gateway_hostname(domain
) ||
726 is_outbound_hostname(domain
) ||
727 is_dns_stub_hostname(domain
) ||
728 is_dns_proxy_stub_hostname(domain
))
731 /* Don't look up the local host name via the network, unless user turned of local synthesis of it */
732 if (manager_is_own_hostname(s
->manager
, domain
) && shall_synthesize_own_hostname_rrs())
735 /* Never send SOA or NS or DNSSEC request to LLMNR, where they make little sense. */
736 r
= dns_question_types_suitable_for_protocol(question
, s
->protocol
);
740 switch (s
->protocol
) {
742 case DNS_PROTOCOL_DNS
: {
743 bool has_search_domains
= false;
747 if (dns_name_is_root(domain
)) {
751 /* Refuse root name if only A and/or AAAA records are requested. */
753 DNS_QUESTION_FOREACH(t
, question
)
754 if (!IN_SET(t
->type
, DNS_TYPE_A
, DNS_TYPE_AAAA
)) {
763 /* Never route things to scopes that lack DNS servers */
764 if (!dns_scope_get_dns_server(s
))
767 /* Route DS requests to the parent */
768 const char *route_domain
= domain
;
769 if (dns_question_contains_key_type(question
, DNS_TYPE_DS
))
770 (void) dns_name_parent(&route_domain
);
772 /* Always honour search domains for routing queries, except if this scope lacks DNS servers. Note that
773 * we return DNS_SCOPE_YES here, rather than just DNS_SCOPE_MAYBE, which means other wildcard scopes
774 * won't be considered anymore. */
775 LIST_FOREACH(domains
, d
, dns_scope_get_search_domains(s
)) {
777 if (!d
->route_only
&& !dns_name_is_root(d
->name
))
778 has_search_domains
= true;
780 if (dns_name_endswith(route_domain
, d
->name
) > 0) {
783 c
= dns_name_count_labels(d
->name
);
792 /* If there's a true search domain defined for this scope, and the query is single-label,
793 * then let's resolve things here, preferably. Note that LLMNR considers itself
794 * authoritative for single-label names too, at the same preference, see below. */
795 if (has_search_domains
&& dns_name_is_single_label(domain
))
796 return DNS_SCOPE_YES_BASE
+ 1;
798 /* If ResolveUnicastSingleLabel=yes and the query is single-label, then bump match result
799 to prevent LLMNR monopoly among candidates. */
800 if ((s
->manager
->resolve_unicast_single_label
|| (query_flags
& SD_RESOLVED_RELAX_SINGLE_LABEL
)) &&
801 dns_name_is_single_label(domain
))
802 return DNS_SCOPE_YES_BASE
+ 1;
804 /* Let's return the number of labels in the best matching result */
806 assert(n_best
<= DNS_SCOPE_YES_END
- DNS_SCOPE_YES_BASE
);
807 return DNS_SCOPE_YES_BASE
+ n_best
;
810 /* Exclude link-local IP ranges */
811 if (match_link_local_reverse_lookups(domain
) >= DNS_SCOPE_YES_BASE
||
812 /* If networks use .local in their private setups, they are supposed to also add .local
813 * to their search domains, which we already checked above. Otherwise, we consider .local
814 * specific to mDNS and won't send such queries ordinary DNS servers. */
815 dns_name_endswith(domain
, "local") > 0)
818 /* If the IP address to look up matches the local subnet, then implicitly synthesizes
819 * DNS_SCOPE_YES_BASE + 0 on this interface, i.e. preferably resolve IP addresses via the DNS
820 * server belonging to this interface. */
821 m
= match_subnet_reverse_lookups(s
, domain
, false);
825 /* If there was no match at all, then see if this scope is suitable as default route. */
826 if (!dns_scope_is_default_route(s
))
829 /* Prefer suitable per-link scopes where possible */
830 if (dns_server_is_fallback(dns_scope_get_dns_server(s
)))
831 return DNS_SCOPE_LAST_RESORT
;
833 return DNS_SCOPE_MAYBE
;
836 case DNS_PROTOCOL_MDNS
: {
839 m
= match_link_local_reverse_lookups(domain
);
843 m
= match_subnet_reverse_lookups(s
, domain
, true);
847 if ((s
->family
== AF_INET
&& dns_name_endswith(domain
, "in-addr.arpa") > 0) ||
848 (s
->family
== AF_INET6
&& dns_name_endswith(domain
, "ip6.arpa") > 0))
849 return DNS_SCOPE_LAST_RESORT
;
851 if ((dns_name_endswith(domain
, "local") > 0 && /* only resolve names ending in .local via mDNS */
852 dns_name_equal(domain
, "local") == 0 && /* but not the single-label "local" name itself */
853 manager_is_own_hostname(s
->manager
, domain
) <= 0)) /* never resolve the local hostname via mDNS */
854 return DNS_SCOPE_YES_BASE
+ 1; /* Return +1, as the top-level .local domain matches, i.e. one label */
859 case DNS_PROTOCOL_LLMNR
: {
862 m
= match_link_local_reverse_lookups(domain
);
866 m
= match_subnet_reverse_lookups(s
, domain
, true);
870 if ((s
->family
== AF_INET
&& dns_name_endswith(domain
, "in-addr.arpa") > 0) ||
871 (s
->family
== AF_INET6
&& dns_name_endswith(domain
, "ip6.arpa") > 0))
872 return DNS_SCOPE_LAST_RESORT
;
874 if ((dns_name_is_single_label(domain
) && /* only resolve single label names via LLMNR */
875 dns_name_equal(domain
, "local") == 0 && /* don't resolve "local" with LLMNR, it's the top-level domain of mDNS after all, see above */
876 manager_is_own_hostname(s
->manager
, domain
) <= 0)) /* never resolve the local hostname via LLMNR */
877 return DNS_SCOPE_YES_BASE
+ 1; /* Return +1, as we consider ourselves authoritative
878 * for single-label names, i.e. one label. This is
879 * particularly relevant as it means a "." route on some
880 * other scope won't pull all traffic away from
881 * us. (If people actually want to pull traffic away
882 * from us they should turn off LLMNR on the
883 * link). Note that unicast DNS scopes with search
884 * domains also consider themselves authoritative for
885 * single-label domains, at the same preference (see
892 assert_not_reached();
896 bool dns_scope_good_key(DnsScope
*s
, const DnsResourceKey
*key
) {
902 /* Check if it makes sense to resolve the specified key on this scope. Note that this call assumes a
903 * fully qualified name, i.e. the search suffixes already appended. */
905 if (!IN_SET(key
->class, DNS_CLASS_IN
, DNS_CLASS_ANY
))
908 if (s
->protocol
== DNS_PROTOCOL_DNS
) {
910 /* On classic DNS, looking up non-address RRs is always fine. (Specifically, we want to
911 * permit looking up DNSKEY and DS records on the root and top-level domains.) */
912 if (!dns_resource_key_is_address(key
))
915 /* Unless explicitly overridden, we refuse to look up A and AAAA RRs on the root and
916 * single-label domains, under the assumption that those should be resolved via LLMNR or
917 * search path only, and should not be leaked onto the internet. */
918 const char* name
= dns_resource_key_name(key
);
920 if (!s
->manager
->resolve_unicast_single_label
&&
921 dns_name_is_single_label(name
))
924 return !dns_name_is_root(name
);
927 /* Never route DNSSEC RR queries to LLMNR/mDNS scopes */
928 if (dns_type_is_dnssec(key
->type
))
931 /* On mDNS and LLMNR, send A and AAAA queries only on the respective scopes */
933 key_family
= dns_type_to_af(key
->type
);
937 return key_family
== s
->family
;
940 static int dns_scope_multicast_membership(DnsScope
*s
, bool b
, struct in_addr in
, struct in6_addr in6
) {
946 if (s
->family
== AF_INET
) {
947 struct ip_mreqn mreqn
= {
949 .imr_ifindex
= s
->link
->ifindex
,
952 if (s
->protocol
== DNS_PROTOCOL_LLMNR
)
953 fd
= manager_llmnr_ipv4_udp_fd(s
->manager
);
955 fd
= manager_mdns_ipv4_fd(s
->manager
);
960 /* Always first try to drop membership before we add
961 * one. This is necessary on some devices, such as
964 (void) setsockopt(fd
, IPPROTO_IP
, IP_DROP_MEMBERSHIP
, &mreqn
, sizeof(mreqn
));
966 if (setsockopt(fd
, IPPROTO_IP
, b
? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP
, &mreqn
, sizeof(mreqn
)) < 0)
969 } else if (s
->family
== AF_INET6
) {
970 struct ipv6_mreq mreq
= {
971 .ipv6mr_multiaddr
= in6
,
972 .ipv6mr_ifindex
= s
->link
->ifindex
,
975 if (s
->protocol
== DNS_PROTOCOL_LLMNR
)
976 fd
= manager_llmnr_ipv6_udp_fd(s
->manager
);
978 fd
= manager_mdns_ipv6_fd(s
->manager
);
984 (void) setsockopt(fd
, IPPROTO_IPV6
, IPV6_DROP_MEMBERSHIP
, &mreq
, sizeof(mreq
));
986 if (setsockopt(fd
, IPPROTO_IPV6
, b
? IPV6_ADD_MEMBERSHIP
: IPV6_DROP_MEMBERSHIP
, &mreq
, sizeof(mreq
)) < 0)
989 return -EAFNOSUPPORT
;
994 int dns_scope_llmnr_membership(DnsScope
*s
, bool b
) {
997 if (s
->protocol
!= DNS_PROTOCOL_LLMNR
)
1000 return dns_scope_multicast_membership(s
, b
, LLMNR_MULTICAST_IPV4_ADDRESS
, LLMNR_MULTICAST_IPV6_ADDRESS
);
1003 int dns_scope_mdns_membership(DnsScope
*s
, bool b
) {
1006 if (s
->protocol
!= DNS_PROTOCOL_MDNS
)
1009 return dns_scope_multicast_membership(s
, b
, MDNS_MULTICAST_IPV4_ADDRESS
, MDNS_MULTICAST_IPV6_ADDRESS
);
1012 int dns_scope_make_reply_packet(
1022 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1023 unsigned n_answer
= 0, n_soa
= 0;
1030 if (dns_question_isempty(q
) &&
1031 dns_answer_isempty(answer
) &&
1032 dns_answer_isempty(soa
))
1035 r
= dns_packet_new(&p
, s
->protocol
, 0, DNS_PACKET_SIZE_MAX
);
1039 /* mDNS answers must have the Authoritative Answer bit set, see RFC 6762, section 18.4. */
1040 c_or_aa
= s
->protocol
== DNS_PROTOCOL_MDNS
;
1042 DNS_PACKET_HEADER(p
)->id
= id
;
1043 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
1054 r
= dns_packet_append_question(p
, q
);
1057 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(dns_question_size(q
));
1059 r
= dns_packet_append_answer(p
, answer
, &n_answer
);
1062 DNS_PACKET_HEADER(p
)->ancount
= htobe16(n_answer
);
1064 r
= dns_packet_append_answer(p
, soa
, &n_soa
);
1067 DNS_PACKET_HEADER(p
)->arcount
= htobe16(n_soa
);
1074 static void dns_scope_verify_conflicts(DnsScope
*s
, DnsPacket
*p
) {
1075 DnsResourceRecord
*rr
;
1076 DnsResourceKey
*key
;
1081 DNS_QUESTION_FOREACH(key
, p
->question
)
1082 dns_zone_verify_conflicts(&s
->zone
, key
);
1084 DNS_ANSWER_FOREACH(rr
, p
->answer
)
1085 dns_zone_verify_conflicts(&s
->zone
, rr
->key
);
1088 void dns_scope_process_query(DnsScope
*s
, DnsStream
*stream
, DnsPacket
*p
) {
1089 _cleanup_(dns_answer_unrefp
) DnsAnswer
*answer
= NULL
, *soa
= NULL
;
1090 _cleanup_(dns_packet_unrefp
) DnsPacket
*reply
= NULL
;
1091 DnsResourceKey
*key
= NULL
;
1092 bool tentative
= false;
1098 if (p
->protocol
!= DNS_PROTOCOL_LLMNR
)
1101 if (p
->ipproto
== IPPROTO_UDP
) {
1102 /* Don't accept UDP queries directed to anything but
1103 * the LLMNR multicast addresses. See RFC 4795,
1106 if (p
->family
== AF_INET
&& !in4_addr_equal(&p
->destination
.in
, &LLMNR_MULTICAST_IPV4_ADDRESS
))
1109 if (p
->family
== AF_INET6
&& !in6_addr_equal(&p
->destination
.in6
, &LLMNR_MULTICAST_IPV6_ADDRESS
))
1113 r
= dns_packet_extract(p
);
1115 log_debug_errno(r
, "Failed to extract resource records from incoming packet: %m");
1119 if (DNS_PACKET_LLMNR_C(p
)) {
1120 /* Somebody notified us about a possible conflict */
1121 dns_scope_verify_conflicts(s
, p
);
1125 if (dns_question_size(p
->question
) != 1)
1126 return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
1128 key
= dns_question_first_key(p
->question
);
1130 r
= dns_zone_lookup(&s
->zone
, key
, 0, &answer
, &soa
, &tentative
);
1132 log_debug_errno(r
, "Failed to look up key: %m");
1139 dns_answer_order_by_scope(answer
, in_addr_is_link_local(p
->family
, &p
->sender
) > 0);
1141 r
= dns_scope_make_reply_packet(s
, DNS_PACKET_ID(p
), DNS_RCODE_SUCCESS
, p
->question
, answer
, soa
, tentative
, &reply
);
1143 log_debug_errno(r
, "Failed to build reply packet: %m");
1148 r
= dns_stream_write_packet(stream
, reply
);
1150 log_debug_errno(r
, "Failed to enqueue reply packet: %m");
1154 /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
1155 * will be dangling until the stream is disconnected, and the default completion handler of the stream
1156 * will then unref the stream and destroy it */
1157 if (DNS_STREAM_QUEUED(stream
))
1158 dns_stream_ref(stream
);
1162 if (!ratelimit_below(&s
->ratelimit
))
1165 if (p
->family
== AF_INET
)
1166 fd
= manager_llmnr_ipv4_udp_fd(s
->manager
);
1167 else if (p
->family
== AF_INET6
)
1168 fd
= manager_llmnr_ipv6_udp_fd(s
->manager
);
1170 log_debug("Unknown protocol");
1174 log_debug_errno(fd
, "Failed to get reply socket: %m");
1178 /* Note that we always immediately reply to all LLMNR
1179 * requests, and do not wait any time, since we
1180 * verified uniqueness for all records. Also see RFC
1181 * 4795, Section 2.7 */
1183 r
= manager_send(s
->manager
, fd
, p
->ifindex
, p
->family
, &p
->sender
, p
->sender_port
, NULL
, reply
);
1185 log_debug_errno(r
, "Failed to send reply packet: %m");
1191 DnsTransaction
*dns_scope_find_transaction(
1193 DnsResourceKey
*key
,
1194 uint64_t query_flags
) {
1196 DnsTransaction
*first
;
1201 /* Iterate through the list of transactions with a matching key */
1202 first
= hashmap_get(scope
->transactions_by_key
, key
);
1203 LIST_FOREACH(transactions_by_key
, t
, first
) {
1205 /* These four flags must match exactly: we cannot use a validated response for a
1206 * non-validating client, and we cannot use a non-validated response for a validating
1207 * client. Similar, if the sources don't match things aren't usable either. */
1208 if (((query_flags
^ t
->query_flags
) &
1209 (SD_RESOLVED_NO_VALIDATE
|
1210 SD_RESOLVED_NO_ZONE
|
1211 SD_RESOLVED_NO_TRUST_ANCHOR
|
1212 SD_RESOLVED_NO_NETWORK
)) != 0)
1215 /* We can reuse a primary query if a regular one is requested, but not vice versa */
1216 if ((query_flags
& SD_RESOLVED_REQUIRE_PRIMARY
) &&
1217 !(t
->query_flags
& SD_RESOLVED_REQUIRE_PRIMARY
))
1220 /* Don't reuse a transaction that allowed caching when we got told not to use it */
1221 if ((query_flags
& SD_RESOLVED_NO_CACHE
) &&
1222 !(t
->query_flags
& SD_RESOLVED_NO_CACHE
))
1225 /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
1227 if ((query_flags
& SD_RESOLVED_CLAMP_TTL
) &&
1228 !(t
->query_flags
& SD_RESOLVED_CLAMP_TTL
))
1237 static int dns_scope_make_conflict_packet(
1239 DnsResourceRecord
*rr
,
1242 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1249 r
= dns_packet_new(&p
, s
->protocol
, 0, DNS_PACKET_SIZE_MAX
);
1253 DNS_PACKET_HEADER(p
)->flags
= htobe16(DNS_PACKET_MAKE_FLAGS(
1264 /* For mDNS, the transaction ID should always be 0 */
1265 if (s
->protocol
!= DNS_PROTOCOL_MDNS
)
1266 random_bytes(&DNS_PACKET_HEADER(p
)->id
, sizeof(uint16_t));
1268 DNS_PACKET_HEADER(p
)->qdcount
= htobe16(1);
1269 DNS_PACKET_HEADER(p
)->arcount
= htobe16(1);
1271 r
= dns_packet_append_key(p
, rr
->key
, 0, NULL
);
1275 r
= dns_packet_append_rr(p
, rr
, 0, NULL
, NULL
);
1284 static int on_conflict_dispatch(sd_event_source
*es
, usec_t usec
, void *userdata
) {
1285 DnsScope
*scope
= ASSERT_PTR(userdata
);
1290 scope
->conflict_event_source
= sd_event_source_disable_unref(scope
->conflict_event_source
);
1293 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
1294 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*rr
= NULL
;
1295 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1297 rr
= ordered_hashmap_steal_first_key_and_value(scope
->conflict_queue
, (void**) &key
);
1301 r
= dns_scope_make_conflict_packet(scope
, rr
, &p
);
1303 log_error_errno(r
, "Failed to make conflict packet: %m");
1307 r
= dns_scope_emit_udp(scope
, -1, AF_UNSPEC
, p
);
1309 log_debug_errno(r
, "Failed to send conflict packet: %m");
1315 int dns_scope_notify_conflict(DnsScope
*scope
, DnsResourceRecord
*rr
) {
1321 /* We don't send these queries immediately. Instead, we queue them, and send them after some jitter
1322 * delay. We only place one RR per key in the conflict messages, not all of them. That should be
1323 * enough to indicate where there might be a conflict */
1324 r
= ordered_hashmap_ensure_put(&scope
->conflict_queue
, &dns_resource_record_hash_ops_by_key
, rr
->key
, rr
);
1325 if (IN_SET(r
, 0, -EEXIST
))
1328 return log_debug_errno(r
, "Failed to queue conflicting RR: %m");
1330 dns_resource_key_ref(rr
->key
);
1331 dns_resource_record_ref(rr
);
1333 if (scope
->conflict_event_source
)
1336 r
= sd_event_add_time_relative(
1337 scope
->manager
->event
,
1338 &scope
->conflict_event_source
,
1340 random_u64_range(LLMNR_JITTER_INTERVAL_USEC
),
1342 on_conflict_dispatch
, scope
);
1344 return log_debug_errno(r
, "Failed to add conflict dispatch event: %m");
1346 (void) sd_event_source_set_description(scope
->conflict_event_source
, "scope-conflict");
1351 void dns_scope_check_conflicts(DnsScope
*scope
, DnsPacket
*p
) {
1352 DnsResourceRecord
*rr
;
1358 if (!IN_SET(p
->protocol
, DNS_PROTOCOL_LLMNR
, DNS_PROTOCOL_MDNS
))
1361 if (DNS_PACKET_RRCOUNT(p
) <= 0)
1364 if (p
->protocol
== DNS_PROTOCOL_LLMNR
) {
1365 if (DNS_PACKET_LLMNR_C(p
) != 0)
1368 if (DNS_PACKET_LLMNR_T(p
) != 0)
1372 if (manager_packet_from_local_address(scope
->manager
, p
))
1375 r
= dns_packet_extract(p
);
1377 log_debug_errno(r
, "Failed to extract packet: %m");
1381 log_debug("Checking for conflicts...");
1383 DNS_ANSWER_FOREACH(rr
, p
->answer
) {
1384 /* No conflict if it is DNS-SD RR used for service enumeration. */
1385 if (dns_resource_key_is_dnssd_ptr(rr
->key
))
1388 /* Check for conflicts against the local zone. If we
1389 * found one, we won't check any further */
1390 r
= dns_zone_check_conflicts(&scope
->zone
, rr
);
1394 /* Check for conflicts against the local cache. If so,
1395 * send out an advisory query, to inform everybody */
1396 r
= dns_cache_check_conflicts(&scope
->cache
, rr
, p
->family
, &p
->sender
);
1400 dns_scope_notify_conflict(scope
, rr
);
1404 void dns_scope_dump(DnsScope
*s
, FILE *f
) {
1410 fputs("[Scope protocol=", f
);
1411 fputs(dns_protocol_to_string(s
->protocol
), f
);
1414 fputs(" interface=", f
);
1415 fputs(s
->link
->ifname
, f
);
1418 if (s
->family
!= AF_UNSPEC
) {
1419 fputs(" family=", f
);
1420 fputs(af_to_name(s
->family
), f
);
1423 fputs(" origin=", f
);
1424 fputs(dns_scope_origin_to_string(s
->origin
), f
);
1428 fputs(s
->delegate
->id
, f
);
1433 if (!dns_zone_is_empty(&s
->zone
)) {
1434 fputs("ZONE:\n", f
);
1435 dns_zone_dump(&s
->zone
, f
);
1438 if (!dns_cache_is_empty(&s
->cache
)) {
1439 fputs("CACHE:\n", f
);
1440 dns_cache_dump(&s
->cache
, f
);
1444 DnsSearchDomain
*dns_scope_get_search_domains(DnsScope
*s
) {
1447 if (s
->protocol
!= DNS_PROTOCOL_DNS
)
1451 return s
->link
->search_domains
;
1453 return s
->delegate
->search_domains
;
1455 return s
->manager
->search_domains
;
1458 bool dns_scope_name_wants_search_domain(DnsScope
*s
, const char *name
) {
1461 if (s
->protocol
!= DNS_PROTOCOL_DNS
)
1464 if (!dns_name_is_single_label(name
))
1467 /* If we allow single-label domain lookups on unicast DNS, and this scope has a search domain that matches
1468 * _exactly_ this name, then do not use search domains. */
1469 if (s
->manager
->resolve_unicast_single_label
)
1470 LIST_FOREACH(domains
, d
, dns_scope_get_search_domains(s
))
1471 if (dns_name_equal(name
, d
->name
) > 0)
1477 bool dns_scope_network_good(DnsScope
*s
) {
1478 /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
1479 * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
1480 * DNS scope we check whether there are any links that are up and have an address.
1482 * Note that Linux routing is complex and even systems that superficially have no IPv4 address might
1483 * be able to route IPv4 (and similar for IPv6), hence let's make a check here independent of address
1489 return manager_routable(s
->manager
);
1492 int dns_scope_ifindex(DnsScope
*s
) {
1496 return s
->link
->ifindex
;
1501 const char* dns_scope_ifname(DnsScope
*s
) {
1505 return s
->link
->ifname
;
1510 static int on_announcement_timeout(sd_event_source
*s
, usec_t usec
, void *userdata
) {
1511 DnsScope
*scope
= userdata
;
1515 scope
->announce_event_source
= sd_event_source_disable_unref(scope
->announce_event_source
);
1517 (void) dns_scope_announce(scope
, false);
1521 int dns_scope_announce(DnsScope
*scope
, bool goodbye
) {
1522 _cleanup_(dns_answer_unrefp
) DnsAnswer
*answer
= NULL
;
1523 _cleanup_(dns_packet_unrefp
) DnsPacket
*p
= NULL
;
1524 _cleanup_set_free_ Set
*types
= NULL
;
1533 if (scope
->protocol
!= DNS_PROTOCOL_MDNS
)
1536 r
= sd_event_get_state(scope
->manager
->event
);
1538 return log_debug_errno(r
, "Failed to get event loop state: %m");
1540 /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
1541 if (r
== SD_EVENT_FINISHED
)
1544 /* Check if we're done with probing. */
1545 LIST_FOREACH(transactions_by_scope
, t
, scope
->transactions
)
1546 if (t
->probing
&& DNS_TRANSACTION_IS_LIVE(t
->state
))
1549 /* Check if there're services pending conflict resolution. */
1550 if (manager_next_dnssd_names(scope
->manager
))
1551 return 0; /* we reach this point only if changing hostname didn't help */
1553 /* Calculate answer's size. */
1554 HASHMAP_FOREACH(z
, scope
->zone
.by_key
) {
1555 if (z
->state
!= DNS_ZONE_ITEM_ESTABLISHED
)
1558 if (z
->rr
->key
->type
== DNS_TYPE_PTR
&&
1559 !dns_zone_contains_name(&scope
->zone
, z
->rr
->ptr
.name
)) {
1560 char key_str
[DNS_RESOURCE_KEY_STRING_MAX
];
1562 log_debug("Skip PTR RR <%s> since its counterparts seem to be withdrawn", dns_resource_key_to_string(z
->rr
->key
, key_str
, sizeof key_str
));
1563 z
->state
= DNS_ZONE_ITEM_WITHDRAWN
;
1567 /* Collect service types for _services._dns-sd._udp.local RRs in a set. Only two-label names
1568 * (not selective names) are considered according to RFC6763 § 9. */
1569 if (!scope
->announced
&&
1570 dns_resource_key_is_dnssd_two_label_ptr(z
->rr
->key
)) {
1571 if (!set_contains(types
, dns_resource_key_name(z
->rr
->key
))) {
1572 r
= set_ensure_put(&types
, &dns_name_hash_ops
, dns_resource_key_name(z
->rr
->key
));
1574 return log_debug_errno(r
, "Failed to add item to set: %m");
1578 LIST_FOREACH(by_key
, i
, z
)
1582 answer
= dns_answer_new(size
+ set_size(types
));
1586 /* Second iteration, actually add RRs to the answer. */
1587 HASHMAP_FOREACH(z
, scope
->zone
.by_key
)
1588 LIST_FOREACH (by_key
, i
, z
) {
1589 DnsAnswerFlags flags
;
1591 if (i
->state
!= DNS_ZONE_ITEM_ESTABLISHED
)
1594 if (dns_resource_key_is_dnssd_ptr(i
->rr
->key
))
1595 flags
= goodbye
? DNS_ANSWER_GOODBYE
: 0;
1597 flags
= goodbye
? (DNS_ANSWER_GOODBYE
|DNS_ANSWER_CACHE_FLUSH
) : DNS_ANSWER_CACHE_FLUSH
;
1599 r
= dns_answer_add(answer
, i
->rr
, 0, flags
, NULL
);
1601 return log_debug_errno(r
, "Failed to add RR to announce: %m");
1604 /* Since all the active services are in the zone make them discoverable now. */
1605 SET_FOREACH(service_type
, types
) {
1606 _cleanup_(dns_resource_record_unrefp
) DnsResourceRecord
*rr
= NULL
;
1608 rr
= dns_resource_record_new_full(DNS_CLASS_IN
, DNS_TYPE_PTR
,
1609 "_services._dns-sd._udp.local");
1613 rr
->ptr
.name
= strdup(service_type
);
1617 rr
->ttl
= MDNS_DEFAULT_TTL
;
1619 r
= dns_zone_put(&scope
->zone
, scope
, rr
, false);
1621 log_warning_errno(r
, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
1623 r
= dns_answer_add(answer
, rr
, 0, 0, NULL
);
1625 return log_debug_errno(r
, "Failed to add RR to announce: %m");
1628 if (dns_answer_isempty(answer
))
1631 r
= dns_scope_make_reply_packet(scope
, 0, DNS_RCODE_SUCCESS
, NULL
, answer
, NULL
, false, &p
);
1633 return log_debug_errno(r
, "Failed to build reply packet: %m");
1635 r
= dns_scope_emit_udp(scope
, -1, AF_UNSPEC
, p
);
1637 return log_debug_errno(r
, "Failed to send reply packet: %m");
1639 /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
1640 * responses, one second apart." */
1641 if (!scope
->announced
) {
1642 scope
->announced
= true;
1644 r
= sd_event_add_time_relative(
1645 scope
->manager
->event
,
1646 &scope
->announce_event_source
,
1648 MDNS_ANNOUNCE_DELAY
,
1650 on_announcement_timeout
, scope
);
1652 return log_debug_errno(r
, "Failed to schedule second announcement: %m");
1654 (void) sd_event_source_set_description(scope
->announce_event_source
, "mdns-announce");
1660 int dns_scope_add_dnssd_services(DnsScope
*scope
) {
1661 DnssdService
*service
;
1666 if (hashmap_isempty(scope
->manager
->dnssd_services
))
1669 scope
->announced
= false;
1671 HASHMAP_FOREACH(service
, scope
->manager
->dnssd_services
) {
1672 service
->withdrawn
= false;
1674 r
= dns_zone_put(&scope
->zone
, scope
, service
->ptr_rr
, false);
1676 log_warning_errno(r
, "Failed to add PTR record to MDNS zone: %m");
1678 if (service
->sub_ptr_rr
) {
1679 r
= dns_zone_put(&scope
->zone
, scope
, service
->sub_ptr_rr
, false);
1681 log_warning_errno(r
, "Failed to add selective PTR record to MDNS zone: %m");
1684 r
= dns_zone_put(&scope
->zone
, scope
, service
->srv_rr
, true);
1686 log_warning_errno(r
, "Failed to add SRV record to MDNS zone: %m");
1688 LIST_FOREACH(items
, txt_data
, service
->txt_data_items
) {
1689 r
= dns_zone_put(&scope
->zone
, scope
, txt_data
->rr
, true);
1691 log_warning_errno(r
, "Failed to add TXT record to MDNS zone: %m");
1698 int dns_scope_remove_dnssd_services(DnsScope
*scope
) {
1699 _cleanup_(dns_resource_key_unrefp
) DnsResourceKey
*key
= NULL
;
1700 DnssdService
*service
;
1705 key
= dns_resource_key_new(DNS_CLASS_IN
, DNS_TYPE_PTR
,
1706 "_services._dns-sd._udp.local");
1710 r
= dns_zone_remove_rrs_by_key(&scope
->zone
, key
);
1714 HASHMAP_FOREACH(service
, scope
->manager
->dnssd_services
) {
1715 dns_zone_remove_rr(&scope
->zone
, service
->ptr_rr
);
1716 dns_zone_remove_rr(&scope
->zone
, service
->sub_ptr_rr
);
1717 dns_zone_remove_rr(&scope
->zone
, service
->srv_rr
);
1718 LIST_FOREACH(items
, txt_data
, service
->txt_data_items
)
1719 dns_zone_remove_rr(&scope
->zone
, txt_data
->rr
);
1725 static bool dns_scope_has_route_only_domains(DnsScope
*scope
) {
1726 DnsSearchDomain
*first
;
1727 bool route_only
= false;
1730 assert(scope
->protocol
== DNS_PROTOCOL_DNS
);
1732 /* Returns 'true' if this scope is suitable for queries to specific domains only. For that we check
1733 * if there are any route-only domains on this interface, as a heuristic to discern VPN-style links
1734 * from non-VPN-style links. Returns 'false' for all other cases, i.e. if the scope is intended to
1735 * take queries to arbitrary domains, i.e. has no routing domains set. */
1738 first
= scope
->link
->search_domains
;
1739 else if (scope
->delegate
)
1740 first
= scope
->delegate
->search_domains
;
1742 first
= scope
->manager
->search_domains
;
1744 LIST_FOREACH(domains
, domain
, first
) {
1745 /* "." means "any domain", thus the interface takes any kind of traffic. Thus, we exit early
1746 * here, as it doesn't really matter whether this link has any route-only domains or not,
1747 * "~." really trumps everything and clearly indicates that this interface shall receive all
1748 * traffic it can get. */
1749 if (dns_name_is_root(DNS_SEARCH_DOMAIN_NAME(domain
)))
1752 if (domain
->route_only
)
1759 bool dns_scope_is_default_route(DnsScope
*scope
) {
1762 /* Only use DNS scopes as default routes */
1763 if (scope
->protocol
!= DNS_PROTOCOL_DNS
)
1768 /* Honour whatever is explicitly configured. This is really the best approach, and trumps any
1769 * automatic logic. */
1770 if (scope
->link
->default_route
>= 0)
1771 return scope
->link
->default_route
;
1773 /* Otherwise check if we have any route-only domains, as a sensible heuristic: if so, let's not
1774 * volunteer as default route. */
1775 return !dns_scope_has_route_only_domains(scope
);
1777 } else if (scope
->delegate
) {
1779 if (scope
->delegate
->default_route
>= 0)
1780 return scope
->delegate
->default_route
;
1782 /* Delegates are by default not used as default route */
1785 /* The global DNS scope is always suitable as default route */
1789 int dns_scope_dump_cache_to_json(DnsScope
*scope
, sd_json_variant
**ret
) {
1790 _cleanup_(sd_json_variant_unrefp
) sd_json_variant
*cache
= NULL
;
1796 r
= dns_cache_dump_to_json(&scope
->cache
, &cache
);
1800 return sd_json_buildo(
1802 SD_JSON_BUILD_PAIR_STRING("protocol", dns_protocol_to_string(scope
->protocol
)),
1803 SD_JSON_BUILD_PAIR_CONDITION(scope
->family
!= AF_UNSPEC
, "family", SD_JSON_BUILD_INTEGER(scope
->family
)),
1804 SD_JSON_BUILD_PAIR_CONDITION(!!scope
->link
, "ifindex", SD_JSON_BUILD_INTEGER(dns_scope_ifindex(scope
))),
1805 SD_JSON_BUILD_PAIR_CONDITION(!!scope
->link
, "ifname", SD_JSON_BUILD_STRING(dns_scope_ifname(scope
))),
1806 SD_JSON_BUILD_PAIR_VARIANT("cache", cache
));
1809 int dns_type_suitable_for_protocol(uint16_t type
, DnsProtocol protocol
) {
1811 /* Tests whether it makes sense to route queries for the specified DNS RR types to the specified
1812 * protocol. For classic DNS pretty much all RR types are suitable, but for LLMNR/mDNS let's
1813 * allowlist only a few that make sense. We use this when routing queries so that we can more quickly
1814 * return errors for queries that will almost certainly fail/time out otherwise. For example, this
1815 * ensures that SOA, NS, or DS/DNSKEY queries are never routed to mDNS/LLMNR where they simply make
1818 if (dns_type_is_obsolete(type
))
1821 if (!dns_type_is_valid_query(type
))
1826 case DNS_PROTOCOL_DNS
:
1829 case DNS_PROTOCOL_LLMNR
:
1838 case DNS_PROTOCOL_MDNS
:
1851 return -EPROTONOSUPPORT
;
1855 int dns_question_types_suitable_for_protocol(DnsQuestion
*q
, DnsProtocol protocol
) {
1856 DnsResourceKey
*key
;
1859 /* Tests whether the types in the specified question make any sense to be routed to the specified
1860 * protocol, i.e. if dns_type_suitable_for_protocol() is true for any of the contained RR types */
1862 DNS_QUESTION_FOREACH(key
, q
) {
1863 r
= dns_type_suitable_for_protocol(key
->type
, protocol
);
1871 static const char* const dns_scope_origin_table
[_DNS_SCOPE_ORIGIN_MAX
] = {
1872 [DNS_SCOPE_GLOBAL
] = "global",
1873 [DNS_SCOPE_LINK
] = "link",
1874 [DNS_SCOPE_DELEGATE
] = "delegate",
1877 DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin
, DnsScopeOrigin
);