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