]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/resolve/resolved-dns-scope.c
io.systemd.Unit.List fix context/runtime split (#38172)
[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 /* Always honour search domains for routing queries, except if this scope lacks DNS servers. Note that
768 * we return DNS_SCOPE_YES here, rather than just DNS_SCOPE_MAYBE, which means other wildcard scopes
769 * won't be considered anymore. */
770 LIST_FOREACH(domains, d, dns_scope_get_search_domains(s)) {
771
772 if (!d->route_only && !dns_name_is_root(d->name))
773 has_search_domains = true;
774
775 if (dns_name_endswith(domain, d->name) > 0) {
776 int c;
777
778 c = dns_name_count_labels(d->name);
779 if (c < 0)
780 continue;
781
782 if (c > n_best)
783 n_best = c;
784 }
785 }
786
787 /* If there's a true search domain defined for this scope, and the query is single-label,
788 * then let's resolve things here, preferably. Note that LLMNR considers itself
789 * authoritative for single-label names too, at the same preference, see below. */
790 if (has_search_domains && dns_name_is_single_label(domain))
791 return DNS_SCOPE_YES_BASE + 1;
792
793 /* If ResolveUnicastSingleLabel=yes and the query is single-label, then bump match result
794 to prevent LLMNR monopoly among candidates. */
795 if ((s->manager->resolve_unicast_single_label || (query_flags & SD_RESOLVED_RELAX_SINGLE_LABEL)) &&
796 dns_name_is_single_label(domain))
797 return DNS_SCOPE_YES_BASE + 1;
798
799 /* Let's return the number of labels in the best matching result */
800 if (n_best >= 0) {
801 assert(n_best <= DNS_SCOPE_YES_END - DNS_SCOPE_YES_BASE);
802 return DNS_SCOPE_YES_BASE + n_best;
803 }
804
805 /* Exclude link-local IP ranges */
806 if (match_link_local_reverse_lookups(domain) >= DNS_SCOPE_YES_BASE ||
807 /* If networks use .local in their private setups, they are supposed to also add .local
808 * to their search domains, which we already checked above. Otherwise, we consider .local
809 * specific to mDNS and won't send such queries ordinary DNS servers. */
810 dns_name_endswith(domain, "local") > 0)
811 return DNS_SCOPE_NO;
812
813 /* If the IP address to look up matches the local subnet, then implicitly synthesizes
814 * DNS_SCOPE_YES_BASE + 0 on this interface, i.e. preferably resolve IP addresses via the DNS
815 * server belonging to this interface. */
816 m = match_subnet_reverse_lookups(s, domain, false);
817 if (m >= 0)
818 return m;
819
820 /* If there was no match at all, then see if this scope is suitable as default route. */
821 if (!dns_scope_is_default_route(s))
822 return DNS_SCOPE_NO;
823
824 /* Prefer suitable per-link scopes where possible */
825 if (dns_server_is_fallback(dns_scope_get_dns_server(s)))
826 return DNS_SCOPE_LAST_RESORT;
827
828 return DNS_SCOPE_MAYBE;
829 }
830
831 case DNS_PROTOCOL_MDNS: {
832 DnsScopeMatch m;
833
834 m = match_link_local_reverse_lookups(domain);
835 if (m >= 0)
836 return m;
837
838 m = match_subnet_reverse_lookups(s, domain, true);
839 if (m >= 0)
840 return m;
841
842 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
843 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
844 return DNS_SCOPE_LAST_RESORT;
845
846 if ((dns_name_endswith(domain, "local") > 0 && /* only resolve names ending in .local via mDNS */
847 dns_name_equal(domain, "local") == 0 && /* but not the single-label "local" name itself */
848 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via mDNS */
849 return DNS_SCOPE_YES_BASE + 1; /* Return +1, as the top-level .local domain matches, i.e. one label */
850
851 return DNS_SCOPE_NO;
852 }
853
854 case DNS_PROTOCOL_LLMNR: {
855 DnsScopeMatch m;
856
857 m = match_link_local_reverse_lookups(domain);
858 if (m >= 0)
859 return m;
860
861 m = match_subnet_reverse_lookups(s, domain, true);
862 if (m >= 0)
863 return m;
864
865 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
866 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
867 return DNS_SCOPE_LAST_RESORT;
868
869 if ((dns_name_is_single_label(domain) && /* only resolve single label names via LLMNR */
870 dns_name_equal(domain, "local") == 0 && /* don't resolve "local" with LLMNR, it's the top-level domain of mDNS after all, see above */
871 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via LLMNR */
872 return DNS_SCOPE_YES_BASE + 1; /* Return +1, as we consider ourselves authoritative
873 * for single-label names, i.e. one label. This is
874 * particularly relevant as it means a "." route on some
875 * other scope won't pull all traffic away from
876 * us. (If people actually want to pull traffic away
877 * from us they should turn off LLMNR on the
878 * link). Note that unicast DNS scopes with search
879 * domains also consider themselves authoritative for
880 * single-label domains, at the same preference (see
881 * above). */
882
883 return DNS_SCOPE_NO;
884 }
885
886 default:
887 assert_not_reached();
888 }
889 }
890
891 bool dns_scope_good_key(DnsScope *s, const DnsResourceKey *key) {
892 int key_family;
893
894 assert(s);
895 assert(key);
896
897 /* Check if it makes sense to resolve the specified key on this scope. Note that this call assumes a
898 * fully qualified name, i.e. the search suffixes already appended. */
899
900 if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
901 return false;
902
903 if (s->protocol == DNS_PROTOCOL_DNS) {
904
905 /* On classic DNS, looking up non-address RRs is always fine. (Specifically, we want to
906 * permit looking up DNSKEY and DS records on the root and top-level domains.) */
907 if (!dns_resource_key_is_address(key))
908 return true;
909
910 /* Unless explicitly overridden, we refuse to look up A and AAAA RRs on the root and
911 * single-label domains, under the assumption that those should be resolved via LLMNR or
912 * search path only, and should not be leaked onto the internet. */
913 const char* name = dns_resource_key_name(key);
914
915 if (!s->manager->resolve_unicast_single_label &&
916 dns_name_is_single_label(name))
917 return false;
918
919 return !dns_name_is_root(name);
920 }
921
922 /* Never route DNSSEC RR queries to LLMNR/mDNS scopes */
923 if (dns_type_is_dnssec(key->type))
924 return false;
925
926 /* On mDNS and LLMNR, send A and AAAA queries only on the respective scopes */
927
928 key_family = dns_type_to_af(key->type);
929 if (key_family < 0)
930 return true;
931
932 return key_family == s->family;
933 }
934
935 static int dns_scope_multicast_membership(DnsScope *s, bool b, struct in_addr in, struct in6_addr in6) {
936 int fd;
937
938 assert(s);
939 assert(s->link);
940
941 if (s->family == AF_INET) {
942 struct ip_mreqn mreqn = {
943 .imr_multiaddr = in,
944 .imr_ifindex = s->link->ifindex,
945 };
946
947 if (s->protocol == DNS_PROTOCOL_LLMNR)
948 fd = manager_llmnr_ipv4_udp_fd(s->manager);
949 else
950 fd = manager_mdns_ipv4_fd(s->manager);
951
952 if (fd < 0)
953 return fd;
954
955 /* Always first try to drop membership before we add
956 * one. This is necessary on some devices, such as
957 * veth. */
958 if (b)
959 (void) setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn));
960
961 if (setsockopt(fd, IPPROTO_IP, b ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0)
962 return -errno;
963
964 } else if (s->family == AF_INET6) {
965 struct ipv6_mreq mreq = {
966 .ipv6mr_multiaddr = in6,
967 .ipv6mr_ifindex = s->link->ifindex,
968 };
969
970 if (s->protocol == DNS_PROTOCOL_LLMNR)
971 fd = manager_llmnr_ipv6_udp_fd(s->manager);
972 else
973 fd = manager_mdns_ipv6_fd(s->manager);
974
975 if (fd < 0)
976 return fd;
977
978 if (b)
979 (void) setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
980
981 if (setsockopt(fd, IPPROTO_IPV6, b ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
982 return -errno;
983 } else
984 return -EAFNOSUPPORT;
985
986 return 0;
987 }
988
989 int dns_scope_llmnr_membership(DnsScope *s, bool b) {
990 assert(s);
991
992 if (s->protocol != DNS_PROTOCOL_LLMNR)
993 return 0;
994
995 return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
996 }
997
998 int dns_scope_mdns_membership(DnsScope *s, bool b) {
999 assert(s);
1000
1001 if (s->protocol != DNS_PROTOCOL_MDNS)
1002 return 0;
1003
1004 return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
1005 }
1006
1007 int dns_scope_make_reply_packet(
1008 DnsScope *s,
1009 uint16_t id,
1010 int rcode,
1011 DnsQuestion *q,
1012 DnsAnswer *answer,
1013 DnsAnswer *soa,
1014 bool tentative,
1015 DnsPacket **ret) {
1016
1017 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1018 unsigned n_answer = 0, n_soa = 0;
1019 int r;
1020 bool c_or_aa;
1021
1022 assert(s);
1023 assert(ret);
1024
1025 if (dns_question_isempty(q) &&
1026 dns_answer_isempty(answer) &&
1027 dns_answer_isempty(soa))
1028 return -EINVAL;
1029
1030 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1031 if (r < 0)
1032 return r;
1033
1034 /* mDNS answers must have the Authoritative Answer bit set, see RFC 6762, section 18.4. */
1035 c_or_aa = s->protocol == DNS_PROTOCOL_MDNS;
1036
1037 DNS_PACKET_HEADER(p)->id = id;
1038 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1039 1 /* qr */,
1040 0 /* opcode */,
1041 c_or_aa,
1042 0 /* tc */,
1043 tentative,
1044 0 /* (ra) */,
1045 0 /* (ad) */,
1046 0 /* (cd) */,
1047 rcode));
1048
1049 r = dns_packet_append_question(p, q);
1050 if (r < 0)
1051 return r;
1052 DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
1053
1054 r = dns_packet_append_answer(p, answer, &n_answer);
1055 if (r < 0)
1056 return r;
1057 DNS_PACKET_HEADER(p)->ancount = htobe16(n_answer);
1058
1059 r = dns_packet_append_answer(p, soa, &n_soa);
1060 if (r < 0)
1061 return r;
1062 DNS_PACKET_HEADER(p)->arcount = htobe16(n_soa);
1063
1064 *ret = TAKE_PTR(p);
1065
1066 return 0;
1067 }
1068
1069 static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
1070 DnsResourceRecord *rr;
1071 DnsResourceKey *key;
1072
1073 assert(s);
1074 assert(p);
1075
1076 DNS_QUESTION_FOREACH(key, p->question)
1077 dns_zone_verify_conflicts(&s->zone, key);
1078
1079 DNS_ANSWER_FOREACH(rr, p->answer)
1080 dns_zone_verify_conflicts(&s->zone, rr->key);
1081 }
1082
1083 void dns_scope_process_query(DnsScope *s, DnsStream *stream, DnsPacket *p) {
1084 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL, *soa = NULL;
1085 _cleanup_(dns_packet_unrefp) DnsPacket *reply = NULL;
1086 DnsResourceKey *key = NULL;
1087 bool tentative = false;
1088 int r;
1089
1090 assert(s);
1091 assert(p);
1092
1093 if (p->protocol != DNS_PROTOCOL_LLMNR)
1094 return;
1095
1096 if (p->ipproto == IPPROTO_UDP) {
1097 /* Don't accept UDP queries directed to anything but
1098 * the LLMNR multicast addresses. See RFC 4795,
1099 * section 2.5. */
1100
1101 if (p->family == AF_INET && !in4_addr_equal(&p->destination.in, &LLMNR_MULTICAST_IPV4_ADDRESS))
1102 return;
1103
1104 if (p->family == AF_INET6 && !in6_addr_equal(&p->destination.in6, &LLMNR_MULTICAST_IPV6_ADDRESS))
1105 return;
1106 }
1107
1108 r = dns_packet_extract(p);
1109 if (r < 0) {
1110 log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
1111 return;
1112 }
1113
1114 if (DNS_PACKET_LLMNR_C(p)) {
1115 /* Somebody notified us about a possible conflict */
1116 dns_scope_verify_conflicts(s, p);
1117 return;
1118 }
1119
1120 if (dns_question_size(p->question) != 1)
1121 return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
1122
1123 key = dns_question_first_key(p->question);
1124
1125 r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
1126 if (r < 0) {
1127 log_debug_errno(r, "Failed to look up key: %m");
1128 return;
1129 }
1130 if (r == 0)
1131 return;
1132
1133 if (answer)
1134 dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
1135
1136 r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
1137 if (r < 0) {
1138 log_debug_errno(r, "Failed to build reply packet: %m");
1139 return;
1140 }
1141
1142 if (stream) {
1143 r = dns_stream_write_packet(stream, reply);
1144 if (r < 0) {
1145 log_debug_errno(r, "Failed to enqueue reply packet: %m");
1146 return;
1147 }
1148
1149 /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
1150 * will be dangling until the stream is disconnected, and the default completion handler of the stream
1151 * will then unref the stream and destroy it */
1152 if (DNS_STREAM_QUEUED(stream))
1153 dns_stream_ref(stream);
1154 } else {
1155 int fd;
1156
1157 if (!ratelimit_below(&s->ratelimit))
1158 return;
1159
1160 if (p->family == AF_INET)
1161 fd = manager_llmnr_ipv4_udp_fd(s->manager);
1162 else if (p->family == AF_INET6)
1163 fd = manager_llmnr_ipv6_udp_fd(s->manager);
1164 else {
1165 log_debug("Unknown protocol");
1166 return;
1167 }
1168 if (fd < 0) {
1169 log_debug_errno(fd, "Failed to get reply socket: %m");
1170 return;
1171 }
1172
1173 /* Note that we always immediately reply to all LLMNR
1174 * requests, and do not wait any time, since we
1175 * verified uniqueness for all records. Also see RFC
1176 * 4795, Section 2.7 */
1177
1178 r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
1179 if (r < 0) {
1180 log_debug_errno(r, "Failed to send reply packet: %m");
1181 return;
1182 }
1183 }
1184 }
1185
1186 DnsTransaction *dns_scope_find_transaction(
1187 DnsScope *scope,
1188 DnsResourceKey *key,
1189 uint64_t query_flags) {
1190
1191 DnsTransaction *first;
1192
1193 assert(scope);
1194 assert(key);
1195
1196 /* Iterate through the list of transactions with a matching key */
1197 first = hashmap_get(scope->transactions_by_key, key);
1198 LIST_FOREACH(transactions_by_key, t, first) {
1199
1200 /* These four flags must match exactly: we cannot use a validated response for a
1201 * non-validating client, and we cannot use a non-validated response for a validating
1202 * client. Similar, if the sources don't match things aren't usable either. */
1203 if (((query_flags ^ t->query_flags) &
1204 (SD_RESOLVED_NO_VALIDATE|
1205 SD_RESOLVED_NO_ZONE|
1206 SD_RESOLVED_NO_TRUST_ANCHOR|
1207 SD_RESOLVED_NO_NETWORK)) != 0)
1208 continue;
1209
1210 /* We can reuse a primary query if a regular one is requested, but not vice versa */
1211 if ((query_flags & SD_RESOLVED_REQUIRE_PRIMARY) &&
1212 !(t->query_flags & SD_RESOLVED_REQUIRE_PRIMARY))
1213 continue;
1214
1215 /* Don't reuse a transaction that allowed caching when we got told not to use it */
1216 if ((query_flags & SD_RESOLVED_NO_CACHE) &&
1217 !(t->query_flags & SD_RESOLVED_NO_CACHE))
1218 continue;
1219
1220 /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
1221 * reuse */
1222 if ((query_flags & SD_RESOLVED_CLAMP_TTL) &&
1223 !(t->query_flags & SD_RESOLVED_CLAMP_TTL))
1224 continue;
1225
1226 return t;
1227 }
1228
1229 return NULL;
1230 }
1231
1232 static int dns_scope_make_conflict_packet(
1233 DnsScope *s,
1234 DnsResourceRecord *rr,
1235 DnsPacket **ret) {
1236
1237 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1238 int r;
1239
1240 assert(s);
1241 assert(rr);
1242 assert(ret);
1243
1244 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1245 if (r < 0)
1246 return r;
1247
1248 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1249 0 /* qr */,
1250 0 /* opcode */,
1251 1 /* conflict */,
1252 0 /* tc */,
1253 0 /* t */,
1254 0 /* (ra) */,
1255 0 /* (ad) */,
1256 0 /* (cd) */,
1257 0));
1258
1259 /* For mDNS, the transaction ID should always be 0 */
1260 if (s->protocol != DNS_PROTOCOL_MDNS)
1261 random_bytes(&DNS_PACKET_HEADER(p)->id, sizeof(uint16_t));
1262
1263 DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
1264 DNS_PACKET_HEADER(p)->arcount = htobe16(1);
1265
1266 r = dns_packet_append_key(p, rr->key, 0, NULL);
1267 if (r < 0)
1268 return r;
1269
1270 r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
1271 if (r < 0)
1272 return r;
1273
1274 *ret = TAKE_PTR(p);
1275
1276 return 0;
1277 }
1278
1279 static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
1280 DnsScope *scope = ASSERT_PTR(userdata);
1281 int r;
1282
1283 assert(es);
1284
1285 scope->conflict_event_source = sd_event_source_disable_unref(scope->conflict_event_source);
1286
1287 for (;;) {
1288 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1289 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1290 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1291
1292 rr = ordered_hashmap_steal_first_key_and_value(scope->conflict_queue, (void**) &key);
1293 if (!rr)
1294 break;
1295
1296 r = dns_scope_make_conflict_packet(scope, rr, &p);
1297 if (r < 0) {
1298 log_error_errno(r, "Failed to make conflict packet: %m");
1299 return 0;
1300 }
1301
1302 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1303 if (r < 0)
1304 log_debug_errno(r, "Failed to send conflict packet: %m");
1305 }
1306
1307 return 0;
1308 }
1309
1310 int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
1311 int r;
1312
1313 assert(scope);
1314 assert(rr);
1315
1316 /* We don't send these queries immediately. Instead, we queue them, and send them after some jitter
1317 * delay. We only place one RR per key in the conflict messages, not all of them. That should be
1318 * enough to indicate where there might be a conflict */
1319 r = ordered_hashmap_ensure_put(&scope->conflict_queue, &dns_resource_record_hash_ops_by_key, rr->key, rr);
1320 if (IN_SET(r, 0, -EEXIST))
1321 return 0;
1322 if (r < 0)
1323 return log_debug_errno(r, "Failed to queue conflicting RR: %m");
1324
1325 dns_resource_key_ref(rr->key);
1326 dns_resource_record_ref(rr);
1327
1328 if (scope->conflict_event_source)
1329 return 0;
1330
1331 r = sd_event_add_time_relative(
1332 scope->manager->event,
1333 &scope->conflict_event_source,
1334 CLOCK_BOOTTIME,
1335 random_u64_range(LLMNR_JITTER_INTERVAL_USEC),
1336 0,
1337 on_conflict_dispatch, scope);
1338 if (r < 0)
1339 return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
1340
1341 (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
1342
1343 return 0;
1344 }
1345
1346 void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
1347 DnsResourceRecord *rr;
1348 int r;
1349
1350 assert(scope);
1351 assert(p);
1352
1353 if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
1354 return;
1355
1356 if (DNS_PACKET_RRCOUNT(p) <= 0)
1357 return;
1358
1359 if (p->protocol == DNS_PROTOCOL_LLMNR) {
1360 if (DNS_PACKET_LLMNR_C(p) != 0)
1361 return;
1362
1363 if (DNS_PACKET_LLMNR_T(p) != 0)
1364 return;
1365 }
1366
1367 if (manager_packet_from_local_address(scope->manager, p))
1368 return;
1369
1370 r = dns_packet_extract(p);
1371 if (r < 0) {
1372 log_debug_errno(r, "Failed to extract packet: %m");
1373 return;
1374 }
1375
1376 log_debug("Checking for conflicts...");
1377
1378 DNS_ANSWER_FOREACH(rr, p->answer) {
1379 /* No conflict if it is DNS-SD RR used for service enumeration. */
1380 if (dns_resource_key_is_dnssd_ptr(rr->key))
1381 continue;
1382
1383 /* Check for conflicts against the local zone. If we
1384 * found one, we won't check any further */
1385 r = dns_zone_check_conflicts(&scope->zone, rr);
1386 if (r != 0)
1387 continue;
1388
1389 /* Check for conflicts against the local cache. If so,
1390 * send out an advisory query, to inform everybody */
1391 r = dns_cache_check_conflicts(&scope->cache, rr, p->family, &p->sender);
1392 if (r <= 0)
1393 continue;
1394
1395 dns_scope_notify_conflict(scope, rr);
1396 }
1397 }
1398
1399 void dns_scope_dump(DnsScope *s, FILE *f) {
1400 assert(s);
1401
1402 if (!f)
1403 f = stdout;
1404
1405 fputs("[Scope protocol=", f);
1406 fputs(dns_protocol_to_string(s->protocol), f);
1407
1408 if (s->link) {
1409 fputs(" interface=", f);
1410 fputs(s->link->ifname, f);
1411 }
1412
1413 if (s->family != AF_UNSPEC) {
1414 fputs(" family=", f);
1415 fputs(af_to_name(s->family), f);
1416 }
1417
1418 fputs(" origin=", f);
1419 fputs(dns_scope_origin_to_string(s->origin), f);
1420
1421 if (s->delegate) {
1422 fputs(" id=", f);
1423 fputs(s->delegate->id, f);
1424 }
1425
1426 fputs("]\n", f);
1427
1428 if (!dns_zone_is_empty(&s->zone)) {
1429 fputs("ZONE:\n", f);
1430 dns_zone_dump(&s->zone, f);
1431 }
1432
1433 if (!dns_cache_is_empty(&s->cache)) {
1434 fputs("CACHE:\n", f);
1435 dns_cache_dump(&s->cache, f);
1436 }
1437 }
1438
1439 DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
1440 assert(s);
1441
1442 if (s->protocol != DNS_PROTOCOL_DNS)
1443 return NULL;
1444
1445 if (s->link)
1446 return s->link->search_domains;
1447 if (s->delegate)
1448 return s->delegate->search_domains;
1449
1450 return s->manager->search_domains;
1451 }
1452
1453 bool dns_scope_name_wants_search_domain(DnsScope *s, const char *name) {
1454 assert(s);
1455
1456 if (s->protocol != DNS_PROTOCOL_DNS)
1457 return false;
1458
1459 if (!dns_name_is_single_label(name))
1460 return false;
1461
1462 /* If we allow single-label domain lookups on unicast DNS, and this scope has a search domain that matches
1463 * _exactly_ this name, then do not use search domains. */
1464 if (s->manager->resolve_unicast_single_label)
1465 LIST_FOREACH(domains, d, dns_scope_get_search_domains(s))
1466 if (dns_name_equal(name, d->name) > 0)
1467 return false;
1468
1469 return true;
1470 }
1471
1472 bool dns_scope_network_good(DnsScope *s) {
1473 /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
1474 * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
1475 * DNS scope we check whether there are any links that are up and have an address.
1476 *
1477 * Note that Linux routing is complex and even systems that superficially have no IPv4 address might
1478 * be able to route IPv4 (and similar for IPv6), hence let's make a check here independent of address
1479 * family. */
1480
1481 if (s->link)
1482 return true;
1483
1484 return manager_routable(s->manager);
1485 }
1486
1487 int dns_scope_ifindex(DnsScope *s) {
1488 assert(s);
1489
1490 if (s->link)
1491 return s->link->ifindex;
1492
1493 return 0;
1494 }
1495
1496 const char* dns_scope_ifname(DnsScope *s) {
1497 assert(s);
1498
1499 if (s->link)
1500 return s->link->ifname;
1501
1502 return NULL;
1503 }
1504
1505 static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1506 DnsScope *scope = userdata;
1507
1508 assert(s);
1509
1510 scope->announce_event_source = sd_event_source_disable_unref(scope->announce_event_source);
1511
1512 (void) dns_scope_announce(scope, false);
1513 return 0;
1514 }
1515
1516 int dns_scope_announce(DnsScope *scope, bool goodbye) {
1517 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
1518 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1519 _cleanup_set_free_ Set *types = NULL;
1520 DnsZoneItem *z;
1521 unsigned size = 0;
1522 char *service_type;
1523 int r;
1524
1525 if (!scope)
1526 return 0;
1527
1528 if (scope->protocol != DNS_PROTOCOL_MDNS)
1529 return 0;
1530
1531 r = sd_event_get_state(scope->manager->event);
1532 if (r < 0)
1533 return log_debug_errno(r, "Failed to get event loop state: %m");
1534
1535 /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
1536 if (r == SD_EVENT_FINISHED)
1537 return 0;
1538
1539 /* Check if we're done with probing. */
1540 LIST_FOREACH(transactions_by_scope, t, scope->transactions)
1541 if (t->probing && DNS_TRANSACTION_IS_LIVE(t->state))
1542 return 0;
1543
1544 /* Check if there're services pending conflict resolution. */
1545 if (manager_next_dnssd_names(scope->manager))
1546 return 0; /* we reach this point only if changing hostname didn't help */
1547
1548 /* Calculate answer's size. */
1549 HASHMAP_FOREACH(z, scope->zone.by_key) {
1550 if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
1551 continue;
1552
1553 if (z->rr->key->type == DNS_TYPE_PTR &&
1554 !dns_zone_contains_name(&scope->zone, z->rr->ptr.name)) {
1555 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1556
1557 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));
1558 z->state = DNS_ZONE_ITEM_WITHDRAWN;
1559 continue;
1560 }
1561
1562 /* Collect service types for _services._dns-sd._udp.local RRs in a set. Only two-label names
1563 * (not selective names) are considered according to RFC6763 § 9. */
1564 if (!scope->announced &&
1565 dns_resource_key_is_dnssd_two_label_ptr(z->rr->key)) {
1566 if (!set_contains(types, dns_resource_key_name(z->rr->key))) {
1567 r = set_ensure_put(&types, &dns_name_hash_ops, dns_resource_key_name(z->rr->key));
1568 if (r < 0)
1569 return log_debug_errno(r, "Failed to add item to set: %m");
1570 }
1571 }
1572
1573 LIST_FOREACH(by_key, i, z)
1574 size++;
1575 }
1576
1577 answer = dns_answer_new(size + set_size(types));
1578 if (!answer)
1579 return log_oom();
1580
1581 /* Second iteration, actually add RRs to the answer. */
1582 HASHMAP_FOREACH(z, scope->zone.by_key)
1583 LIST_FOREACH (by_key, i, z) {
1584 DnsAnswerFlags flags;
1585
1586 if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
1587 continue;
1588
1589 if (dns_resource_key_is_dnssd_ptr(i->rr->key))
1590 flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
1591 else
1592 flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
1593
1594 r = dns_answer_add(answer, i->rr, 0, flags, NULL);
1595 if (r < 0)
1596 return log_debug_errno(r, "Failed to add RR to announce: %m");
1597 }
1598
1599 /* Since all the active services are in the zone make them discoverable now. */
1600 SET_FOREACH(service_type, types) {
1601 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1602
1603 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
1604 "_services._dns-sd._udp.local");
1605 if (!rr)
1606 return log_oom();
1607
1608 rr->ptr.name = strdup(service_type);
1609 if (!rr->ptr.name)
1610 return log_oom();
1611
1612 rr->ttl = MDNS_DEFAULT_TTL;
1613
1614 r = dns_zone_put(&scope->zone, scope, rr, false);
1615 if (r < 0)
1616 log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
1617
1618 r = dns_answer_add(answer, rr, 0, 0, NULL);
1619 if (r < 0)
1620 return log_debug_errno(r, "Failed to add RR to announce: %m");
1621 }
1622
1623 if (dns_answer_isempty(answer))
1624 return 0;
1625
1626 r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
1627 if (r < 0)
1628 return log_debug_errno(r, "Failed to build reply packet: %m");
1629
1630 r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1631 if (r < 0)
1632 return log_debug_errno(r, "Failed to send reply packet: %m");
1633
1634 /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
1635 * responses, one second apart." */
1636 if (!scope->announced) {
1637 scope->announced = true;
1638
1639 r = sd_event_add_time_relative(
1640 scope->manager->event,
1641 &scope->announce_event_source,
1642 CLOCK_BOOTTIME,
1643 MDNS_ANNOUNCE_DELAY,
1644 0,
1645 on_announcement_timeout, scope);
1646 if (r < 0)
1647 return log_debug_errno(r, "Failed to schedule second announcement: %m");
1648
1649 (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
1650 }
1651
1652 return 0;
1653 }
1654
1655 int dns_scope_add_dnssd_services(DnsScope *scope) {
1656 DnssdService *service;
1657 int r;
1658
1659 assert(scope);
1660
1661 if (hashmap_isempty(scope->manager->dnssd_services))
1662 return 0;
1663
1664 scope->announced = false;
1665
1666 HASHMAP_FOREACH(service, scope->manager->dnssd_services) {
1667 service->withdrawn = false;
1668
1669 r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
1670 if (r < 0)
1671 log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
1672
1673 if (service->sub_ptr_rr) {
1674 r = dns_zone_put(&scope->zone, scope, service->sub_ptr_rr, false);
1675 if (r < 0)
1676 log_warning_errno(r, "Failed to add selective PTR record to MDNS zone: %m");
1677 }
1678
1679 r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
1680 if (r < 0)
1681 log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
1682
1683 LIST_FOREACH(items, txt_data, service->txt_data_items) {
1684 r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
1685 if (r < 0)
1686 log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
1687 }
1688 }
1689
1690 return 0;
1691 }
1692
1693 int dns_scope_remove_dnssd_services(DnsScope *scope) {
1694 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1695 DnssdService *service;
1696 int r;
1697
1698 assert(scope);
1699
1700 key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
1701 "_services._dns-sd._udp.local");
1702 if (!key)
1703 return log_oom();
1704
1705 r = dns_zone_remove_rrs_by_key(&scope->zone, key);
1706 if (r < 0)
1707 return r;
1708
1709 HASHMAP_FOREACH(service, scope->manager->dnssd_services) {
1710 dns_zone_remove_rr(&scope->zone, service->ptr_rr);
1711 dns_zone_remove_rr(&scope->zone, service->sub_ptr_rr);
1712 dns_zone_remove_rr(&scope->zone, service->srv_rr);
1713 LIST_FOREACH(items, txt_data, service->txt_data_items)
1714 dns_zone_remove_rr(&scope->zone, txt_data->rr);
1715 }
1716
1717 return 0;
1718 }
1719
1720 static bool dns_scope_has_route_only_domains(DnsScope *scope) {
1721 DnsSearchDomain *first;
1722 bool route_only = false;
1723
1724 assert(scope);
1725 assert(scope->protocol == DNS_PROTOCOL_DNS);
1726
1727 /* Returns 'true' if this scope is suitable for queries to specific domains only. For that we check
1728 * if there are any route-only domains on this interface, as a heuristic to discern VPN-style links
1729 * from non-VPN-style links. Returns 'false' for all other cases, i.e. if the scope is intended to
1730 * take queries to arbitrary domains, i.e. has no routing domains set. */
1731
1732 if (scope->link)
1733 first = scope->link->search_domains;
1734 else if (scope->delegate)
1735 first = scope->delegate->search_domains;
1736 else
1737 first = scope->manager->search_domains;
1738
1739 LIST_FOREACH(domains, domain, first) {
1740 /* "." means "any domain", thus the interface takes any kind of traffic. Thus, we exit early
1741 * here, as it doesn't really matter whether this link has any route-only domains or not,
1742 * "~." really trumps everything and clearly indicates that this interface shall receive all
1743 * traffic it can get. */
1744 if (dns_name_is_root(DNS_SEARCH_DOMAIN_NAME(domain)))
1745 return false;
1746
1747 if (domain->route_only)
1748 route_only = true;
1749 }
1750
1751 return route_only;
1752 }
1753
1754 bool dns_scope_is_default_route(DnsScope *scope) {
1755 assert(scope);
1756
1757 /* Only use DNS scopes as default routes */
1758 if (scope->protocol != DNS_PROTOCOL_DNS)
1759 return false;
1760
1761 if (scope->link) {
1762
1763 /* Honour whatever is explicitly configured. This is really the best approach, and trumps any
1764 * automatic logic. */
1765 if (scope->link->default_route >= 0)
1766 return scope->link->default_route;
1767
1768 /* Otherwise check if we have any route-only domains, as a sensible heuristic: if so, let's not
1769 * volunteer as default route. */
1770 return !dns_scope_has_route_only_domains(scope);
1771
1772 } else if (scope->delegate) {
1773
1774 if (scope->delegate->default_route >= 0)
1775 return scope->delegate->default_route;
1776
1777 /* Delegates are by default not used as default route */
1778 return false;
1779 } else
1780 /* The global DNS scope is always suitable as default route */
1781 return true;
1782 }
1783
1784 int dns_scope_dump_cache_to_json(DnsScope *scope, sd_json_variant **ret) {
1785 _cleanup_(sd_json_variant_unrefp) sd_json_variant *cache = NULL;
1786 int r;
1787
1788 assert(scope);
1789 assert(ret);
1790
1791 r = dns_cache_dump_to_json(&scope->cache, &cache);
1792 if (r < 0)
1793 return r;
1794
1795 return sd_json_buildo(
1796 ret,
1797 SD_JSON_BUILD_PAIR_STRING("protocol", dns_protocol_to_string(scope->protocol)),
1798 SD_JSON_BUILD_PAIR_CONDITION(scope->family != AF_UNSPEC, "family", SD_JSON_BUILD_INTEGER(scope->family)),
1799 SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifindex", SD_JSON_BUILD_INTEGER(dns_scope_ifindex(scope))),
1800 SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifname", SD_JSON_BUILD_STRING(dns_scope_ifname(scope))),
1801 SD_JSON_BUILD_PAIR_VARIANT("cache", cache));
1802 }
1803
1804 int dns_type_suitable_for_protocol(uint16_t type, DnsProtocol protocol) {
1805
1806 /* Tests whether it makes sense to route queries for the specified DNS RR types to the specified
1807 * protocol. For classic DNS pretty much all RR types are suitable, but for LLMNR/mDNS let's
1808 * allowlist only a few that make sense. We use this when routing queries so that we can more quickly
1809 * return errors for queries that will almost certainly fail/time out otherwise. For example, this
1810 * ensures that SOA, NS, or DS/DNSKEY queries are never routed to mDNS/LLMNR where they simply make
1811 * no sense. */
1812
1813 if (dns_type_is_obsolete(type))
1814 return false;
1815
1816 if (!dns_type_is_valid_query(type))
1817 return false;
1818
1819 switch (protocol) {
1820
1821 case DNS_PROTOCOL_DNS:
1822 return true;
1823
1824 case DNS_PROTOCOL_LLMNR:
1825 return IN_SET(type,
1826 DNS_TYPE_ANY,
1827 DNS_TYPE_A,
1828 DNS_TYPE_AAAA,
1829 DNS_TYPE_CNAME,
1830 DNS_TYPE_PTR,
1831 DNS_TYPE_TXT);
1832
1833 case DNS_PROTOCOL_MDNS:
1834 return IN_SET(type,
1835 DNS_TYPE_ANY,
1836 DNS_TYPE_A,
1837 DNS_TYPE_AAAA,
1838 DNS_TYPE_CNAME,
1839 DNS_TYPE_PTR,
1840 DNS_TYPE_TXT,
1841 DNS_TYPE_SRV,
1842 DNS_TYPE_NSEC,
1843 DNS_TYPE_HINFO);
1844
1845 default:
1846 return -EPROTONOSUPPORT;
1847 }
1848 }
1849
1850 int dns_question_types_suitable_for_protocol(DnsQuestion *q, DnsProtocol protocol) {
1851 DnsResourceKey *key;
1852 int r;
1853
1854 /* Tests whether the types in the specified question make any sense to be routed to the specified
1855 * protocol, i.e. if dns_type_suitable_for_protocol() is true for any of the contained RR types */
1856
1857 DNS_QUESTION_FOREACH(key, q) {
1858 r = dns_type_suitable_for_protocol(key->type, protocol);
1859 if (r != 0)
1860 return r;
1861 }
1862
1863 return false;
1864 }
1865
1866 static const char* const dns_scope_origin_table[_DNS_SCOPE_ORIGIN_MAX] = {
1867 [DNS_SCOPE_GLOBAL] = "global",
1868 [DNS_SCOPE_LINK] = "link",
1869 [DNS_SCOPE_DELEGATE] = "delegate",
1870 };
1871
1872 DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin, DnsScopeOrigin);