Debian Codegraph @

src/resolve/resolved-dns-scope.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <netinet/tcp.h>
4
5 #include "sd-event.h"
6 #include "sd-json.h"
7
8 #include "af-list.h"
9 #include "alloc-util.h"
10 #include "dns-answer.h"
11 #include "dns-domain.h"
12 #include "dns-packet.h"
13 #include "dns-question.h"
14 #include "dns-rr.h"
15 #include "dns-type.h"
16 #include "errno-util.h"
17 #include "fd-util.h"
18 #include "hostname-util.h"
19 #include "json-util.h"
20 #include "log.h"
21 #include "random-util.h"
22 #include "resolved-dns-browse-services.h"
23 #include "resolved-dns-delegate.h"
24 #include "resolved-dns-query.h"
25 #include "resolved-dns-scope.h"
26 #include "resolved-dns-search-domain.h"
27 #include "resolved-dns-server.h"
28 #include "resolved-dns-synthesize.h"
29 #include "resolved-dns-transaction.h"
30 #include "resolved-dns-zone.h"
31 #include "resolved-dnssd.h"
32 #include "resolved-link.h"
33 #include "resolved-llmnr.h"
34 #include "resolved-manager.h"
35 #include "resolved-mdns.h"
36 #include "resolved-timeouts.h"
37 #include "set.h"
38 #include "socket-util.h"
39 #include "string-table.h"
40
41 #define MULTICAST_RATELIMIT_INTERVAL_USEC (1*USEC_PER_SEC)
42 #define MULTICAST_RATELIMIT_BURST 1000
43
44 /* After how much time to repeat LLMNR requests, see RFC 4795 Section 7 */
45 #define MULTICAST_RESEND_TIMEOUT_MIN_USEC (100 * USEC_PER_MSEC)
46 #define MULTICAST_RESEND_TIMEOUT_MAX_USEC (1 * USEC_PER_SEC)
47
48 int dns_scope_new(
49 Manager *m,
50 DnsScope **ret,
51 DnsScopeOrigin origin,
52 Link *link,
53 DnsDelegate *delegate,
54 DnsProtocol protocol,
55 int family) {
56
57 DnsScope *s;
58
59 assert(m);
60 assert(ret);
61 assert(origin >= 0);
62 assert(origin < _DNS_SCOPE_ORIGIN_MAX);
63
64 assert(!!link == (origin == DNS_SCOPE_LINK));
65 assert(!!delegate == (origin == DNS_SCOPE_DELEGATE));
66
67 s = new(DnsScope, 1);
68 if (!s)
69 return -ENOMEM;
70
71 *s = (DnsScope) {
72 .manager = m,
73 .link = link,
74 .delegate = delegate,
75 .origin = origin,
76 .protocol = protocol,
77 .family = family,
78 .resend_timeout = MULTICAST_RESEND_TIMEOUT_MIN_USEC,
79 .cache.cache_max = m->cache_max[protocol],
80
81 /* Enforce ratelimiting for the multicast protocols */
82 .ratelimit = { MULTICAST_RATELIMIT_INTERVAL_USEC, MULTICAST_RATELIMIT_BURST },
83 };
84
85 if (protocol == DNS_PROTOCOL_DNS) {
86 /* Copy DNSSEC mode from the link if it is set there,
87 * otherwise take the manager's DNSSEC mode. Note that
88 * we copy this only at scope creation time, and do
89 * not update it from the on, even if the setting
90 * changes. */
91
92 if (link) {
93 s->dnssec_mode = link_get_dnssec_mode(link);
94 s->dns_over_tls_mode = link_get_dns_over_tls_mode(link);
95 } else {
96 s->dnssec_mode = manager_get_dnssec_mode(m);
97 s->dns_over_tls_mode = manager_get_dns_over_tls_mode(m);
98 }
99
100 } else {
101 s->dnssec_mode = DNSSEC_NO;
102 s->dns_over_tls_mode = DNS_OVER_TLS_NO;
103 }
104
105 LIST_PREPEND(scopes, m->dns_scopes, s);
106
107 dns_scope_llmnr_membership(s, true);
108 dns_scope_mdns_membership(s, true);
109
110 log_debug("New scope on link %s, protocol %s, family %s, origin %s, delegate %s",
111 link ? link->ifname : "*",
112 dns_protocol_to_string(protocol),
113 family == AF_UNSPEC ? "*" : af_to_name(family),
114 dns_scope_origin_to_string(origin),
115 s->delegate ? s->delegate->id : "n/a");
116
117 *ret = s;
118 return 0;
119 }
120
121 static void dns_scope_abort_transactions(DnsScope *s) {
122 assert(s);
123
124 while (s->transactions) {
125 DnsTransaction *t = s->transactions;
126
127 /* Abort the transaction, but make sure it is not
128 * freed while we still look at it */
129
130 t->block_gc++;
131 if (DNS_TRANSACTION_IS_LIVE(t->state))
132 dns_transaction_complete(t, DNS_TRANSACTION_ABORTED);
133 t->block_gc--;
134
135 dns_transaction_free(t);
136 }
137 }
138
139 DnsScope* dns_scope_free(DnsScope *s) {
140 if (!s)
141 return NULL;
142
143 log_debug("Removing scope on link %s, protocol %s, family %s, origin %s, delegate %s",
144 s->link ? s->link->ifname : "*",
145 dns_protocol_to_string(s->protocol),
146 s->family == AF_UNSPEC ? "*" : af_to_name(s->family),
147 dns_scope_origin_to_string(s->origin),
148 s->delegate ? s->delegate->id : "n/a");
149
150 dns_scope_llmnr_membership(s, false);
151 dns_scope_mdns_membership(s, false);
152 dns_scope_abort_transactions(s);
153
154 while (s->query_candidates)
155 dns_query_candidate_unref(s->query_candidates);
156
157 hashmap_free(s->transactions_by_key);
158
159 ordered_hashmap_free(s->conflict_queue);
160 sd_event_source_disable_unref(s->conflict_event_source);
161
162 sd_event_source_disable_unref(s->announce_event_source);
163
164 sd_event_source_disable_unref(s->mdns_goodbye_event_source);
165
166 dns_cache_flush(&s->cache);
167 dns_zone_flush(&s->zone);
168
169 /* Clear records of mDNS service browse subscriber, since cache bas been flushed */
170 dns_browse_services_purge(s->manager, s->family);
171
172 LIST_REMOVE(scopes, s->manager->dns_scopes, s);
173 return mfree(s);
174 }
175
176 DnsServer *dns_scope_get_dns_server(DnsScope *s) {
177 assert(s);
178
179 if (s->protocol != DNS_PROTOCOL_DNS)
180 return NULL;
181
182 if (s->link) {
183 assert(!s->delegate);
184 return link_get_dns_server(s->link);
185 } else if (s->delegate)
186 return dns_delegate_get_dns_server(s->delegate);
187 else
188 return manager_get_dns_server(s->manager);
189 }
190
191 unsigned dns_scope_get_n_dns_servers(DnsScope *s) {
192 assert(s);
193
194 if (s->protocol != DNS_PROTOCOL_DNS)
195 return 0;
196
197 if (s->link) {
198 assert(!s->delegate);
199 return s->link->n_dns_servers;
200 } else if (s->delegate)
201 return s->delegate->n_dns_servers;
202 else
203 return s->manager->n_dns_servers;
204 }
205
206 void dns_scope_next_dns_server(DnsScope *s, DnsServer *if_current) {
207 assert(s);
208
209 if (s->protocol != DNS_PROTOCOL_DNS)
210 return;
211
212 /* Changes to the next DNS server in the list. If 'if_current' is passed will do so only if the
213 * current DNS server still matches it. */
214
215 if (s->link)
216 link_next_dns_server(s->link, if_current);
217 else if (s->delegate)
218 dns_delegate_next_dns_server(s->delegate, if_current);
219 else
220 manager_next_dns_server(s->manager, if_current);
221 }
222
223 void dns_scope_packet_received(DnsScope *s, usec_t rtt) {
224 assert(s);
225
226 if (rtt <= s->max_rtt)
227 return;
228
229 s->max_rtt = rtt;
230 s->resend_timeout = MIN(MAX(MULTICAST_RESEND_TIMEOUT_MIN_USEC, s->max_rtt * 2), MULTICAST_RESEND_TIMEOUT_MAX_USEC);
231 }
232
233 void dns_scope_packet_lost(DnsScope *s, usec_t usec) {
234 assert(s);
235
236 if (s->resend_timeout <= usec)
237 s->resend_timeout = MIN(s->resend_timeout * 2, MULTICAST_RESEND_TIMEOUT_MAX_USEC);
238 }
239
240 static int dns_scope_emit_one(DnsScope *s, int fd, int family, DnsPacket *p) {
241 int r;
242
243 assert(s);
244 assert(p);
245 assert(p->protocol == s->protocol);
246
247 if (family == AF_UNSPEC) {
248 if (s->family == AF_UNSPEC)
249 return -EAFNOSUPPORT;
250
251 family = s->family;
252 }
253
254 switch (s->protocol) {
255
256 case DNS_PROTOCOL_DNS: {
257 size_t mtu, udp_size, min_mtu, socket_mtu = 0;
258
259 assert(fd >= 0);
260
261 if (DNS_PACKET_QDCOUNT(p) > 1) /* Classic DNS only allows one question per packet */
262 return -EOPNOTSUPP;
263
264 if (p->size > DNS_PACKET_UNICAST_SIZE_MAX)
265 return -EMSGSIZE;
266
267 /* Determine the local most accurate MTU */
268 if (s->link)
269 mtu = s->link->mtu;
270 else
271 mtu = manager_find_mtu(s->manager);
272
273 /* Acquire the socket's PMDU MTU */
274 r = socket_get_mtu(fd, family, &socket_mtu);
275 if (r < 0 && !ERRNO_IS_DISCONNECT(r)) /* Will return ENOTCONN if no information is available yet */
276 return log_debug_errno(r, "Failed to read socket MTU: %m");
277
278 /* Determine the appropriate UDP header size */
279 udp_size = udp_header_size(family);
280 min_mtu = udp_size + DNS_PACKET_HEADER_SIZE;
281
282 log_debug("Emitting UDP, link MTU is %zu, socket MTU is %zu, minimal MTU is %zu",
283 mtu, socket_mtu, min_mtu);
284
285 /* Clamp by the kernel's idea of the (path) MTU */
286 if (socket_mtu != 0 && socket_mtu < mtu)
287 mtu = socket_mtu;
288
289 /* Put a lower limit, in case all MTU data we acquired was rubbish */
290 if (mtu < min_mtu)
291 mtu = min_mtu;
292
293 /* Now check our packet size against the MTU we determined */
294 if (udp_size + p->size > mtu)
295 return -EMSGSIZE; /* This means: try TCP instead */
296
297 r = manager_write(s->manager, fd, p);
298 if (r < 0)
299 return r;
300
301 break;
302 }
303
304 case DNS_PROTOCOL_LLMNR: {
305 union in_addr_union addr;
306
307 assert(fd < 0);
308
309 if (DNS_PACKET_QDCOUNT(p) > 1)
310 return -EOPNOTSUPP;
311
312 if (!ratelimit_below(&s->ratelimit))
313 return -EBUSY;
314
315 if (family == AF_INET) {
316 addr.in = LLMNR_MULTICAST_IPV4_ADDRESS;
317 fd = manager_llmnr_ipv4_udp_fd(s->manager);
318 } else if (family == AF_INET6) {
319 addr.in6 = LLMNR_MULTICAST_IPV6_ADDRESS;
320 fd = manager_llmnr_ipv6_udp_fd(s->manager);
321 } else
322 return -EAFNOSUPPORT;
323 if (fd < 0)
324 return fd;
325
326 assert(s->link);
327 r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, LLMNR_PORT, NULL, p);
328 if (r < 0)
329 return r;
330
331 break;
332 }
333
334 case DNS_PROTOCOL_MDNS: {
335 union in_addr_union addr;
336 assert(fd < 0);
337
338 if (!ratelimit_below(&s->ratelimit))
339 return -EBUSY;
340
341 if (family == AF_INET) {
342 if (in4_addr_is_null(&p->destination.in))
343 addr.in = MDNS_MULTICAST_IPV4_ADDRESS;
344 else
345 addr = p->destination;
346 fd = manager_mdns_ipv4_fd(s->manager);
347 } else if (family == AF_INET6) {
348 if (in6_addr_is_null(&p->destination.in6))
349 addr.in6 = MDNS_MULTICAST_IPV6_ADDRESS;
350 else
351 addr = p->destination;
352 fd = manager_mdns_ipv6_fd(s->manager);
353 } else
354 return -EAFNOSUPPORT;
355 if (fd < 0)
356 return fd;
357
358 assert(s->link);
359 r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, p->destination_port ?: MDNS_PORT, NULL, p);
360 if (r < 0)
361 return r;
362
363 break;
364 }
365
366 default:
367 return -EAFNOSUPPORT;
368 }
369
370 return 1;
371 }
372
373 int dns_scope_emit_udp(DnsScope *s, int fd, int af, DnsPacket *p) {
374 int r;
375
376 assert(s);
377 assert(p);
378 assert(p->protocol == s->protocol);
379 assert((s->protocol == DNS_PROTOCOL_DNS) == (fd >= 0));
380
381 do {
382 /* If there are multiple linked packets, set the TC bit in all but the last of them */
383 if (p->more) {
384 assert(p->protocol == DNS_PROTOCOL_MDNS);
385 dns_packet_set_flags(p, true, true);
386 }
387
388 r = dns_scope_emit_one(s, fd, af, p);
389 if (r < 0)
390 return r;
391
392 p = p->more;
393 } while (p);
394
395 return 0;
396 }
397
398 static int dns_scope_socket(
399 DnsScope *s,
400 int type,
401 int family,
402 const union in_addr_union *address,
403 DnsServer *server,
404 uint16_t port,
405 union sockaddr_union *ret_socket_address) {
406
407 _cleanup_close_ int fd = -EBADF;
408 union sockaddr_union sa;
409 socklen_t salen;
410 int r, ifindex;
411
412 assert(s);
413
414 if (server) {
415 assert(family == AF_UNSPEC);
416 assert(!address);
417
418 ifindex = dns_server_ifindex(server);
419
420 switch (server->family) {
421 case AF_INET:
422 sa = (union sockaddr_union) {
423 .in.sin_family = server->family,
424 .in.sin_port = htobe16(port),
425 .in.sin_addr = server->address.in,
426 };
427 salen = sizeof(sa.in);
428 break;
429 case AF_INET6:
430 sa = (union sockaddr_union) {
431 .in6.sin6_family = server->family,
432 .in6.sin6_port = htobe16(port),
433 .in6.sin6_addr = server->address.in6,
434 .in6.sin6_scope_id = ifindex,
435 };
436 salen = sizeof(sa.in6);
437 break;
438 default:
439 return -EAFNOSUPPORT;
440 }
441 } else {
442 assert(family != AF_UNSPEC);
443 assert(address);
444
445 ifindex = dns_scope_ifindex(s);
446
447 switch (family) {
448 case AF_INET:
449 sa = (union sockaddr_union) {
450 .in.sin_family = family,
451 .in.sin_port = htobe16(port),
452 .in.sin_addr = address->in,
453 };
454 salen = sizeof(sa.in);
455 break;
456 case AF_INET6:
457 sa = (union sockaddr_union) {
458 .in6.sin6_family = family,
459 .in6.sin6_port = htobe16(port),
460 .in6.sin6_addr = address->in6,
461 .in6.sin6_scope_id = ifindex,
462 };
463 salen = sizeof(sa.in6);
464 break;
465 default:
466 return -EAFNOSUPPORT;
467 }
468 }
469
470 fd = socket(sa.sa.sa_family, type|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
471 if (fd < 0)
472 return -errno;
473
474 if (type == SOCK_STREAM) {
475 r = setsockopt_int(fd, IPPROTO_TCP, TCP_NODELAY, true);
476 if (r < 0)
477 return r;
478 }
479
480 if (s->delegate && s->delegate->fwmark > 0) {
481 r = setsockopt_int(fd, SOL_SOCKET, SO_MARK, s->delegate->fwmark);
482 if (r < 0)
483 return log_debug_errno(r, "Failed to set firewall mark on DNS socket: %m");
484 }
485
486 bool addr_is_nonlocal = s->link &&
487 !manager_find_link_address(s->manager, sa.sa.sa_family, sockaddr_in_addr(&sa.sa)) &&
488 in_addr_is_localhost(sa.sa.sa_family, sockaddr_in_addr(&sa.sa)) == 0;
489
490 if (addr_is_nonlocal && ifindex != 0) {
491 /* As a special exception we don't use UNICAST_IF if we notice that the specified IP address
492 * is on the local host. Otherwise, destination addresses on the local host result in
493 * EHOSTUNREACH, since Linux won't send the packets out of the specified interface, but
494 * delivers them directly to the local socket. */
495 r = socket_set_unicast_if(fd, sa.sa.sa_family, ifindex);
496 if (r < 0)
497 return r;
498 }
499
500 if (s->protocol == DNS_PROTOCOL_LLMNR) {
501 /* RFC 4795, section 2.5 requires the TTL to be set to 1 */
502 r = socket_set_ttl(fd, sa.sa.sa_family, 1);
503 if (r < 0)
504 return r;
505 }
506
507 if (type == SOCK_DGRAM) {
508 /* Set IP_RECVERR or IPV6_RECVERR to get ICMP error feedback. See discussion in #10345. */
509 r = socket_set_recverr(fd, sa.sa.sa_family, true);
510 if (r < 0)
511 return r;
512
513 r = socket_set_recvpktinfo(fd, sa.sa.sa_family, true);
514 if (r < 0)
515 return r;
516
517 /* Turn of path MTU discovery for security reasons */
518 r = socket_disable_pmtud(fd, sa.sa.sa_family);
519 if (r < 0)
520 log_debug_errno(r, "Failed to disable UDP PMTUD, ignoring: %m");
521
522 /* Learn about fragmentation taking place */
523 r = socket_set_recvfragsize(fd, sa.sa.sa_family, true);
524 if (r < 0)
525 log_debug_errno(r, "Failed to enable fragment size reception, ignoring: %m");
526 }
527
528 if (ret_socket_address)
529 *ret_socket_address = sa;
530 else {
531 bool bound = false;
532
533 /* Let's temporarily bind the socket to the specified ifindex. Older kernels only take
534 * the SO_BINDTODEVICE/SO_BINDTOINDEX ifindex into account when making routing decisions
535 * in connect() — and not IP_UNICAST_IF. We don't really want any of the other semantics of
536 * SO_BINDTODEVICE/SO_BINDTOINDEX, hence we immediately unbind the socket after the fact
537 * again.
538 */
539 if (addr_is_nonlocal) {
540 r = socket_bind_to_ifindex(fd, ifindex);
541 if (r < 0)
542 return r;
543
544 bound = true;
545 }
546
547 r = connect(fd, &sa.sa, salen);
548 if (r < 0 && errno != EINPROGRESS)
549 return -errno;
550
551 if (bound) {
552 r = socket_bind_to_ifindex(fd, 0);
553 if (r < 0)
554 return r;
555 }
556 }
557
558 return TAKE_FD(fd);
559 }
560
561 int dns_scope_socket_udp(DnsScope *s, DnsServer *server) {
562 return dns_scope_socket(s, SOCK_DGRAM, AF_UNSPEC, NULL, server, dns_server_port(server), NULL);
563 }
564
565 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) {
566 /* If ret_socket_address is not NULL, the caller is responsible
567 * for calling connect() or sendmsg(). This is required by TCP
568 * Fast Open, to be able to send the initial SYN packet along
569 * with the first data packet. */
570 return dns_scope_socket(s, SOCK_STREAM, family, address, server, port, ret_socket_address);
571 }
572
573 static DnsScopeMatch match_link_local_reverse_lookups(const char *domain) {
574 assert(domain);
575
576 if (dns_name_endswith(domain, "254.169.in-addr.arpa") > 0)
577 return DNS_SCOPE_YES_BASE + 4; /* 4 labels match */
578
579 if (dns_name_endswith(domain, "8.e.f.ip6.arpa") > 0 ||
580 dns_name_endswith(domain, "9.e.f.ip6.arpa") > 0 ||
581 dns_name_endswith(domain, "a.e.f.ip6.arpa") > 0 ||
582 dns_name_endswith(domain, "b.e.f.ip6.arpa") > 0)
583 return DNS_SCOPE_YES_BASE + 5; /* 5 labels match */
584
585 return _DNS_SCOPE_MATCH_INVALID;
586 }
587
588 static DnsScopeMatch match_subnet_reverse_lookups(
589 DnsScope *s,
590 const char *domain,
591 bool exclude_own) {
592
593 union in_addr_union ia;
594 int f, r;
595
596 assert(s);
597 assert(domain);
598
599 /* Checks whether the specified domain is a reverse address domain (i.e. in the .in-addr.arpa or
600 * .ip6.arpa area), and if so, whether the address matches any of the local subnets of the link the
601 * scope is associated with. If so, our scope should consider itself relevant for any lookup in the
602 * domain, since it apparently refers to hosts on this link's subnet.
603 *
604 * If 'exclude_own' is true this will return DNS_SCOPE_NO for any IP addresses assigned locally. This
605 * is useful for LLMNR/mDNS as we never want to look up our own hostname on LLMNR/mDNS but always use
606 * the locally synthesized one. */
607
608 if (!s->link)
609 return _DNS_SCOPE_MATCH_INVALID; /* No link, hence no local addresses to check */
610
611 r = dns_name_address(domain, &f, &ia);
612 if (r < 0)
613 log_debug_errno(r, "Failed to determine whether '%s' is an address domain: %m", domain);
614 if (r <= 0)
615 return _DNS_SCOPE_MATCH_INVALID;
616
617 if (s->family != AF_UNSPEC && f != s->family)
618 return _DNS_SCOPE_MATCH_INVALID; /* Don't look for IPv4 addresses on LLMNR/mDNS over IPv6 and vice versa */
619
620 if (in_addr_is_null(f, &ia))
621 return DNS_SCOPE_NO;
622
623 LIST_FOREACH(addresses, a, s->link->addresses) {
624
625 if (a->family != f)
626 continue;
627
628 /* Equals our own address? nah, let's not use this scope. The local synthesizer will pick it up for us. */
629 if (exclude_own &&
630 in_addr_equal(f, &a->in_addr, &ia) > 0)
631 return DNS_SCOPE_NO;
632
633 if (a->prefixlen == UCHAR_MAX) /* don't know subnet mask */
634 continue;
635
636 /* Don't send mDNS queries for the IPv4 broadcast address */
637 if (f == AF_INET && in_addr_equal(f, &a->in_addr_broadcast, &ia) > 0)
638 return DNS_SCOPE_NO;
639
640 /* Check if the address is in the local subnet */
641 r = in_addr_prefix_covers(f, &a->in_addr, a->prefixlen, &ia);
642 if (r < 0)
643 log_debug_errno(r, "Failed to determine whether link address covers lookup address '%s': %m", domain);
644 if (r > 0)
645 /* Note that we only claim zero labels match. This is so that this is at the same
646 * priority a DNS scope with "." as routing domain is. */
647 return DNS_SCOPE_YES_BASE + 0;
648 }
649
650 return _DNS_SCOPE_MATCH_INVALID;
651 }
652
653 /* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml */
654 /* https://www.iana.org/assignments/locally-served-dns-zones/locally-served-dns-zones.xhtml */
655 static bool dns_refuse_special_use_domain(const char *domain, DnsQuestion *question) {
656 /* RFC9462 § 6.4: resolvers SHOULD respond to queries of any type other than SVCB for
657 * _dns.resolver.arpa. with NODATA and queries of any type for any domain name under
658 * resolver.arpa with NODATA. */
659 if (dns_name_equal(domain, "_dns.resolver.arpa") > 0) {
660 DnsResourceKey *t;
661
662 /* Only SVCB is permitted to _dns.resolver.arpa */
663 DNS_QUESTION_FOREACH(t, question)
664 if (t->type == DNS_TYPE_SVCB)
665 return false;
666
667 return true;
668 }
669
670 if (dns_name_endswith(domain, "resolver.arpa") > 0)
671 return true;
672
673 return false;
674 }
675
676 DnsScopeMatch dns_scope_good_domain(
677 DnsScope *s,
678 DnsQuery *q,
679 uint64_t query_flags) {
680
681 DnsQuestion *question;
682 const char *domain;
683 uint64_t flags;
684 int ifindex, r;
685
686 /* This returns the following return values:
687 *
688 * DNS_SCOPE_NO → This scope is not suitable for lookups of this domain, at all
689 * DNS_SCOPE_LAST_RESORT→ This scope is not suitable, unless we have no alternative
690 * DNS_SCOPE_MAYBE → This scope is suitable, but only if nothing else wants it
691 * DNS_SCOPE_YES_BASE+n → This scope is suitable, and 'n' suffix labels match
692 *
693 * (The idea is that the caller will only use the scopes with the longest 'n' returned. If no scopes return
694 * DNS_SCOPE_YES_BASE+n, then it should use those which returned DNS_SCOPE_MAYBE. It should never use those
695 * which returned DNS_SCOPE_NO.)
696 */
697
698 assert(s);
699 assert(q);
700
701 question = dns_query_question_for_protocol(q, s->protocol);
702 if (!question)
703 return DNS_SCOPE_NO;
704
705 domain = dns_question_first_name(question);
706 if (!domain)
707 return DNS_SCOPE_NO;
708
709 ifindex = q->ifindex;
710 flags = q->flags;
711
712 /* Checks if the specified domain is something to look up on this scope. Note that this accepts
713 * non-qualified hostnames, i.e. those without any search path suffixed. */
714
715 if (ifindex != 0 && (!s->link || s->link->ifindex != ifindex))
716 return DNS_SCOPE_NO;
717
718 if ((SD_RESOLVED_FLAGS_MAKE(s->protocol, s->family, false, false) & flags) == 0)
719 return DNS_SCOPE_NO;
720
721 /* Never resolve any loopback hostname or IP address via DNS, LLMNR or mDNS. Instead, always rely on
722 * synthesized RRs for these. */
723 if (is_localhost(domain) ||
724 dns_name_endswith(domain, "127.in-addr.arpa") > 0 ||
725 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)
726 return DNS_SCOPE_NO;
727
728 /* Never respond to some of the domains listed in RFC6303 + RFC6761 */
729 if (dns_name_dont_resolve(domain))
730 return DNS_SCOPE_NO;
731
732 /* Avoid asking invalid questions of some special use domains */
733 if (dns_refuse_special_use_domain(domain, question))
734 return DNS_SCOPE_NO;
735
736 /* Never go to network for the _gateway, _outbound, _localdnsstub, _localdnsproxy domain — they're something special, synthesized locally. */
737 if (is_gateway_hostname(domain) ||
738 is_outbound_hostname(domain) ||
739 is_dns_stub_hostname(domain) ||
740 is_dns_proxy_stub_hostname(domain))
741 return DNS_SCOPE_NO;
742
743 /* Don't look up the local host name via the network, unless user turned of local synthesis of it */
744 if (manager_is_own_hostname(s->manager, domain) && shall_synthesize_own_hostname_rrs())
745 return DNS_SCOPE_NO;
746
747 /* Never send SOA or NS or DNSSEC request to LLMNR, where they make little sense. */
748 r = dns_question_types_suitable_for_protocol(question, s->protocol);
749 if (r <= 0)
750 return DNS_SCOPE_NO;
751
752 switch (s->protocol) {
753
754 case DNS_PROTOCOL_DNS: {
755 bool has_search_domains = false;
756 DnsScopeMatch m;
757 int n_best = -1;
758
759 if (dns_name_is_root(domain)) {
760 DnsResourceKey *t;
761 bool found = false;
762
763 /* Refuse root name if only A and/or AAAA records are requested. */
764
765 DNS_QUESTION_FOREACH(t, question)
766 if (!IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_AAAA)) {
767 found = true;
768 break;
769 }
770
771 if (!found)
772 return DNS_SCOPE_NO;
773 }
774
775 /* Never route things to scopes that lack DNS servers */
776 if (!dns_scope_get_dns_server(s))
777 return DNS_SCOPE_NO;
778
779 /* Always honour search domains for routing queries, except if this scope lacks DNS servers. Note that
780 * we return DNS_SCOPE_YES here, rather than just DNS_SCOPE_MAYBE, which means other wildcard scopes
781 * won't be considered anymore. */
782 LIST_FOREACH(domains, d, dns_scope_get_search_domains(s)) {
783
784 if (!d->route_only && !dns_name_is_root(d->name))
785 has_search_domains = true;
786
787 if (dns_name_endswith(domain, d->name) > 0) {
788 int c;
789
790 c = dns_name_count_labels(d->name);
791 if (c < 0)
792 continue;
793
794 if (c > n_best)
795 n_best = c;
796 }
797 }
798
799 /* If there's a true search domain defined for this scope, and the query is single-label,
800 * then let's resolve things here, preferably. Note that LLMNR considers itself
801 * authoritative for single-label names too, at the same preference, see below. */
802 if (has_search_domains && dns_name_is_single_label(domain))
803 return DNS_SCOPE_YES_BASE + 1;
804
805 /* If ResolveUnicastSingleLabel=yes and the query is single-label, then bump match result
806 to prevent LLMNR monopoly among candidates. */
807 if ((s->manager->resolve_unicast_single_label || (query_flags & SD_RESOLVED_RELAX_SINGLE_LABEL)) &&
808 dns_name_is_single_label(domain))
809 return DNS_SCOPE_YES_BASE + 1;
810
811 /* Let's return the number of labels in the best matching result */
812 if (n_best >= 0) {
813 assert(n_best <= DNS_SCOPE_YES_END - DNS_SCOPE_YES_BASE);
814 return DNS_SCOPE_YES_BASE + n_best;
815 }
816
817 /* Exclude link-local IP ranges */
818 if (match_link_local_reverse_lookups(domain) >= DNS_SCOPE_YES_BASE ||
819 /* If networks use .local in their private setups, they are supposed to also add .local
820 * to their search domains, which we already checked above. Otherwise, we consider .local
821 * specific to mDNS and won't send such queries ordinary DNS servers. */
822 dns_name_endswith(domain, "local") > 0)
823 return DNS_SCOPE_NO;
824
825 /* If the IP address to look up matches the local subnet, then implicitly synthesizes
826 * DNS_SCOPE_YES_BASE + 0 on this interface, i.e. preferably resolve IP addresses via the DNS
827 * server belonging to this interface. */
828 m = match_subnet_reverse_lookups(s, domain, false);
829 if (m >= 0)
830 return m;
831
832 /* If there was no match at all, then see if this scope is suitable as default route. */
833 if (!dns_scope_is_default_route(s))
834 return DNS_SCOPE_NO;
835
836 /* Prefer suitable per-link scopes where possible */
837 if (dns_server_is_fallback(dns_scope_get_dns_server(s)))
838 return DNS_SCOPE_LAST_RESORT;
839
840 return DNS_SCOPE_MAYBE;
841 }
842
843 case DNS_PROTOCOL_MDNS: {
844 DnsScopeMatch m;
845
846 m = match_link_local_reverse_lookups(domain);
847 if (m >= 0)
848 return m;
849
850 m = match_subnet_reverse_lookups(s, domain, true);
851 if (m >= 0)
852 return m;
853
854 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
855 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
856 return DNS_SCOPE_LAST_RESORT;
857
858 if ((dns_name_endswith(domain, "local") > 0 && /* only resolve names ending in .local via mDNS */
859 dns_name_equal(domain, "local") == 0 && /* but not the single-label "local" name itself */
860 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via mDNS */
861 return DNS_SCOPE_YES_BASE + 1; /* Return +1, as the top-level .local domain matches, i.e. one label */
862
863 return DNS_SCOPE_NO;
864 }
865
866 case DNS_PROTOCOL_LLMNR: {
867 DnsScopeMatch m;
868
869 m = match_link_local_reverse_lookups(domain);
870 if (m >= 0)
871 return m;
872
873 m = match_subnet_reverse_lookups(s, domain, true);
874 if (m >= 0)
875 return m;
876
877 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
878 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
879 return DNS_SCOPE_LAST_RESORT;
880
881 if ((dns_name_is_single_label(domain) && /* only resolve single label names via LLMNR */
882 dns_name_equal(domain, "local") == 0 && /* don't resolve "local" with LLMNR, it's the top-level domain of mDNS after all, see above */
883 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via LLMNR */
884 return DNS_SCOPE_YES_BASE + 1; /* Return +1, as we consider ourselves authoritative
885 * for single-label names, i.e. one label. This is
886 * particularly relevant as it means a "." route on some
887 * other scope won't pull all traffic away from
888 * us. (If people actually want to pull traffic away
889 * from us they should turn off LLMNR on the
890 * link). Note that unicast DNS scopes with search
891 * domains also consider themselves authoritative for
892 * single-label domains, at the same preference (see
893 * above). */
894
895 return DNS_SCOPE_NO;
896 }
897
898 default:
899 assert_not_reached();
900 }
901 }
902
903 bool dns_scope_good_key(DnsScope *s, const DnsResourceKey *key) {
904 int key_family;
905
906 assert(s);
907 assert(key);
908
909 /* Check if it makes sense to resolve the specified key on this scope. Note that this call assumes a
910 * fully qualified name, i.e. the search suffixes already appended. */
911
912 if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
913 return false;
914
915 if (s->protocol == DNS_PROTOCOL_DNS) {
916
917 /* On classic DNS, looking up non-address RRs is always fine. (Specifically, we want to
918 * permit looking up DNSKEY and DS records on the root and top-level domains.) */
919 if (!dns_resource_key_is_address(key))
920 return true;
921
922 /* Unless explicitly overridden, we refuse to look up A and AAAA RRs on the root and
923 * single-label domains, under the assumption that those should be resolved via LLMNR or
924 * search path only, and should not be leaked onto the internet. */
925 const char* name = dns_resource_key_name(key);
926
927 if (!s->manager->resolve_unicast_single_label &&
928 dns_name_is_single_label(name))
929 return false;
930
931 return !dns_name_is_root(name);
932 }
933
934 /* Never route DNSSEC RR queries to LLMNR/mDNS scopes */
935 if (dns_type_is_dnssec(key->type))
936 return false;
937
938 /* On mDNS and LLMNR, send A and AAAA queries only on the respective scopes */
939
940 key_family = dns_type_to_af(key->type);
941 if (key_family < 0)
942 return true;
943
944 return key_family == s->family;
945 }
946
947 static int dns_scope_multicast_membership(DnsScope *s, bool b, struct in_addr in, struct in6_addr in6) {
948 int fd;
949
950 assert(s);
951 assert(s->link);
952
953 if (s->family == AF_INET) {
954 struct ip_mreqn mreqn = {
955 .imr_multiaddr = in,
956 .imr_ifindex = s->link->ifindex,
957 };
958
959 if (s->protocol == DNS_PROTOCOL_LLMNR)
960 fd = manager_llmnr_ipv4_udp_fd(s->manager);
961 else
962 fd = manager_mdns_ipv4_fd(s->manager);
963
964 if (fd < 0)
965 return fd;
966
967 /* Always first try to drop membership before we add
968 * one. This is necessary on some devices, such as
969 * veth. */
970 if (b)
971 (void) setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn));
972
973 if (setsockopt(fd, IPPROTO_IP, b ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0)
974 return -errno;
975
976 } else if (s->family == AF_INET6) {
977 struct ipv6_mreq mreq = {
978 .ipv6mr_multiaddr = in6,
979 .ipv6mr_ifindex = s->link->ifindex,
980 };
981
982 if (s->protocol == DNS_PROTOCOL_LLMNR)
983 fd = manager_llmnr_ipv6_udp_fd(s->manager);
984 else
985 fd = manager_mdns_ipv6_fd(s->manager);
986
987 if (fd < 0)
988 return fd;
989
990 if (b)
991 (void) setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
992
993 if (setsockopt(fd, IPPROTO_IPV6, b ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
994 return -errno;
995 } else
996 return -EAFNOSUPPORT;
997
998 return 0;
999 }
1000
1001 int dns_scope_llmnr_membership(DnsScope *s, bool b) {
1002 assert(s);
1003
1004 if (s->protocol != DNS_PROTOCOL_LLMNR)
1005 return 0;
1006
1007 return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
1008 }
1009
1010 int dns_scope_mdns_membership(DnsScope *s, bool b) {
1011 assert(s);
1012
1013 if (s->protocol != DNS_PROTOCOL_MDNS)
1014 return 0;
1015
1016 return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
1017 }
1018
1019 int dns_scope_make_reply_packet(
1020 DnsScope *s,
1021 uint16_t id,
1022 int rcode,
1023 DnsQuestion *q,
1024 DnsAnswer *answer,
1025 DnsAnswer *soa,
1026 bool tentative,
1027 DnsPacket **ret) {
1028
1029 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1030 unsigned n_answer = 0, n_soa = 0;
1031 int r;
1032 bool c_or_aa;
1033
1034 assert(s);
1035 assert(ret);
1036
1037 if (dns_question_isempty(q) &&
1038 dns_answer_isempty(answer) &&
1039 dns_answer_isempty(soa))
1040 return -EINVAL;
1041
1042 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1043 if (r < 0)
1044 return r;
1045
1046 /* mDNS answers must have the Authoritative Answer bit set, see RFC 6762, section 18.4. */
1047 c_or_aa = s->protocol == DNS_PROTOCOL_MDNS;
1048
1049 DNS_PACKET_HEADER(p)->id = id;
1050 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1051 1 /* qr */,
1052 0 /* opcode */,
1053 c_or_aa,
1054 0 /* tc */,
1055 tentative,
1056 0 /* (ra) */,
1057 0 /* (ad) */,
1058 0 /* (cd) */,
1059 rcode));
1060
1061 r = dns_packet_append_question(p, q);
1062 if (r < 0)
1063 return r;
1064 DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
1065
1066 r = dns_packet_append_answer(p, answer, &n_answer);
1067 if (r < 0)
1068 return r;
1069 DNS_PACKET_HEADER(p)->ancount = htobe16(n_answer);
1070
1071 r = dns_packet_append_answer(p, soa, &n_soa);
1072 if (r < 0)
1073 return r;
1074 DNS_PACKET_HEADER(p)->arcount = htobe16(n_soa);
1075
1076 *ret = TAKE_PTR(p);
1077
1078 return 0;
1079 }
1080
1081 static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
1082 DnsResourceRecord *rr;
1083 DnsResourceKey *key;
1084
1085 assert(s);
1086 assert(p);
1087
1088 DNS_QUESTION_FOREACH(key, p->question)
1089 dns_zone_verify_conflicts(&s->zone, key);
1090
1091 DNS_ANSWER_FOREACH(rr, p->answer)
1092 dns_zone_verify_conflicts(&s->zone, rr->key);
1093 }
1094
1095 void dns_scope_process_query(DnsScope *s, DnsStream *stream, DnsPacket *p) {
1096 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL, *soa = NULL;
1097 _cleanup_(dns_packet_unrefp) DnsPacket *reply = NULL;
1098 DnsResourceKey *key = NULL;
1099 bool tentative = false;
1100 int r;
1101
1102 assert(s);
1103 assert(p);
1104
1105 if (p->protocol != DNS_PROTOCOL_LLMNR)
1106 return;
1107
1108 if (p->ipproto == IPPROTO_UDP) {
1109 /* Don't accept UDP queries directed to anything but
1110 * the LLMNR multicast addresses. See RFC 4795,
1111 * section 2.5. */
1112
1113 if (p->family == AF_INET && !in4_addr_equal(&p->destination.in, &LLMNR_MULTICAST_IPV4_ADDRESS))
1114 return;
1115
1116 if (p->family == AF_INET6 && !in6_addr_equal(&p->destination.in6, &LLMNR_MULTICAST_IPV6_ADDRESS))
1117 return;
1118 }
1119
1120 r = dns_packet_extract(p);
1121 if (r < 0) {
1122 log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
1123 return;
1124 }
1125
1126 if (DNS_PACKET_LLMNR_C(p)) {
1127 /* Somebody notified us about a possible conflict */
1128 dns_scope_verify_conflicts(s, p);
1129 return;
1130 }
1131
1132 if (dns_question_size(p->question) != 1)
1133 return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
1134
1135 key = dns_question_first_key(p->question);
1136
1137 r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
1138 if (r < 0) {
1139 log_debug_errno(r, "Failed to look up key: %m");
1140 return;
1141 }
1142 if (r == 0)
1143 return;
1144
1145 if (answer)
1146 dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
1147
1148 r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
1149 if (r < 0) {
1150 log_debug_errno(r, "Failed to build reply packet: %m");
1151 return;
1152 }
1153
1154 if (stream) {
1155 r = dns_stream_write_packet(stream, reply);
1156 if (r < 0) {
1157 log_debug_errno(r, "Failed to enqueue reply packet: %m");
1158 return;
1159 }
1160
1161 /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
1162 * will be dangling until the stream is disconnected, and the default completion handler of the stream
1163 * will then unref the stream and destroy it */
1164 if (DNS_STREAM_QUEUED(stream))
1165 dns_stream_ref(stream);
1166 } else {
1167 int fd;
1168
1169 if (!ratelimit_below(&s->ratelimit))
1170 return;
1171
1172 if (p->family == AF_INET)
1173 fd = manager_llmnr_ipv4_udp_fd(s->manager);
1174 else if (p->family == AF_INET6)
1175 fd = manager_llmnr_ipv6_udp_fd(s->manager);
1176 else {
1177 log_debug("Unknown protocol");
1178 return;
1179 }
1180 if (fd < 0) {
1181 log_debug_errno(fd, "Failed to get reply socket: %m");
1182 return;
1183 }
1184
1185 /* Note that we always immediately reply to all LLMNR
1186 * requests, and do not wait any time, since we
1187 * verified uniqueness for all records. Also see RFC
1188 * 4795, Section 2.7 */
1189
1190 r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
1191 if (r < 0) {
1192 log_debug_errno(r, "Failed to send reply packet: %m");
1193 return;
1194 }
1195 }
1196 }
1197
1198 DnsTransaction *dns_scope_find_transaction(
1199 DnsScope *scope,
1200 DnsResourceKey *key,
1201 uint64_t query_flags) {
1202
1203 DnsTransaction *first;
1204
1205 assert(scope);
1206 assert(key);
1207
1208 /* Iterate through the list of transactions with a matching key */
1209 first = hashmap_get(scope->transactions_by_key, key);
1210 LIST_FOREACH(transactions_by_key, t, first) {
1211
1212 /* These four flags must match exactly: we cannot use a validated response for a
1213 * non-validating client, and we cannot use a non-validated response for a validating
1214 * client. Similar, if the sources don't match things aren't usable either. */
1215 if (((query_flags ^ t->query_flags) &
1216 (SD_RESOLVED_NO_VALIDATE|
1217 SD_RESOLVED_NO_ZONE|
1218 SD_RESOLVED_NO_TRUST_ANCHOR|
1219 SD_RESOLVED_NO_NETWORK)) != 0)
1220 continue;
1221
1222 /* We can reuse a primary query if a regular one is requested, but not vice versa */
1223 if ((query_flags & SD_RESOLVED_REQUIRE_PRIMARY) &&
1224 !(t->query_flags & SD_RESOLVED_REQUIRE_PRIMARY))
1225 continue;
1226
1227 /* Don't reuse a transaction that allowed caching when we got told not to use it */
1228 if ((query_flags & SD_RESOLVED_NO_CACHE) &&
1229 !(t->query_flags & SD_RESOLVED_NO_CACHE))
1230 continue;
1231
1232 /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
1233 * reuse */
1234 if ((query_flags & SD_RESOLVED_CLAMP_TTL) &&
1235 !(t->query_flags & SD_RESOLVED_CLAMP_TTL))
1236 continue;
1237
1238 return t;
1239 }
1240
1241 return NULL;
1242 }
1243
1244 static int dns_scope_make_conflict_packet(
1245 DnsScope *s,
1246 DnsResourceRecord *rr,
1247 DnsPacket **ret) {
1248
1249 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1250 int r;
1251
1252 assert(s);
1253 assert(rr);
1254 assert(ret);
1255
1256 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1257 if (r < 0)
1258 return r;
1259
1260 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1261 0 /* qr */,
1262 0 /* opcode */,
1263 1 /* conflict */,
1264 0 /* tc */,
1265 0 /* t */,
1266 0 /* (ra) */,
1267 0 /* (ad) */,
1268 0 /* (cd) */,
1269 0));
1270
1271 /* For mDNS, the transaction ID should always be 0 */
1272 if (s->protocol != DNS_PROTOCOL_MDNS)
1273 random_bytes(&DNS_PACKET_HEADER(p)->id, sizeof(uint16_t));
1274
1275 DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
1276 DNS_PACKET_HEADER(p)->arcount = htobe16(1);
1277
1278 r = dns_packet_append_key(p, rr->key, 0, NULL);
1279 if (r < 0)
1280 return r;
1281
1282 r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
1283 if (r < 0)
1284 return r;
1285
1286 *ret = TAKE_PTR(p);
1287
1288 return 0;
1289 }
1290
1291 static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
1292 DnsScope *scope = ASSERT_PTR(userdata);
1293 int r;
1294
1295 assert(es);
1296
1297 scope->conflict_event_source = sd_event_source_disable_unref(scope->conflict_event_source);
1298
1299 for (;;) {
1300 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1301 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1302 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1303
1304 rr = ordered_hashmap_steal_first_key_and_value(scope->conflict_queue, (void**) &key);
1305 if (!rr)
1306 break;
1307
1308 r = dns_scope_make_conflict_packet(scope, rr, &p);
1309 if (r < 0) {
1310 log_error_errno(r, "Failed to make conflict packet: %m");
1311 return 0;
1312 }
1313
1314 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1315 if (r < 0)
1316 log_debug_errno(r, "Failed to send conflict packet: %m");
1317 }
1318
1319 return 0;
1320 }
1321
1322 int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
1323 int r;
1324
1325 assert(scope);
1326 assert(rr);
1327
1328 /* We don't send these queries immediately. Instead, we queue them, and send them after some jitter
1329 * delay. We only place one RR per key in the conflict messages, not all of them. That should be
1330 * enough to indicate where there might be a conflict */
1331 r = ordered_hashmap_ensure_put(&scope->conflict_queue, &dns_resource_record_hash_ops_by_key, rr->key, rr);
1332 if (IN_SET(r, 0, -EEXIST))
1333 return 0;
1334 if (r < 0)
1335 return log_debug_errno(r, "Failed to queue conflicting RR: %m");
1336
1337 dns_resource_key_ref(rr->key);
1338 dns_resource_record_ref(rr);
1339
1340 if (scope->conflict_event_source)
1341 return 0;
1342
1343 r = sd_event_add_time_relative(
1344 scope->manager->event,
1345 &scope->conflict_event_source,
1346 CLOCK_BOOTTIME,
1347 random_u64_range(LLMNR_JITTER_INTERVAL_USEC),
1348 0,
1349 on_conflict_dispatch, scope);
1350 if (r < 0)
1351 return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
1352
1353 (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
1354
1355 return 0;
1356 }
1357
1358 void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
1359 DnsResourceRecord *rr;
1360 int r;
1361
1362 assert(scope);
1363 assert(p);
1364
1365 if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
1366 return;
1367
1368 if (DNS_PACKET_RRCOUNT(p) <= 0)
1369 return;
1370
1371 if (p->protocol == DNS_PROTOCOL_LLMNR) {
1372 if (DNS_PACKET_LLMNR_C(p) != 0)
1373 return;
1374
1375 if (DNS_PACKET_LLMNR_T(p) != 0)
1376 return;
1377 }
1378
1379 if (manager_packet_from_local_address(scope->manager, p))
1380 return;
1381
1382 r = dns_packet_extract(p);
1383 if (r < 0) {
1384 log_debug_errno(r, "Failed to extract packet: %m");
1385 return;
1386 }
1387
1388 log_debug("Checking for conflicts...");
1389
1390 DNS_ANSWER_FOREACH(rr, p->answer) {
1391 /* No conflict if it is DNS-SD RR used for service enumeration. */
1392 if (dns_resource_key_is_dnssd_ptr(rr->key))
1393 continue;
1394
1395 /* Check for conflicts against the local zone. If we
1396 * found one, we won't check any further */
1397 r = dns_zone_check_conflicts(&scope->zone, rr);
1398 if (r != 0)
1399 continue;
1400
1401 /* Check for conflicts against the local cache. If so,
1402 * send out an advisory query, to inform everybody */
1403 r = dns_cache_check_conflicts(&scope->cache, rr, p->family, &p->sender);
1404 if (r <= 0)
1405 continue;
1406
1407 dns_scope_notify_conflict(scope, rr);
1408 }
1409 }
1410
1411 void dns_scope_dump(DnsScope *s, FILE *f) {
1412 assert(s);
1413
1414 if (!f)
1415 f = stdout;
1416
1417 fputs("[Scope protocol=", f);
1418 fputs(dns_protocol_to_string(s->protocol), f);
1419
1420 if (s->link) {
1421 fputs(" interface=", f);
1422 fputs(s->link->ifname, f);
1423 }
1424
1425 if (s->family != AF_UNSPEC) {
1426 fputs(" family=", f);
1427 fputs(af_to_name(s->family), f);
1428 }
1429
1430 fputs(" origin=", f);
1431 fputs(dns_scope_origin_to_string(s->origin), f);
1432
1433 if (s->delegate) {
1434 fputs(" id=", f);
1435 fputs(s->delegate->id, f);
1436 }
1437
1438 if (s->protocol == DNS_PROTOCOL_DNS) {
1439 fputs(" DNSSEC=", f);
1440 fputs(dnssec_mode_to_string(s->dnssec_mode), f);
1441
1442 fputs(" DNSOverTLS=", f);
1443 fputs(dns_over_tls_mode_to_string(s->dns_over_tls_mode), f);
1444 }
1445
1446 fputs("]\n", f);
1447
1448 if (!dns_zone_is_empty(&s->zone)) {
1449 fputs("ZONE:\n", f);
1450 dns_zone_dump(&s->zone, f);
1451 }
1452
1453 if (!dns_cache_is_empty(&s->cache)) {
1454 fputs("CACHE:\n", f);
1455 dns_cache_dump(&s->cache, f);
1456 }
1457 }
1458
1459 DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
1460 assert(s);
1461
1462 if (s->protocol != DNS_PROTOCOL_DNS)
1463 return NULL;
1464
1465 if (s->link)
1466 return s->link->search_domains;
1467 if (s->delegate)
1468 return s->delegate->search_domains;
1469
1470 return s->manager->search_domains;
1471 }
1472
1473 bool dns_scope_name_wants_search_domain(DnsScope *s, const char *name) {
1474 assert(s);
1475
1476 if (s->protocol != DNS_PROTOCOL_DNS)
1477 return false;
1478
1479 if (!dns_name_is_single_label(name))
1480 return false;
1481
1482 /* If we allow single-label domain lookups on unicast DNS, and this scope has a search domain that matches
1483 * _exactly_ this name, then do not use search domains. */
1484 if (s->manager->resolve_unicast_single_label)
1485 LIST_FOREACH(domains, d, dns_scope_get_search_domains(s))
1486 if (dns_name_equal(name, d->name) > 0)
1487 return false;
1488
1489 return true;
1490 }
1491
1492 bool dns_scope_network_good(DnsScope *s) {
1493 /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
1494 * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
1495 * DNS scope we check whether there are any links that are up and have an address.
1496 *
1497 * Note that Linux routing is complex and even systems that superficially have no IPv4 address might
1498 * be able to route IPv4 (and similar for IPv6), hence let's make a check here independent of address
1499 * family. */
1500
1501 if (s->link)
1502 return true;
1503
1504 return manager_routable(s->manager);
1505 }
1506
1507 int dns_scope_ifindex(DnsScope *s) {
1508 assert(s);
1509
1510 if (s->link)
1511 return s->link->ifindex;
1512
1513 return 0;
1514 }
1515
1516 const char* dns_scope_ifname(DnsScope *s) {
1517 assert(s);
1518
1519 if (s->link)
1520 return s->link->ifname;
1521
1522 return NULL;
1523 }
1524
1525 static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1526 DnsScope *scope = userdata;
1527
1528 assert(s);
1529
1530 scope->announce_event_source = sd_event_source_disable_unref(scope->announce_event_source);
1531
1532 (void) dns_scope_announce(scope, false);
1533 return 0;
1534 }
1535
1536 int dns_scope_announce(DnsScope *scope, bool goodbye) {
1537 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
1538 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1539 _cleanup_set_free_ Set *types = NULL;
1540 DnsZoneItem *z;
1541 unsigned size = 0;
1542 char *service_type;
1543 int r;
1544
1545 if (!scope)
1546 return 0;
1547
1548 if (scope->protocol != DNS_PROTOCOL_MDNS)
1549 return 0;
1550
1551 r = sd_event_get_state(scope->manager->event);
1552 if (r < 0)
1553 return log_debug_errno(r, "Failed to get event loop state: %m");
1554
1555 /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
1556 if (r == SD_EVENT_FINISHED)
1557 return 0;
1558
1559 /* Check if we're done with probing. */
1560 LIST_FOREACH(transactions_by_scope, t, scope->transactions)
1561 if (t->probing && DNS_TRANSACTION_IS_LIVE(t->state))
1562 return 0;
1563
1564 /* Check if there're services pending conflict resolution. */
1565 if (manager_next_dnssd_names(scope->manager))
1566 return 0; /* we reach this point only if changing hostname didn't help */
1567
1568 /* Calculate answer's size. */
1569 HASHMAP_FOREACH(z, scope->zone.by_key) {
1570 if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
1571 continue;
1572
1573 if (z->rr->key->type == DNS_TYPE_PTR &&
1574 !dns_zone_contains_name(&scope->zone, z->rr->ptr.name)) {
1575 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1576
1577 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));
1578 z->state = DNS_ZONE_ITEM_WITHDRAWN;
1579 continue;
1580 }
1581
1582 /* Collect service types for _services._dns-sd._udp.local RRs in a set. Only two-label names
1583 * (not selective names) are considered according to RFC6763 § 9. */
1584 if (!scope->announced &&
1585 dns_resource_key_is_dnssd_two_label_ptr(z->rr->key)) {
1586 if (!set_contains(types, dns_resource_key_name(z->rr->key))) {
1587 r = set_ensure_put(&types, &dns_name_hash_ops, dns_resource_key_name(z->rr->key));
1588 if (r < 0)
1589 return log_debug_errno(r, "Failed to add item to set: %m");
1590 }
1591 }
1592
1593 LIST_FOREACH(by_key, i, z)
1594 size++;
1595 }
1596
1597 answer = dns_answer_new(size + set_size(types));
1598 if (!answer)
1599 return log_oom();
1600
1601 /* Second iteration, actually add RRs to the answer. */
1602 HASHMAP_FOREACH(z, scope->zone.by_key)
1603 LIST_FOREACH (by_key, i, z) {
1604 DnsAnswerFlags flags;
1605
1606 if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
1607 continue;
1608
1609 if (dns_resource_key_is_dnssd_ptr(i->rr->key))
1610 flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
1611 else
1612 flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
1613
1614 r = dns_answer_add(answer, i->rr, 0, flags, NULL);
1615 if (r < 0)
1616 return log_debug_errno(r, "Failed to add RR to announce: %m");
1617 }
1618
1619 /* Since all the active services are in the zone make them discoverable now. */
1620 SET_FOREACH(service_type, types) {
1621 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1622
1623 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
1624 "_services._dns-sd._udp.local");
1625 if (!rr)
1626 return log_oom();
1627
1628 rr->ptr.name = strdup(service_type);
1629 if (!rr->ptr.name)
1630 return log_oom();
1631
1632 rr->ttl = MDNS_DEFAULT_TTL;
1633
1634 r = dns_zone_put(&scope->zone, scope, rr, false);
1635 if (r < 0)
1636 log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
1637
1638 r = dns_answer_add(answer, rr, 0, 0, NULL);
1639 if (r < 0)
1640 return log_debug_errno(r, "Failed to add RR to announce: %m");
1641 }
1642
1643 if (dns_answer_isempty(answer))
1644 return 0;
1645
1646 r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
1647 if (r < 0)
1648 return log_debug_errno(r, "Failed to build reply packet: %m");
1649
1650 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1651 if (r < 0)
1652 return log_debug_errno(r, "Failed to send reply packet: %m");
1653
1654 /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
1655 * responses, one second apart." */
1656 if (!scope->announced) {
1657 scope->announced = true;
1658
1659 r = sd_event_add_time_relative(
1660 scope->manager->event,
1661 &scope->announce_event_source,
1662 CLOCK_BOOTTIME,
1663 MDNS_ANNOUNCE_DELAY,
1664 0,
1665 on_announcement_timeout, scope);
1666 if (r < 0)
1667 return log_debug_errno(r, "Failed to schedule second announcement: %m");
1668
1669 (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
1670 }
1671
1672 return 0;
1673 }
1674
1675 int dns_scope_add_dnssd_registered_services(DnsScope *scope) {
1676 DnssdRegisteredService *service;
1677 int r;
1678
1679 assert(scope);
1680
1681 if (hashmap_isempty(scope->manager->dnssd_registered_services))
1682 return 0;
1683
1684 scope->announced = false;
1685
1686 HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
1687 service->withdrawn = false;
1688
1689 r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
1690 if (r < 0)
1691 log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
1692
1693 if (service->sub_ptr_rr) {
1694 r = dns_zone_put(&scope->zone, scope, service->sub_ptr_rr, false);
1695 if (r < 0)
1696 log_warning_errno(r, "Failed to add selective PTR record to MDNS zone: %m");
1697 }
1698
1699 r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
1700 if (r < 0)
1701 log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
1702
1703 LIST_FOREACH(items, txt_data, service->txt_data_items) {
1704 r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
1705 if (r < 0)
1706 log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
1707 }
1708 }
1709
1710 return 0;
1711 }
1712
1713 int dns_scope_remove_dnssd_registered_services(DnsScope *scope) {
1714 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1715 DnssdRegisteredService *service;
1716 int r;
1717
1718 assert(scope);
1719
1720 key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
1721 "_services._dns-sd._udp.local");
1722 if (!key)
1723 return log_oom();
1724
1725 r = dns_zone_remove_rrs_by_key(&scope->zone, key);
1726 if (r < 0)
1727 return r;
1728
1729 HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
1730 dns_zone_remove_rr(&scope->zone, service->ptr_rr);
1731 dns_zone_remove_rr(&scope->zone, service->sub_ptr_rr);
1732 dns_zone_remove_rr(&scope->zone, service->srv_rr);
1733 LIST_FOREACH(items, txt_data, service->txt_data_items)
1734 dns_zone_remove_rr(&scope->zone, txt_data->rr);
1735 }
1736
1737 return 0;
1738 }
1739
1740 static bool dns_scope_has_route_only_domains(DnsScope *scope) {
1741 DnsSearchDomain *first;
1742 bool route_only = false;
1743
1744 assert(scope);
1745 assert(scope->protocol == DNS_PROTOCOL_DNS);
1746
1747 /* Returns 'true' if this scope is suitable for queries to specific domains only. For that we check
1748 * if there are any route-only domains on this interface, as a heuristic to discern VPN-style links
1749 * from non-VPN-style links. Returns 'false' for all other cases, i.e. if the scope is intended to
1750 * take queries to arbitrary domains, i.e. has no routing domains set. */
1751
1752 if (scope->link)
1753 first = scope->link->search_domains;
1754 else if (scope->delegate)
1755 first = scope->delegate->search_domains;
1756 else
1757 first = scope->manager->search_domains;
1758
1759 LIST_FOREACH(domains, domain, first) {
1760 /* "." means "any domain", thus the interface takes any kind of traffic. Thus, we exit early
1761 * here, as it doesn't really matter whether this link has any route-only domains or not,
1762 * "~." really trumps everything and clearly indicates that this interface shall receive all
1763 * traffic it can get. */
1764 if (dns_name_is_root(DNS_SEARCH_DOMAIN_NAME(domain)))
1765 return false;
1766
1767 if (domain->route_only)
1768 route_only = true;
1769 }
1770
1771 return route_only;
1772 }
1773
1774 bool dns_scope_is_default_route(DnsScope *scope) {
1775 assert(scope);
1776
1777 /* Only use DNS scopes as default routes */
1778 if (scope->protocol != DNS_PROTOCOL_DNS)
1779 return false;
1780
1781 if (scope->link) {
1782
1783 /* Honour whatever is explicitly configured. This is really the best approach, and trumps any
1784 * automatic logic. */
1785 if (scope->link->default_route >= 0)
1786 return scope->link->default_route;
1787
1788 /* Otherwise check if we have any route-only domains, as a sensible heuristic: if so, let's not
1789 * volunteer as default route. */
1790 return !dns_scope_has_route_only_domains(scope);
1791
1792 } else if (scope->delegate) {
1793
1794 if (scope->delegate->default_route >= 0)
1795 return scope->delegate->default_route;
1796
1797 /* Delegates are by default not used as default route */
1798 return false;
1799 } else
1800 /* The global DNS scope is always suitable as default route */
1801 return true;
1802 }
1803
1804 int dns_scope_to_json(DnsScope *scope, bool with_cache, sd_json_variant **ret) {
1805 _cleanup_(sd_json_variant_unrefp) sd_json_variant *cache = NULL;
1806 int r;
1807
1808 assert(scope);
1809 assert(ret);
1810
1811 if (with_cache) {
1812 r = dns_cache_dump_to_json(&scope->cache, &cache);
1813 if (r < 0)
1814 return r;
1815 }
1816
1817 return sd_json_buildo(
1818 ret,
1819 JSON_BUILD_PAIR_ENUM("protocol", dns_protocol_to_string(scope->protocol)),
1820 SD_JSON_BUILD_PAIR_CONDITION(scope->family != AF_UNSPEC, "family", SD_JSON_BUILD_INTEGER(scope->family)),
1821 SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifindex", SD_JSON_BUILD_INTEGER(dns_scope_ifindex(scope))),
1822 SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifname", SD_JSON_BUILD_STRING(dns_scope_ifname(scope))),
1823 SD_JSON_BUILD_PAIR_CONDITION(with_cache, "cache", SD_JSON_BUILD_VARIANT(cache)),
1824 SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
1825 "dnssec",
1826 SD_JSON_BUILD_STRING(dnssec_mode_to_string(scope->dnssec_mode))),
1827 SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
1828 "dnsOverTLS",
1829 SD_JSON_BUILD_STRING(dns_over_tls_mode_to_string(scope->dns_over_tls_mode))));
1830 }
1831
1832 int dns_type_suitable_for_protocol(uint16_t type, DnsProtocol protocol) {
1833
1834 /* Tests whether it makes sense to route queries for the specified DNS RR types to the specified
1835 * protocol. For classic DNS pretty much all RR types are suitable, but for LLMNR/mDNS let's
1836 * allowlist only a few that make sense. We use this when routing queries so that we can more quickly
1837 * return errors for queries that will almost certainly fail/time out otherwise. For example, this
1838 * ensures that SOA, NS, or DS/DNSKEY queries are never routed to mDNS/LLMNR where they simply make
1839 * no sense. */
1840
1841 if (dns_type_is_obsolete(type))
1842 return false;
1843
1844 if (!dns_type_is_valid_query(type))
1845 return false;
1846
1847 switch (protocol) {
1848
1849 case DNS_PROTOCOL_DNS:
1850 return true;
1851
1852 case DNS_PROTOCOL_LLMNR:
1853 return IN_SET(type,
1854 DNS_TYPE_ANY,
1855 DNS_TYPE_A,
1856 DNS_TYPE_AAAA,
1857 DNS_TYPE_CNAME,
1858 DNS_TYPE_PTR,
1859 DNS_TYPE_TXT);
1860
1861 case DNS_PROTOCOL_MDNS:
1862 return IN_SET(type,
1863 DNS_TYPE_ANY,
1864 DNS_TYPE_A,
1865 DNS_TYPE_AAAA,
1866 DNS_TYPE_CNAME,
1867 DNS_TYPE_PTR,
1868 DNS_TYPE_TXT,
1869 DNS_TYPE_SRV,
1870 DNS_TYPE_NSEC,
1871 DNS_TYPE_HINFO);
1872
1873 default:
1874 return -EPROTONOSUPPORT;
1875 }
1876 }
1877
1878 int dns_question_types_suitable_for_protocol(DnsQuestion *q, DnsProtocol protocol) {
1879 DnsResourceKey *key;
1880 int r;
1881
1882 /* Tests whether the types in the specified question make any sense to be routed to the specified
1883 * protocol, i.e. if dns_type_suitable_for_protocol() is true for any of the contained RR types */
1884
1885 DNS_QUESTION_FOREACH(key, q) {
1886 r = dns_type_suitable_for_protocol(key->type, protocol);
1887 if (r != 0)
1888 return r;
1889 }
1890
1891 return false;
1892 }
1893
1894 static const char* const dns_scope_origin_table[_DNS_SCOPE_ORIGIN_MAX] = {
1895 [DNS_SCOPE_GLOBAL] = "global",
1896 [DNS_SCOPE_LINK] = "link",
1897 [DNS_SCOPE_DELEGATE] = "delegate",
1898 };
1899
1900 DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin, DnsScopeOrigin);