]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/resolved-dns-scope.c
72b918b3cfce52da9372ab7fb285edc0a38f29e9
[thirdparty/systemd.git] / src / resolve / resolved-dns-scope.c
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-domain.h"
11 #include "dns-type.h"
12 #include "errno-util.h"
13 #include "fd-util.h"
14 #include "hostname-util.h"
15 #include "log.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"
35 #include "set.h"
36 #include "socket-util.h"
37 #include "string-table.h"
38
39 #define MULTICAST_RATELIMIT_INTERVAL_USEC (1*USEC_PER_SEC)
40 #define MULTICAST_RATELIMIT_BURST 1000
41
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)
45
46 int dns_scope_new(
47 Manager *m,
48 DnsScope **ret,
49 DnsScopeOrigin origin,
50 Link *link,
51 DnsDelegate *delegate,
52 DnsProtocol protocol,
53 int family) {
54
55 DnsScope *s;
56
57 assert(m);
58 assert(ret);
59 assert(origin >= 0);
60 assert(origin < _DNS_SCOPE_ORIGIN_MAX);
61
62 assert(!!link == (origin == DNS_SCOPE_LINK));
63 assert(!!delegate == (origin == DNS_SCOPE_DELEGATE));
64
65 s = new(DnsScope, 1);
66 if (!s)
67 return -ENOMEM;
68
69 *s = (DnsScope) {
70 .manager = m,
71 .link = link,
72 .delegate = delegate,
73 .origin = origin,
74 .protocol = protocol,
75 .family = family,
76 .resend_timeout = MULTICAST_RESEND_TIMEOUT_MIN_USEC,
77
78 /* Enforce ratelimiting for the multicast protocols */
79 .ratelimit = { MULTICAST_RATELIMIT_INTERVAL_USEC, MULTICAST_RATELIMIT_BURST },
80 };
81
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
87 * changes. */
88
89 if (link) {
90 s->dnssec_mode = link_get_dnssec_mode(link);
91 s->dns_over_tls_mode = link_get_dns_over_tls_mode(link);
92 } else {
93 s->dnssec_mode = manager_get_dnssec_mode(m);
94 s->dns_over_tls_mode = manager_get_dns_over_tls_mode(m);
95 }
96
97 } else {
98 s->dnssec_mode = DNSSEC_NO;
99 s->dns_over_tls_mode = DNS_OVER_TLS_NO;
100 }
101
102 LIST_PREPEND(scopes, m->dns_scopes, s);
103
104 dns_scope_llmnr_membership(s, true);
105 dns_scope_mdns_membership(s, true);
106
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");
113
114 *ret = s;
115 return 0;
116 }
117
118 static void dns_scope_abort_transactions(DnsScope *s) {
119 assert(s);
120
121 while (s->transactions) {
122 DnsTransaction *t = s->transactions;
123
124 /* Abort the transaction, but make sure it is not
125 * freed while we still look at it */
126
127 t->block_gc++;
128 if (DNS_TRANSACTION_IS_LIVE(t->state))
129 dns_transaction_complete(t, DNS_TRANSACTION_ABORTED);
130 t->block_gc--;
131
132 dns_transaction_free(t);
133 }
134 }
135
136 DnsScope* dns_scope_free(DnsScope *s) {
137 if (!s)
138 return NULL;
139
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");
146
147 dns_scope_llmnr_membership(s, false);
148 dns_scope_mdns_membership(s, false);
149 dns_scope_abort_transactions(s);
150
151 while (s->query_candidates)
152 dns_query_candidate_unref(s->query_candidates);
153
154 hashmap_free(s->transactions_by_key);
155
156 ordered_hashmap_free(s->conflict_queue);
157 sd_event_source_disable_unref(s->conflict_event_source);
158
159 sd_event_source_disable_unref(s->announce_event_source);
160
161 sd_event_source_disable_unref(s->mdns_goodbye_event_source);
162
163 dns_cache_flush(&s->cache);
164 dns_zone_flush(&s->zone);
165
166 LIST_REMOVE(scopes, s->manager->dns_scopes, s);
167 return mfree(s);
168 }
169
170 DnsServer *dns_scope_get_dns_server(DnsScope *s) {
171 assert(s);
172
173 if (s->protocol != DNS_PROTOCOL_DNS)
174 return NULL;
175
176 if (s->link) {
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);
181 else
182 return manager_get_dns_server(s->manager);
183 }
184
185 unsigned dns_scope_get_n_dns_servers(DnsScope *s) {
186 assert(s);
187
188 if (s->protocol != DNS_PROTOCOL_DNS)
189 return 0;
190
191 if (s->link) {
192 assert(!s->delegate);
193 return s->link->n_dns_servers;
194 } else if (s->delegate)
195 return s->delegate->n_dns_servers;
196 else
197 return s->manager->n_dns_servers;
198 }
199
200 void dns_scope_next_dns_server(DnsScope *s, DnsServer *if_current) {
201 assert(s);
202
203 if (s->protocol != DNS_PROTOCOL_DNS)
204 return;
205
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. */
208
209 if (s->link)
210 link_next_dns_server(s->link, if_current);
211 else if (s->delegate)
212 dns_delegate_next_dns_server(s->delegate, if_current);
213 else
214 manager_next_dns_server(s->manager, if_current);
215 }
216
217 void dns_scope_packet_received(DnsScope *s, usec_t rtt) {
218 assert(s);
219
220 if (rtt <= s->max_rtt)
221 return;
222
223 s->max_rtt = rtt;
224 s->resend_timeout = MIN(MAX(MULTICAST_RESEND_TIMEOUT_MIN_USEC, s->max_rtt * 2), MULTICAST_RESEND_TIMEOUT_MAX_USEC);
225 }
226
227 void dns_scope_packet_lost(DnsScope *s, usec_t usec) {
228 assert(s);
229
230 if (s->resend_timeout <= usec)
231 s->resend_timeout = MIN(s->resend_timeout * 2, MULTICAST_RESEND_TIMEOUT_MAX_USEC);
232 }
233
234 static int dns_scope_emit_one(DnsScope *s, int fd, int family, DnsPacket *p) {
235 int r;
236
237 assert(s);
238 assert(p);
239 assert(p->protocol == s->protocol);
240
241 if (family == AF_UNSPEC) {
242 if (s->family == AF_UNSPEC)
243 return -EAFNOSUPPORT;
244
245 family = s->family;
246 }
247
248 switch (s->protocol) {
249
250 case DNS_PROTOCOL_DNS: {
251 size_t mtu, udp_size, min_mtu, socket_mtu = 0;
252
253 assert(fd >= 0);
254
255 if (DNS_PACKET_QDCOUNT(p) > 1) /* Classic DNS only allows one question per packet */
256 return -EOPNOTSUPP;
257
258 if (p->size > DNS_PACKET_UNICAST_SIZE_MAX)
259 return -EMSGSIZE;
260
261 /* Determine the local most accurate MTU */
262 if (s->link)
263 mtu = s->link->mtu;
264 else
265 mtu = manager_find_mtu(s->manager);
266
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");
271
272 /* Determine the appropriate UDP header size */
273 udp_size = udp_header_size(family);
274 min_mtu = udp_size + DNS_PACKET_HEADER_SIZE;
275
276 log_debug("Emitting UDP, link MTU is %zu, socket MTU is %zu, minimal MTU is %zu",
277 mtu, socket_mtu, min_mtu);
278
279 /* Clamp by the kernel's idea of the (path) MTU */
280 if (socket_mtu != 0 && socket_mtu < mtu)
281 mtu = socket_mtu;
282
283 /* Put a lower limit, in case all MTU data we acquired was rubbish */
284 if (mtu < min_mtu)
285 mtu = min_mtu;
286
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 */
290
291 r = manager_write(s->manager, fd, p);
292 if (r < 0)
293 return r;
294
295 break;
296 }
297
298 case DNS_PROTOCOL_LLMNR: {
299 union in_addr_union addr;
300
301 assert(fd < 0);
302
303 if (DNS_PACKET_QDCOUNT(p) > 1)
304 return -EOPNOTSUPP;
305
306 if (!ratelimit_below(&s->ratelimit))
307 return -EBUSY;
308
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);
315 } else
316 return -EAFNOSUPPORT;
317 if (fd < 0)
318 return fd;
319
320 assert(s->link);
321 r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, LLMNR_PORT, NULL, p);
322 if (r < 0)
323 return r;
324
325 break;
326 }
327
328 case DNS_PROTOCOL_MDNS: {
329 union in_addr_union addr;
330 assert(fd < 0);
331
332 if (!ratelimit_below(&s->ratelimit))
333 return -EBUSY;
334
335 if (family == AF_INET) {
336 if (in4_addr_is_null(&p->destination.in))
337 addr.in = MDNS_MULTICAST_IPV4_ADDRESS;
338 else
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;
344 else
345 addr = p->destination;
346 fd = manager_mdns_ipv6_fd(s->manager);
347 } else
348 return -EAFNOSUPPORT;
349 if (fd < 0)
350 return fd;
351
352 assert(s->link);
353 r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, p->destination_port ?: MDNS_PORT, NULL, p);
354 if (r < 0)
355 return r;
356
357 break;
358 }
359
360 default:
361 return -EAFNOSUPPORT;
362 }
363
364 return 1;
365 }
366
367 int dns_scope_emit_udp(DnsScope *s, int fd, int af, DnsPacket *p) {
368 int r;
369
370 assert(s);
371 assert(p);
372 assert(p->protocol == s->protocol);
373 assert((s->protocol == DNS_PROTOCOL_DNS) == (fd >= 0));
374
375 do {
376 /* If there are multiple linked packets, set the TC bit in all but the last of them */
377 if (p->more) {
378 assert(p->protocol == DNS_PROTOCOL_MDNS);
379 dns_packet_set_flags(p, true, true);
380 }
381
382 r = dns_scope_emit_one(s, fd, af, p);
383 if (r < 0)
384 return r;
385
386 p = p->more;
387 } while (p);
388
389 return 0;
390 }
391
392 static int dns_scope_socket(
393 DnsScope *s,
394 int type,
395 int family,
396 const union in_addr_union *address,
397 DnsServer *server,
398 uint16_t port,
399 union sockaddr_union *ret_socket_address) {
400
401 _cleanup_close_ int fd = -EBADF;
402 union sockaddr_union sa;
403 socklen_t salen;
404 int r, ifindex;
405
406 assert(s);
407
408 if (server) {
409 assert(family == AF_UNSPEC);
410 assert(!address);
411
412 ifindex = dns_server_ifindex(server);
413
414 switch (server->family) {
415 case AF_INET:
416 sa = (union sockaddr_union) {
417 .in.sin_family = server->family,
418 .in.sin_port = htobe16(port),
419 .in.sin_addr = server->address.in,
420 };
421 salen = sizeof(sa.in);
422 break;
423 case AF_INET6:
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,
429 };
430 salen = sizeof(sa.in6);
431 break;
432 default:
433 return -EAFNOSUPPORT;
434 }
435 } else {
436 assert(family != AF_UNSPEC);
437 assert(address);
438
439 ifindex = dns_scope_ifindex(s);
440
441 switch (family) {
442 case AF_INET:
443 sa = (union sockaddr_union) {
444 .in.sin_family = family,
445 .in.sin_port = htobe16(port),
446 .in.sin_addr = address->in,
447 };
448 salen = sizeof(sa.in);
449 break;
450 case AF_INET6:
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,
456 };
457 salen = sizeof(sa.in6);
458 break;
459 default:
460 return -EAFNOSUPPORT;
461 }
462 }
463
464 fd = socket(sa.sa.sa_family, type|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
465 if (fd < 0)
466 return -errno;
467
468 if (type == SOCK_STREAM) {
469 r = setsockopt_int(fd, IPPROTO_TCP, TCP_NODELAY, true);
470 if (r < 0)
471 return r;
472 }
473
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;
477
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);
484 if (r < 0)
485 return r;
486 }
487
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);
491 if (r < 0)
492 return r;
493 }
494
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);
498 if (r < 0)
499 return r;
500
501 r = socket_set_recvpktinfo(fd, sa.sa.sa_family, true);
502 if (r < 0)
503 return r;
504
505 /* Turn of path MTU discovery for security reasons */
506 r = socket_disable_pmtud(fd, sa.sa.sa_family);
507 if (r < 0)
508 log_debug_errno(r, "Failed to disable UDP PMTUD, ignoring: %m");
509
510 /* Learn about fragmentation taking place */
511 r = socket_set_recvfragsize(fd, sa.sa.sa_family, true);
512 if (r < 0)
513 log_debug_errno(r, "Failed to enable fragment size reception, ignoring: %m");
514 }
515
516 if (ret_socket_address)
517 *ret_socket_address = sa;
518 else {
519 bool bound = false;
520
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
525 * again.
526 */
527 if (addr_is_nonlocal) {
528 r = socket_bind_to_ifindex(fd, ifindex);
529 if (r < 0)
530 return r;
531
532 bound = true;
533 }
534
535 r = connect(fd, &sa.sa, salen);
536 if (r < 0 && errno != EINPROGRESS)
537 return -errno;
538
539 if (bound) {
540 r = socket_bind_to_ifindex(fd, 0);
541 if (r < 0)
542 return r;
543 }
544 }
545
546 return TAKE_FD(fd);
547 }
548
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);
551 }
552
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);
559 }
560
561 static DnsScopeMatch match_link_local_reverse_lookups(const char *domain) {
562 assert(domain);
563
564 if (dns_name_endswith(domain, "254.169.in-addr.arpa") > 0)
565 return DNS_SCOPE_YES_BASE + 4; /* 4 labels match */
566
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 */
572
573 return _DNS_SCOPE_MATCH_INVALID;
574 }
575
576 static DnsScopeMatch match_subnet_reverse_lookups(
577 DnsScope *s,
578 const char *domain,
579 bool exclude_own) {
580
581 union in_addr_union ia;
582 int f, r;
583
584 assert(s);
585 assert(domain);
586
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.
591 *
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. */
595
596 if (!s->link)
597 return _DNS_SCOPE_MATCH_INVALID; /* No link, hence no local addresses to check */
598
599 r = dns_name_address(domain, &f, &ia);
600 if (r < 0)
601 log_debug_errno(r, "Failed to determine whether '%s' is an address domain: %m", domain);
602 if (r <= 0)
603 return _DNS_SCOPE_MATCH_INVALID;
604
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 */
607
608 if (in_addr_is_null(f, &ia))
609 return DNS_SCOPE_NO;
610
611 LIST_FOREACH(addresses, a, s->link->addresses) {
612
613 if (a->family != f)
614 continue;
615
616 /* Equals our own address? nah, let's not use this scope. The local synthesizer will pick it up for us. */
617 if (exclude_own &&
618 in_addr_equal(f, &a->in_addr, &ia) > 0)
619 return DNS_SCOPE_NO;
620
621 if (a->prefixlen == UCHAR_MAX) /* don't know subnet mask */
622 continue;
623
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)
626 return DNS_SCOPE_NO;
627
628 /* Check if the address is in the local subnet */
629 r = in_addr_prefix_covers(f, &a->in_addr, a->prefixlen, &ia);
630 if (r < 0)
631 log_debug_errno(r, "Failed to determine whether link address covers lookup address '%s': %m", domain);
632 if (r > 0)
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;
636 }
637
638 return _DNS_SCOPE_MATCH_INVALID;
639 }
640
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) {
648 DnsResourceKey *t;
649
650 /* Only SVCB is permitted to _dns.resolver.arpa */
651 DNS_QUESTION_FOREACH(t, question)
652 if (t->type == DNS_TYPE_SVCB)
653 return false;
654
655 return true;
656 }
657
658 if (dns_name_endswith(domain, "resolver.arpa") > 0)
659 return true;
660
661 return false;
662 }
663
664 DnsScopeMatch dns_scope_good_domain(
665 DnsScope *s,
666 DnsQuery *q,
667 uint64_t query_flags) {
668
669 DnsQuestion *question;
670 const char *domain;
671 uint64_t flags;
672 int ifindex, r;
673
674 /* This returns the following return values:
675 *
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
680 *
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.)
684 */
685
686 assert(s);
687 assert(q);
688
689 question = dns_query_question_for_protocol(q, s->protocol);
690 if (!question)
691 return DNS_SCOPE_NO;
692
693 domain = dns_question_first_name(question);
694 if (!domain)
695 return DNS_SCOPE_NO;
696
697 ifindex = q->ifindex;
698 flags = q->flags;
699
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. */
702
703 if (ifindex != 0 && (!s->link || s->link->ifindex != ifindex))
704 return DNS_SCOPE_NO;
705
706 if ((SD_RESOLVED_FLAGS_MAKE(s->protocol, s->family, false, false) & flags) == 0)
707 return DNS_SCOPE_NO;
708
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)
714 return DNS_SCOPE_NO;
715
716 /* Never respond to some of the domains listed in RFC6303 + RFC6761 */
717 if (dns_name_dont_resolve(domain))
718 return DNS_SCOPE_NO;
719
720 /* Avoid asking invalid questions of some special use domains */
721 if (dns_refuse_special_use_domain(domain, question))
722 return DNS_SCOPE_NO;
723
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))
729 return DNS_SCOPE_NO;
730
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())
733 return DNS_SCOPE_NO;
734
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);
737 if (r <= 0)
738 return DNS_SCOPE_NO;
739
740 switch (s->protocol) {
741
742 case DNS_PROTOCOL_DNS: {
743 bool has_search_domains = false;
744 DnsScopeMatch m;
745 int n_best = -1;
746
747 if (dns_name_is_root(domain)) {
748 DnsResourceKey *t;
749 bool found = false;
750
751 /* Refuse root name if only A and/or AAAA records are requested. */
752
753 DNS_QUESTION_FOREACH(t, question)
754 if (!IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_AAAA)) {
755 found = true;
756 break;
757 }
758
759 if (!found)
760 return DNS_SCOPE_NO;
761 }
762
763 /* Never route things to scopes that lack DNS servers */
764 if (!dns_scope_get_dns_server(s))
765 return DNS_SCOPE_NO;
766
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);
771
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)) {
776
777 if (!d->route_only && !dns_name_is_root(d->name))
778 has_search_domains = true;
779
780 if (dns_name_endswith(route_domain, d->name) > 0) {
781 int c;
782
783 c = dns_name_count_labels(d->name);
784 if (c < 0)
785 continue;
786
787 if (c > n_best)
788 n_best = c;
789 }
790 }
791
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;
797
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;
803
804 /* Let's return the number of labels in the best matching result */
805 if (n_best >= 0) {
806 assert(n_best <= DNS_SCOPE_YES_END - DNS_SCOPE_YES_BASE);
807 return DNS_SCOPE_YES_BASE + n_best;
808 }
809
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)
816 return DNS_SCOPE_NO;
817
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);
822 if (m >= 0)
823 return m;
824
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))
827 return DNS_SCOPE_NO;
828
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;
832
833 return DNS_SCOPE_MAYBE;
834 }
835
836 case DNS_PROTOCOL_MDNS: {
837 DnsScopeMatch m;
838
839 m = match_link_local_reverse_lookups(domain);
840 if (m >= 0)
841 return m;
842
843 m = match_subnet_reverse_lookups(s, domain, true);
844 if (m >= 0)
845 return m;
846
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;
850
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 */
855
856 return DNS_SCOPE_NO;
857 }
858
859 case DNS_PROTOCOL_LLMNR: {
860 DnsScopeMatch m;
861
862 m = match_link_local_reverse_lookups(domain);
863 if (m >= 0)
864 return m;
865
866 m = match_subnet_reverse_lookups(s, domain, true);
867 if (m >= 0)
868 return m;
869
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;
873
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
886 * above). */
887
888 return DNS_SCOPE_NO;
889 }
890
891 default:
892 assert_not_reached();
893 }
894 }
895
896 bool dns_scope_good_key(DnsScope *s, const DnsResourceKey *key) {
897 int key_family;
898
899 assert(s);
900 assert(key);
901
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. */
904
905 if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
906 return false;
907
908 if (s->protocol == DNS_PROTOCOL_DNS) {
909
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))
913 return true;
914
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);
919
920 if (!s->manager->resolve_unicast_single_label &&
921 dns_name_is_single_label(name))
922 return false;
923
924 return !dns_name_is_root(name);
925 }
926
927 /* Never route DNSSEC RR queries to LLMNR/mDNS scopes */
928 if (dns_type_is_dnssec(key->type))
929 return false;
930
931 /* On mDNS and LLMNR, send A and AAAA queries only on the respective scopes */
932
933 key_family = dns_type_to_af(key->type);
934 if (key_family < 0)
935 return true;
936
937 return key_family == s->family;
938 }
939
940 static int dns_scope_multicast_membership(DnsScope *s, bool b, struct in_addr in, struct in6_addr in6) {
941 int fd;
942
943 assert(s);
944 assert(s->link);
945
946 if (s->family == AF_INET) {
947 struct ip_mreqn mreqn = {
948 .imr_multiaddr = in,
949 .imr_ifindex = s->link->ifindex,
950 };
951
952 if (s->protocol == DNS_PROTOCOL_LLMNR)
953 fd = manager_llmnr_ipv4_udp_fd(s->manager);
954 else
955 fd = manager_mdns_ipv4_fd(s->manager);
956
957 if (fd < 0)
958 return fd;
959
960 /* Always first try to drop membership before we add
961 * one. This is necessary on some devices, such as
962 * veth. */
963 if (b)
964 (void) setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn));
965
966 if (setsockopt(fd, IPPROTO_IP, b ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0)
967 return -errno;
968
969 } else if (s->family == AF_INET6) {
970 struct ipv6_mreq mreq = {
971 .ipv6mr_multiaddr = in6,
972 .ipv6mr_ifindex = s->link->ifindex,
973 };
974
975 if (s->protocol == DNS_PROTOCOL_LLMNR)
976 fd = manager_llmnr_ipv6_udp_fd(s->manager);
977 else
978 fd = manager_mdns_ipv6_fd(s->manager);
979
980 if (fd < 0)
981 return fd;
982
983 if (b)
984 (void) setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
985
986 if (setsockopt(fd, IPPROTO_IPV6, b ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
987 return -errno;
988 } else
989 return -EAFNOSUPPORT;
990
991 return 0;
992 }
993
994 int dns_scope_llmnr_membership(DnsScope *s, bool b) {
995 assert(s);
996
997 if (s->protocol != DNS_PROTOCOL_LLMNR)
998 return 0;
999
1000 return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
1001 }
1002
1003 int dns_scope_mdns_membership(DnsScope *s, bool b) {
1004 assert(s);
1005
1006 if (s->protocol != DNS_PROTOCOL_MDNS)
1007 return 0;
1008
1009 return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
1010 }
1011
1012 int dns_scope_make_reply_packet(
1013 DnsScope *s,
1014 uint16_t id,
1015 int rcode,
1016 DnsQuestion *q,
1017 DnsAnswer *answer,
1018 DnsAnswer *soa,
1019 bool tentative,
1020 DnsPacket **ret) {
1021
1022 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1023 unsigned n_answer = 0, n_soa = 0;
1024 int r;
1025 bool c_or_aa;
1026
1027 assert(s);
1028 assert(ret);
1029
1030 if (dns_question_isempty(q) &&
1031 dns_answer_isempty(answer) &&
1032 dns_answer_isempty(soa))
1033 return -EINVAL;
1034
1035 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1036 if (r < 0)
1037 return r;
1038
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;
1041
1042 DNS_PACKET_HEADER(p)->id = id;
1043 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1044 1 /* qr */,
1045 0 /* opcode */,
1046 c_or_aa,
1047 0 /* tc */,
1048 tentative,
1049 0 /* (ra) */,
1050 0 /* (ad) */,
1051 0 /* (cd) */,
1052 rcode));
1053
1054 r = dns_packet_append_question(p, q);
1055 if (r < 0)
1056 return r;
1057 DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
1058
1059 r = dns_packet_append_answer(p, answer, &n_answer);
1060 if (r < 0)
1061 return r;
1062 DNS_PACKET_HEADER(p)->ancount = htobe16(n_answer);
1063
1064 r = dns_packet_append_answer(p, soa, &n_soa);
1065 if (r < 0)
1066 return r;
1067 DNS_PACKET_HEADER(p)->arcount = htobe16(n_soa);
1068
1069 *ret = TAKE_PTR(p);
1070
1071 return 0;
1072 }
1073
1074 static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
1075 DnsResourceRecord *rr;
1076 DnsResourceKey *key;
1077
1078 assert(s);
1079 assert(p);
1080
1081 DNS_QUESTION_FOREACH(key, p->question)
1082 dns_zone_verify_conflicts(&s->zone, key);
1083
1084 DNS_ANSWER_FOREACH(rr, p->answer)
1085 dns_zone_verify_conflicts(&s->zone, rr->key);
1086 }
1087
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;
1093 int r;
1094
1095 assert(s);
1096 assert(p);
1097
1098 if (p->protocol != DNS_PROTOCOL_LLMNR)
1099 return;
1100
1101 if (p->ipproto == IPPROTO_UDP) {
1102 /* Don't accept UDP queries directed to anything but
1103 * the LLMNR multicast addresses. See RFC 4795,
1104 * section 2.5. */
1105
1106 if (p->family == AF_INET && !in4_addr_equal(&p->destination.in, &LLMNR_MULTICAST_IPV4_ADDRESS))
1107 return;
1108
1109 if (p->family == AF_INET6 && !in6_addr_equal(&p->destination.in6, &LLMNR_MULTICAST_IPV6_ADDRESS))
1110 return;
1111 }
1112
1113 r = dns_packet_extract(p);
1114 if (r < 0) {
1115 log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
1116 return;
1117 }
1118
1119 if (DNS_PACKET_LLMNR_C(p)) {
1120 /* Somebody notified us about a possible conflict */
1121 dns_scope_verify_conflicts(s, p);
1122 return;
1123 }
1124
1125 if (dns_question_size(p->question) != 1)
1126 return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
1127
1128 key = dns_question_first_key(p->question);
1129
1130 r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
1131 if (r < 0) {
1132 log_debug_errno(r, "Failed to look up key: %m");
1133 return;
1134 }
1135 if (r == 0)
1136 return;
1137
1138 if (answer)
1139 dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
1140
1141 r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
1142 if (r < 0) {
1143 log_debug_errno(r, "Failed to build reply packet: %m");
1144 return;
1145 }
1146
1147 if (stream) {
1148 r = dns_stream_write_packet(stream, reply);
1149 if (r < 0) {
1150 log_debug_errno(r, "Failed to enqueue reply packet: %m");
1151 return;
1152 }
1153
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);
1159 } else {
1160 int fd;
1161
1162 if (!ratelimit_below(&s->ratelimit))
1163 return;
1164
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);
1169 else {
1170 log_debug("Unknown protocol");
1171 return;
1172 }
1173 if (fd < 0) {
1174 log_debug_errno(fd, "Failed to get reply socket: %m");
1175 return;
1176 }
1177
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 */
1182
1183 r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
1184 if (r < 0) {
1185 log_debug_errno(r, "Failed to send reply packet: %m");
1186 return;
1187 }
1188 }
1189 }
1190
1191 DnsTransaction *dns_scope_find_transaction(
1192 DnsScope *scope,
1193 DnsResourceKey *key,
1194 uint64_t query_flags) {
1195
1196 DnsTransaction *first;
1197
1198 assert(scope);
1199 assert(key);
1200
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) {
1204
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)
1213 continue;
1214
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))
1218 continue;
1219
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))
1223 continue;
1224
1225 /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
1226 * reuse */
1227 if ((query_flags & SD_RESOLVED_CLAMP_TTL) &&
1228 !(t->query_flags & SD_RESOLVED_CLAMP_TTL))
1229 continue;
1230
1231 return t;
1232 }
1233
1234 return NULL;
1235 }
1236
1237 static int dns_scope_make_conflict_packet(
1238 DnsScope *s,
1239 DnsResourceRecord *rr,
1240 DnsPacket **ret) {
1241
1242 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1243 int r;
1244
1245 assert(s);
1246 assert(rr);
1247 assert(ret);
1248
1249 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1250 if (r < 0)
1251 return r;
1252
1253 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1254 0 /* qr */,
1255 0 /* opcode */,
1256 1 /* conflict */,
1257 0 /* tc */,
1258 0 /* t */,
1259 0 /* (ra) */,
1260 0 /* (ad) */,
1261 0 /* (cd) */,
1262 0));
1263
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));
1267
1268 DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
1269 DNS_PACKET_HEADER(p)->arcount = htobe16(1);
1270
1271 r = dns_packet_append_key(p, rr->key, 0, NULL);
1272 if (r < 0)
1273 return r;
1274
1275 r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
1276 if (r < 0)
1277 return r;
1278
1279 *ret = TAKE_PTR(p);
1280
1281 return 0;
1282 }
1283
1284 static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
1285 DnsScope *scope = ASSERT_PTR(userdata);
1286 int r;
1287
1288 assert(es);
1289
1290 scope->conflict_event_source = sd_event_source_disable_unref(scope->conflict_event_source);
1291
1292 for (;;) {
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;
1296
1297 rr = ordered_hashmap_steal_first_key_and_value(scope->conflict_queue, (void**) &key);
1298 if (!rr)
1299 break;
1300
1301 r = dns_scope_make_conflict_packet(scope, rr, &p);
1302 if (r < 0) {
1303 log_error_errno(r, "Failed to make conflict packet: %m");
1304 return 0;
1305 }
1306
1307 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1308 if (r < 0)
1309 log_debug_errno(r, "Failed to send conflict packet: %m");
1310 }
1311
1312 return 0;
1313 }
1314
1315 int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
1316 int r;
1317
1318 assert(scope);
1319 assert(rr);
1320
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))
1326 return 0;
1327 if (r < 0)
1328 return log_debug_errno(r, "Failed to queue conflicting RR: %m");
1329
1330 dns_resource_key_ref(rr->key);
1331 dns_resource_record_ref(rr);
1332
1333 if (scope->conflict_event_source)
1334 return 0;
1335
1336 r = sd_event_add_time_relative(
1337 scope->manager->event,
1338 &scope->conflict_event_source,
1339 CLOCK_BOOTTIME,
1340 random_u64_range(LLMNR_JITTER_INTERVAL_USEC),
1341 0,
1342 on_conflict_dispatch, scope);
1343 if (r < 0)
1344 return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
1345
1346 (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
1347
1348 return 0;
1349 }
1350
1351 void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
1352 DnsResourceRecord *rr;
1353 int r;
1354
1355 assert(scope);
1356 assert(p);
1357
1358 if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
1359 return;
1360
1361 if (DNS_PACKET_RRCOUNT(p) <= 0)
1362 return;
1363
1364 if (p->protocol == DNS_PROTOCOL_LLMNR) {
1365 if (DNS_PACKET_LLMNR_C(p) != 0)
1366 return;
1367
1368 if (DNS_PACKET_LLMNR_T(p) != 0)
1369 return;
1370 }
1371
1372 if (manager_packet_from_local_address(scope->manager, p))
1373 return;
1374
1375 r = dns_packet_extract(p);
1376 if (r < 0) {
1377 log_debug_errno(r, "Failed to extract packet: %m");
1378 return;
1379 }
1380
1381 log_debug("Checking for conflicts...");
1382
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))
1386 continue;
1387
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);
1391 if (r != 0)
1392 continue;
1393
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);
1397 if (r <= 0)
1398 continue;
1399
1400 dns_scope_notify_conflict(scope, rr);
1401 }
1402 }
1403
1404 void dns_scope_dump(DnsScope *s, FILE *f) {
1405 assert(s);
1406
1407 if (!f)
1408 f = stdout;
1409
1410 fputs("[Scope protocol=", f);
1411 fputs(dns_protocol_to_string(s->protocol), f);
1412
1413 if (s->link) {
1414 fputs(" interface=", f);
1415 fputs(s->link->ifname, f);
1416 }
1417
1418 if (s->family != AF_UNSPEC) {
1419 fputs(" family=", f);
1420 fputs(af_to_name(s->family), f);
1421 }
1422
1423 fputs(" origin=", f);
1424 fputs(dns_scope_origin_to_string(s->origin), f);
1425
1426 if (s->delegate) {
1427 fputs(" id=", f);
1428 fputs(s->delegate->id, f);
1429 }
1430
1431 fputs("]\n", f);
1432
1433 if (!dns_zone_is_empty(&s->zone)) {
1434 fputs("ZONE:\n", f);
1435 dns_zone_dump(&s->zone, f);
1436 }
1437
1438 if (!dns_cache_is_empty(&s->cache)) {
1439 fputs("CACHE:\n", f);
1440 dns_cache_dump(&s->cache, f);
1441 }
1442 }
1443
1444 DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
1445 assert(s);
1446
1447 if (s->protocol != DNS_PROTOCOL_DNS)
1448 return NULL;
1449
1450 if (s->link)
1451 return s->link->search_domains;
1452 if (s->delegate)
1453 return s->delegate->search_domains;
1454
1455 return s->manager->search_domains;
1456 }
1457
1458 bool dns_scope_name_wants_search_domain(DnsScope *s, const char *name) {
1459 assert(s);
1460
1461 if (s->protocol != DNS_PROTOCOL_DNS)
1462 return false;
1463
1464 if (!dns_name_is_single_label(name))
1465 return false;
1466
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)
1472 return false;
1473
1474 return true;
1475 }
1476
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.
1481 *
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
1484 * family. */
1485
1486 if (s->link)
1487 return true;
1488
1489 return manager_routable(s->manager);
1490 }
1491
1492 int dns_scope_ifindex(DnsScope *s) {
1493 assert(s);
1494
1495 if (s->link)
1496 return s->link->ifindex;
1497
1498 return 0;
1499 }
1500
1501 const char* dns_scope_ifname(DnsScope *s) {
1502 assert(s);
1503
1504 if (s->link)
1505 return s->link->ifname;
1506
1507 return NULL;
1508 }
1509
1510 static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1511 DnsScope *scope = userdata;
1512
1513 assert(s);
1514
1515 scope->announce_event_source = sd_event_source_disable_unref(scope->announce_event_source);
1516
1517 (void) dns_scope_announce(scope, false);
1518 return 0;
1519 }
1520
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;
1525 DnsZoneItem *z;
1526 unsigned size = 0;
1527 char *service_type;
1528 int r;
1529
1530 if (!scope)
1531 return 0;
1532
1533 if (scope->protocol != DNS_PROTOCOL_MDNS)
1534 return 0;
1535
1536 r = sd_event_get_state(scope->manager->event);
1537 if (r < 0)
1538 return log_debug_errno(r, "Failed to get event loop state: %m");
1539
1540 /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
1541 if (r == SD_EVENT_FINISHED)
1542 return 0;
1543
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))
1547 return 0;
1548
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 */
1552
1553 /* Calculate answer's size. */
1554 HASHMAP_FOREACH(z, scope->zone.by_key) {
1555 if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
1556 continue;
1557
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];
1561
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;
1564 continue;
1565 }
1566
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));
1573 if (r < 0)
1574 return log_debug_errno(r, "Failed to add item to set: %m");
1575 }
1576 }
1577
1578 LIST_FOREACH(by_key, i, z)
1579 size++;
1580 }
1581
1582 answer = dns_answer_new(size + set_size(types));
1583 if (!answer)
1584 return log_oom();
1585
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;
1590
1591 if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
1592 continue;
1593
1594 if (dns_resource_key_is_dnssd_ptr(i->rr->key))
1595 flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
1596 else
1597 flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
1598
1599 r = dns_answer_add(answer, i->rr, 0, flags, NULL);
1600 if (r < 0)
1601 return log_debug_errno(r, "Failed to add RR to announce: %m");
1602 }
1603
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;
1607
1608 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
1609 "_services._dns-sd._udp.local");
1610 if (!rr)
1611 return log_oom();
1612
1613 rr->ptr.name = strdup(service_type);
1614 if (!rr->ptr.name)
1615 return log_oom();
1616
1617 rr->ttl = MDNS_DEFAULT_TTL;
1618
1619 r = dns_zone_put(&scope->zone, scope, rr, false);
1620 if (r < 0)
1621 log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
1622
1623 r = dns_answer_add(answer, rr, 0, 0, NULL);
1624 if (r < 0)
1625 return log_debug_errno(r, "Failed to add RR to announce: %m");
1626 }
1627
1628 if (dns_answer_isempty(answer))
1629 return 0;
1630
1631 r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
1632 if (r < 0)
1633 return log_debug_errno(r, "Failed to build reply packet: %m");
1634
1635 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1636 if (r < 0)
1637 return log_debug_errno(r, "Failed to send reply packet: %m");
1638
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;
1643
1644 r = sd_event_add_time_relative(
1645 scope->manager->event,
1646 &scope->announce_event_source,
1647 CLOCK_BOOTTIME,
1648 MDNS_ANNOUNCE_DELAY,
1649 0,
1650 on_announcement_timeout, scope);
1651 if (r < 0)
1652 return log_debug_errno(r, "Failed to schedule second announcement: %m");
1653
1654 (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
1655 }
1656
1657 return 0;
1658 }
1659
1660 int dns_scope_add_dnssd_services(DnsScope *scope) {
1661 DnssdService *service;
1662 int r;
1663
1664 assert(scope);
1665
1666 if (hashmap_isempty(scope->manager->dnssd_services))
1667 return 0;
1668
1669 scope->announced = false;
1670
1671 HASHMAP_FOREACH(service, scope->manager->dnssd_services) {
1672 service->withdrawn = false;
1673
1674 r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
1675 if (r < 0)
1676 log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
1677
1678 if (service->sub_ptr_rr) {
1679 r = dns_zone_put(&scope->zone, scope, service->sub_ptr_rr, false);
1680 if (r < 0)
1681 log_warning_errno(r, "Failed to add selective PTR record to MDNS zone: %m");
1682 }
1683
1684 r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
1685 if (r < 0)
1686 log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
1687
1688 LIST_FOREACH(items, txt_data, service->txt_data_items) {
1689 r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
1690 if (r < 0)
1691 log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
1692 }
1693 }
1694
1695 return 0;
1696 }
1697
1698 int dns_scope_remove_dnssd_services(DnsScope *scope) {
1699 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1700 DnssdService *service;
1701 int r;
1702
1703 assert(scope);
1704
1705 key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
1706 "_services._dns-sd._udp.local");
1707 if (!key)
1708 return log_oom();
1709
1710 r = dns_zone_remove_rrs_by_key(&scope->zone, key);
1711 if (r < 0)
1712 return r;
1713
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);
1720 }
1721
1722 return 0;
1723 }
1724
1725 static bool dns_scope_has_route_only_domains(DnsScope *scope) {
1726 DnsSearchDomain *first;
1727 bool route_only = false;
1728
1729 assert(scope);
1730 assert(scope->protocol == DNS_PROTOCOL_DNS);
1731
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. */
1736
1737 if (scope->link)
1738 first = scope->link->search_domains;
1739 else if (scope->delegate)
1740 first = scope->delegate->search_domains;
1741 else
1742 first = scope->manager->search_domains;
1743
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)))
1750 return false;
1751
1752 if (domain->route_only)
1753 route_only = true;
1754 }
1755
1756 return route_only;
1757 }
1758
1759 bool dns_scope_is_default_route(DnsScope *scope) {
1760 assert(scope);
1761
1762 /* Only use DNS scopes as default routes */
1763 if (scope->protocol != DNS_PROTOCOL_DNS)
1764 return false;
1765
1766 if (scope->link) {
1767
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;
1772
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);
1776
1777 } else if (scope->delegate) {
1778
1779 if (scope->delegate->default_route >= 0)
1780 return scope->delegate->default_route;
1781
1782 /* Delegates are by default not used as default route */
1783 return false;
1784 } else
1785 /* The global DNS scope is always suitable as default route */
1786 return true;
1787 }
1788
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;
1791 int r;
1792
1793 assert(scope);
1794 assert(ret);
1795
1796 r = dns_cache_dump_to_json(&scope->cache, &cache);
1797 if (r < 0)
1798 return r;
1799
1800 return sd_json_buildo(
1801 ret,
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));
1807 }
1808
1809 int dns_type_suitable_for_protocol(uint16_t type, DnsProtocol protocol) {
1810
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
1816 * no sense. */
1817
1818 if (dns_type_is_obsolete(type))
1819 return false;
1820
1821 if (!dns_type_is_valid_query(type))
1822 return false;
1823
1824 switch (protocol) {
1825
1826 case DNS_PROTOCOL_DNS:
1827 return true;
1828
1829 case DNS_PROTOCOL_LLMNR:
1830 return IN_SET(type,
1831 DNS_TYPE_ANY,
1832 DNS_TYPE_A,
1833 DNS_TYPE_AAAA,
1834 DNS_TYPE_CNAME,
1835 DNS_TYPE_PTR,
1836 DNS_TYPE_TXT);
1837
1838 case DNS_PROTOCOL_MDNS:
1839 return IN_SET(type,
1840 DNS_TYPE_ANY,
1841 DNS_TYPE_A,
1842 DNS_TYPE_AAAA,
1843 DNS_TYPE_CNAME,
1844 DNS_TYPE_PTR,
1845 DNS_TYPE_TXT,
1846 DNS_TYPE_SRV,
1847 DNS_TYPE_NSEC,
1848 DNS_TYPE_HINFO);
1849
1850 default:
1851 return -EPROTONOSUPPORT;
1852 }
1853 }
1854
1855 int dns_question_types_suitable_for_protocol(DnsQuestion *q, DnsProtocol protocol) {
1856 DnsResourceKey *key;
1857 int r;
1858
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 */
1861
1862 DNS_QUESTION_FOREACH(key, q) {
1863 r = dns_type_suitable_for_protocol(key->type, protocol);
1864 if (r != 0)
1865 return r;
1866 }
1867
1868 return false;
1869 }
1870
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",
1875 };
1876
1877 DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin, DnsScopeOrigin);