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