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