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