]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/resolve/resolved-dns-scope.c
resolved: use structured initialization for DnsScope
[thirdparty/systemd.git] / src / resolve / resolved-dns-scope.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
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"
10#include "missing.h"
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
46f08bea 70 log_debug("New scope on link %s, protocol %s, family %s", l ? l->name : "*", dns_protocol_to_string(protocol), family == AF_UNSPEC ? "*" : af_to_name(family));
1716f6dc 71
aea2429d
LP
72 /* Enforce ratelimiting for the multicast protocols */
73 RATELIMIT_INIT(s->ratelimit, MULTICAST_RATELIMIT_INTERVAL_USEC, MULTICAST_RATELIMIT_BURST);
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
101 log_debug("Removing scope on link %s, protocol %s, family %s", s->link ? s->link->name : "*", dns_protocol_to_string(s->protocol), s->family == AF_UNSPEC ? "*" : af_to_name(s->family));
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) {
2817157b 389 be32_t ifindex_be = htobe32(ifindex);
623a4c97
LP
390
391 if (sa.sa.sa_family == AF_INET) {
2817157b 392 r = setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex_be, sizeof(ifindex_be));
623a4c97
LP
393 if (r < 0)
394 return -errno;
395 } else if (sa.sa.sa_family == AF_INET6) {
2817157b 396 r = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_IF, &ifindex_be, sizeof(ifindex_be));
623a4c97
LP
397 if (r < 0)
398 return -errno;
399 }
400 }
401
402 if (s->protocol == DNS_PROTOCOL_LLMNR) {
bf3f1271 403 /* RFC 4795, section 2.5 requires the TTL to be set to 1 */
623a4c97
LP
404
405 if (sa.sa.sa_family == AF_INET) {
2ff48e98 406 r = setsockopt_int(fd, IPPROTO_IP, IP_TTL, true);
623a4c97 407 if (r < 0)
2ff48e98 408 return r;
623a4c97 409 } else if (sa.sa.sa_family == AF_INET6) {
2ff48e98 410 r = setsockopt_int(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, true);
623a4c97 411 if (r < 0)
2ff48e98 412 return r;
623a4c97
LP
413 }
414 }
ad867662 415
9fcdab9c
YW
416 if (type == SOCK_DGRAM) {
417 /* Set IP_RECVERR or IPV6_RECVERR to get ICMP error feedback. See discussion in #10345. */
c9e69182
LP
418
419 if (sa.sa.sa_family == AF_INET) {
420 r = setsockopt_int(fd, IPPROTO_IP, IP_RECVERR, true);
421 if (r < 0)
422 return r;
423
424 r = setsockopt_int(fd, IPPROTO_IP, IP_PKTINFO, true);
425 if (r < 0)
426 return r;
427
428 } else if (sa.sa.sa_family == AF_INET6) {
429 r = setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVERR, true);
430 if (r < 0)
431 return r;
432
433 r = setsockopt_int(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, true);
434 if (r < 0)
435 return r;
436 }
9fcdab9c
YW
437 }
438
91ccab1e
IT
439 if (ret_socket_address)
440 *ret_socket_address = sa;
441 else {
442 r = connect(fd, &sa.sa, salen);
443 if (r < 0 && errno != EINPROGRESS)
444 return -errno;
445 }
ad867662 446
c10d6bdb 447 return TAKE_FD(fd);
ad867662
LP
448}
449
519ef046 450int dns_scope_socket_udp(DnsScope *s, DnsServer *server, uint16_t port) {
91ccab1e 451 return dns_scope_socket(s, SOCK_DGRAM, AF_UNSPEC, NULL, server, port, NULL);
0db64366
TG
452}
453
91ccab1e
IT
454int 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) {
455 /* If ret_socket_address is not NULL, the caller is responisble
456 * for calling connect() or sendmsg(). This is required by TCP
457 * Fast Open, to be able to send the initial SYN packet along
458 * with the first data packet. */
459 return dns_scope_socket(s, SOCK_STREAM, family, address, server, port, ret_socket_address);
0db64366
TG
460}
461
51323288 462DnsScopeMatch dns_scope_good_domain(DnsScope *s, int ifindex, uint64_t flags, const char *domain) {
a51c1048 463 DnsSearchDomain *d;
74b2466e
LP
464
465 assert(s);
466 assert(domain);
467
28b9b764
LP
468 /* Checks if the specified domain is something to look up on
469 * this scope. Note that this accepts non-qualified hostnames,
470 * i.e. those without any search path prefixed yet. */
471
51323288
LP
472 if (ifindex != 0 && (!s->link || s->link->ifindex != ifindex))
473 return DNS_SCOPE_NO;
474
931851e8 475 if ((SD_RESOLVED_FLAGS_MAKE(s->protocol, s->family, 0) & flags) == 0)
51323288
LP
476 return DNS_SCOPE_NO;
477
78c6a153
LP
478 /* Never resolve any loopback hostname or IP address via DNS,
479 * LLMNR or mDNS. Instead, always rely on synthesized RRs for
480 * these. */
481 if (is_localhost(domain) ||
482 dns_name_endswith(domain, "127.in-addr.arpa") > 0 ||
9436e8ca
LP
483 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)
484 return DNS_SCOPE_NO;
485
c9ad0edb
LP
486 /* Never respond to some of the domains listed in RFC6303 */
487 if (dns_name_endswith(domain, "0.in-addr.arpa") > 0 ||
488 dns_name_equal(domain, "255.255.255.255.in-addr.arpa") > 0 ||
489 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)
490 return DNS_SCOPE_NO;
491
7bcffc2e
LP
492 /* Never respond to some of the domains listed in RFC6761 */
493 if (dns_name_endswith(domain, "invalid") > 0)
494 return DNS_SCOPE_NO;
495
106784eb 496 switch (s->protocol) {
801ad6a6 497
613dca46
LP
498 case DNS_PROTOCOL_DNS: {
499 DnsServer *dns_server;
500
501 /* Never route things to scopes that lack DNS servers */
502 dns_server = dns_scope_get_dns_server(s);
503 if (!dns_server)
504 return DNS_SCOPE_NO;
505
506 /* Always honour search domains for routing queries, except if this scope lacks DNS servers. Note that
507 * we return DNS_SCOPE_YES here, rather than just DNS_SCOPE_MAYBE, which means other wildcard scopes
508 * won't be considered anymore. */
509 LIST_FOREACH(domains, d, dns_scope_get_search_domains(s))
510 if (dns_name_endswith(domain, d->name) > 0)
511 return DNS_SCOPE_YES;
512
513 /* If the DNS server has route-only domains, don't send other requests to it. This would be a privacy
514 * violation, will most probably fail anyway, and adds unnecessary load. */
515 if (dns_server_limited_domains(dns_server))
516 return DNS_SCOPE_NO;
801ad6a6 517
28b9b764
LP
518 /* Exclude link-local IP ranges */
519 if (dns_name_endswith(domain, "254.169.in-addr.arpa") == 0 &&
c9ad0edb
LP
520 dns_name_endswith(domain, "8.e.f.ip6.arpa") == 0 &&
521 dns_name_endswith(domain, "9.e.f.ip6.arpa") == 0 &&
522 dns_name_endswith(domain, "a.e.f.ip6.arpa") == 0 &&
b43d96b0
DM
523 dns_name_endswith(domain, "b.e.f.ip6.arpa") == 0 &&
524 /* If networks use .local in their private setups, they are supposed to also add .local to their search
525 * domains, which we already checked above. Otherwise, we consider .local specific to mDNS and won't
526 * send such queries ordinary DNS servers. */
527 dns_name_endswith(domain, "local") == 0)
faa133f3 528 return DNS_SCOPE_MAYBE;
1716f6dc 529
faa133f3 530 return DNS_SCOPE_NO;
613dca46 531 }
1716f6dc 532
106784eb 533 case DNS_PROTOCOL_MDNS:
78c6a153
LP
534 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
535 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0) ||
536 (dns_name_endswith(domain, "local") > 0 && /* only resolve names ending in .local via mDNS */
537 dns_name_equal(domain, "local") == 0 && /* but not the single-label "local" name itself */
538 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via mDNS */
d8b7e75f 539 return DNS_SCOPE_MAYBE;
74b2466e
LP
540
541 return DNS_SCOPE_NO;
74b2466e 542
106784eb 543 case DNS_PROTOCOL_LLMNR:
78c6a153
LP
544 if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
545 (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0) ||
dc477e73 546 (dns_name_is_single_label(domain) && /* only resolve single label names via LLMNR */
78c6a153
LP
547 !is_gateway_hostname(domain) && /* don't resolve "gateway" with LLMNR, let nss-myhostname handle this */
548 manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via LLMNR */
1716f6dc 549 return DNS_SCOPE_MAYBE;
74b2466e 550
1716f6dc 551 return DNS_SCOPE_NO;
74b2466e 552
106784eb
DM
553 default:
554 assert_not_reached("Unknown scope protocol");
555 }
1716f6dc
LP
556}
557
011696f7
LP
558bool dns_scope_good_key(DnsScope *s, const DnsResourceKey *key) {
559 int key_family;
560
1716f6dc
LP
561 assert(s);
562 assert(key);
563
28b9b764
LP
564 /* Check if it makes sense to resolve the specified key on
565 * this scope. Note that this call assumes as fully qualified
566 * name, i.e. the search suffixes already appended. */
567
011696f7
LP
568 if (key->class != DNS_CLASS_IN)
569 return false;
570
28b9b764
LP
571 if (s->protocol == DNS_PROTOCOL_DNS) {
572
e5abebab 573 /* On classic DNS, looking up non-address RRs is always
28b9b764
LP
574 * fine. (Specifically, we want to permit looking up
575 * DNSKEY and DS records on the root and top-level
576 * domains.) */
577 if (!dns_resource_key_is_address(key))
578 return true;
579
580 /* However, we refuse to look up A and AAAA RRs on the
581 * root and single-label domains, under the assumption
582 * that those should be resolved via LLMNR or search
583 * path only, and should not be leaked onto the
584 * internet. */
1c02e7ba
ZJS
585 return !(dns_name_is_single_label(dns_resource_key_name(key)) ||
586 dns_name_is_root(dns_resource_key_name(key)));
28b9b764 587 }
1716f6dc
LP
588
589 /* On mDNS and LLMNR, send A and AAAA queries only on the
590 * respective scopes */
591
011696f7
LP
592 key_family = dns_type_to_af(key->type);
593 if (key_family < 0)
594 return true;
1716f6dc 595
011696f7 596 return key_family == s->family;
1716f6dc
LP
597}
598
0db4c90a 599static int dns_scope_multicast_membership(DnsScope *s, bool b, struct in_addr in, struct in6_addr in6) {
1716f6dc
LP
600 int fd;
601
5ba73e9b 602 assert(s);
5ba73e9b
LP
603 assert(s->link);
604
1716f6dc
LP
605 if (s->family == AF_INET) {
606 struct ip_mreqn mreqn = {
0db4c90a 607 .imr_multiaddr = in,
1716f6dc
LP
608 .imr_ifindex = s->link->ifindex,
609 };
610
d37baf40
DR
611 if (s->protocol == DNS_PROTOCOL_LLMNR)
612 fd = manager_llmnr_ipv4_udp_fd(s->manager);
613 else
614 fd = manager_mdns_ipv4_fd(s->manager);
615
1716f6dc
LP
616 if (fd < 0)
617 return fd;
618
7b4c2ee7
LP
619 /* Always first try to drop membership before we add
620 * one. This is necessary on some devices, such as
621 * veth. */
622 if (b)
dc751688 623 (void) setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn));
7b4c2ee7 624
1716f6dc
LP
625 if (setsockopt(fd, IPPROTO_IP, b ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0)
626 return -errno;
627
628 } else if (s->family == AF_INET6) {
629 struct ipv6_mreq mreq = {
0db4c90a 630 .ipv6mr_multiaddr = in6,
1716f6dc
LP
631 .ipv6mr_interface = s->link->ifindex,
632 };
633
d37baf40
DR
634 if (s->protocol == DNS_PROTOCOL_LLMNR)
635 fd = manager_llmnr_ipv6_udp_fd(s->manager);
636 else
637 fd = manager_mdns_ipv6_fd(s->manager);
638
1716f6dc
LP
639 if (fd < 0)
640 return fd;
641
7b4c2ee7 642 if (b)
dc751688 643 (void) setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
7b4c2ee7 644
1716f6dc
LP
645 if (setsockopt(fd, IPPROTO_IPV6, b ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
646 return -errno;
647 } else
648 return -EAFNOSUPPORT;
649
650 return 0;
74b2466e 651}
623a4c97 652
0db4c90a 653int dns_scope_llmnr_membership(DnsScope *s, bool b) {
f471bc11 654 assert(s);
0db4c90a
DM
655
656 if (s->protocol != DNS_PROTOCOL_LLMNR)
657 return 0;
658
659 return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
660}
661
662int dns_scope_mdns_membership(DnsScope *s, bool b) {
f471bc11 663 assert(s);
0db4c90a
DM
664
665 if (s->protocol != DNS_PROTOCOL_MDNS)
666 return 0;
667
668 return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
669}
670
3b991089 671int dns_scope_make_reply_packet(
ec2c5e43
LP
672 DnsScope *s,
673 uint16_t id,
674 int rcode,
675 DnsQuestion *q,
676 DnsAnswer *answer,
677 DnsAnswer *soa,
678 bool tentative,
679 DnsPacket **ret) {
680
623a4c97 681 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
623a4c97
LP
682 int r;
683
684 assert(s);
a4076574 685 assert(ret);
623a4c97 686
501e8eb0
LP
687 if (dns_question_isempty(q) &&
688 dns_answer_isempty(answer) &&
689 dns_answer_isempty(soa))
623a4c97
LP
690 return -EINVAL;
691
51027656 692 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
623a4c97
LP
693 if (r < 0)
694 return r;
695
696 DNS_PACKET_HEADER(p)->id = id;
ea917db9
LP
697 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
698 1 /* qr */,
699 0 /* opcode */,
700 0 /* c */,
701 0 /* tc */,
ec2c5e43 702 tentative,
ea917db9
LP
703 0 /* (ra) */,
704 0 /* (ad) */,
705 0 /* (cd) */,
706 rcode));
623a4c97 707
f471bc11
LP
708 r = dns_packet_append_question(p, q);
709 if (r < 0)
710 return r;
711 DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
8bf52d3d 712
f471bc11
LP
713 r = dns_packet_append_answer(p, answer);
714 if (r < 0)
715 return r;
716 DNS_PACKET_HEADER(p)->ancount = htobe16(dns_answer_size(answer));
8bf52d3d 717
f471bc11
LP
718 r = dns_packet_append_answer(p, soa);
719 if (r < 0)
720 return r;
721 DNS_PACKET_HEADER(p)->arcount = htobe16(dns_answer_size(soa));
623a4c97 722
1cc6c93a 723 *ret = TAKE_PTR(p);
623a4c97
LP
724
725 return 0;
726}
727
a4076574 728static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
2a3900d7
LP
729 DnsResourceRecord *rr;
730 DnsResourceKey *key;
a4076574
LP
731
732 assert(s);
733 assert(p);
734
2a3900d7
LP
735 DNS_QUESTION_FOREACH(key, p->question)
736 dns_zone_verify_conflicts(&s->zone, key);
737
738 DNS_ANSWER_FOREACH(rr, p->answer)
739 dns_zone_verify_conflicts(&s->zone, rr->key);
a4076574
LP
740}
741
623a4c97 742void dns_scope_process_query(DnsScope *s, DnsStream *stream, DnsPacket *p) {
8bf52d3d 743 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL, *soa = NULL;
b30bf55d 744 _cleanup_(dns_packet_unrefp) DnsPacket *reply = NULL;
5032b16d 745 DnsResourceKey *key = NULL;
ec2c5e43 746 bool tentative = false;
b30bf55d 747 int r;
623a4c97
LP
748
749 assert(s);
750 assert(p);
751
752 if (p->protocol != DNS_PROTOCOL_LLMNR)
753 return;
754
2442b93d
LP
755 if (p->ipproto == IPPROTO_UDP) {
756 /* Don't accept UDP queries directed to anything but
757 * the LLMNR multicast addresses. See RFC 4795,
d076c6f9 758 * section 2.5. */
2442b93d
LP
759
760 if (p->family == AF_INET && !in_addr_equal(AF_INET, &p->destination, (union in_addr_union*) &LLMNR_MULTICAST_IPV4_ADDRESS))
761 return;
762
763 if (p->family == AF_INET6 && !in_addr_equal(AF_INET6, &p->destination, (union in_addr_union*) &LLMNR_MULTICAST_IPV6_ADDRESS))
764 return;
765 }
766
623a4c97
LP
767 r = dns_packet_extract(p);
768 if (r < 0) {
b30bf55d 769 log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
623a4c97
LP
770 return;
771 }
772
8b757a38 773 if (DNS_PACKET_LLMNR_C(p)) {
a4076574
LP
774 /* Somebody notified us about a possible conflict */
775 dns_scope_verify_conflicts(s, p);
ea917db9
LP
776 return;
777 }
778
501e8eb0 779 assert(dns_question_size(p->question) == 1);
5032b16d
LP
780 key = p->question->keys[0];
781
97ebebbc 782 r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
623a4c97 783 if (r < 0) {
da927ba9 784 log_debug_errno(r, "Failed to lookup key: %m");
623a4c97
LP
785 return;
786 }
787 if (r == 0)
788 return;
789
fcf57f9c
LP
790 if (answer)
791 dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
af93291c 792
ec2c5e43 793 r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
623a4c97 794 if (r < 0) {
da927ba9 795 log_debug_errno(r, "Failed to build reply packet: %m");
623a4c97
LP
796 return;
797 }
798
b30bf55d 799 if (stream) {
623a4c97 800 r = dns_stream_write_packet(stream, reply);
b30bf55d
LP
801 if (r < 0) {
802 log_debug_errno(r, "Failed to enqueue reply packet: %m");
803 return;
804 }
805
806 /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
807 * will be dangling until the stream is disconnected, and the default completion handler of the stream
808 * will then unref the stream and destroy it */
809 if (DNS_STREAM_QUEUED(stream))
810 dns_stream_ref(stream);
811 } else {
812 int fd;
813
7994ac1d 814 if (!ratelimit_below(&s->ratelimit))
aea2429d
LP
815 return;
816
623a4c97
LP
817 if (p->family == AF_INET)
818 fd = manager_llmnr_ipv4_udp_fd(s->manager);
819 else if (p->family == AF_INET6)
820 fd = manager_llmnr_ipv6_udp_fd(s->manager);
821 else {
822 log_debug("Unknown protocol");
823 return;
824 }
825 if (fd < 0) {
da927ba9 826 log_debug_errno(fd, "Failed to get reply socket: %m");
623a4c97
LP
827 return;
828 }
829
6e068472
LP
830 /* Note that we always immediately reply to all LLMNR
831 * requests, and do not wait any time, since we
832 * verified uniqueness for all records. Also see RFC
833 * 4795, Section 2.7 */
834
b30bf55d
LP
835 r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
836 if (r < 0) {
837 log_debug_errno(r, "Failed to send reply packet: %m");
838 return;
839 }
623a4c97
LP
840 }
841}
ec2c5e43 842
f52e61da 843DnsTransaction *dns_scope_find_transaction(DnsScope *scope, DnsResourceKey *key, bool cache_ok) {
ec2c5e43
LP
844 DnsTransaction *t;
845
846 assert(scope);
f52e61da 847 assert(key);
ec2c5e43 848
da0c630e
LP
849 /* Try to find an ongoing transaction that is a equal to the
850 * specified question */
f9ebb22a 851 t = hashmap_get(scope->transactions_by_key, key);
4a46ed1b
LP
852 if (!t)
853 return NULL;
dc4d47e2 854
da0c630e
LP
855 /* Refuse reusing transactions that completed based on cached
856 * data instead of a real packet, if that's requested. */
857 if (!cache_ok &&
3bbdc31d 858 IN_SET(t->state, DNS_TRANSACTION_SUCCESS, DNS_TRANSACTION_RCODE_FAILURE) &&
c3bc53e6 859 t->answer_source != DNS_TRANSACTION_NETWORK)
da0c630e 860 return NULL;
ec2c5e43 861
da0c630e 862 return t;
ec2c5e43 863}
a4076574
LP
864
865static int dns_scope_make_conflict_packet(
866 DnsScope *s,
867 DnsResourceRecord *rr,
868 DnsPacket **ret) {
869
870 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
871 int r;
872
873 assert(s);
874 assert(rr);
875 assert(ret);
876
51027656 877 r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
a4076574
LP
878 if (r < 0)
879 return r;
880
881 DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
882 0 /* qr */,
883 0 /* opcode */,
884 1 /* conflict */,
885 0 /* tc */,
886 0 /* t */,
887 0 /* (ra) */,
888 0 /* (ad) */,
889 0 /* (cd) */,
890 0));
fe2dfc8b
DM
891
892 /* For mDNS, the transaction ID should always be 0 */
893 if (s->protocol != DNS_PROTOCOL_MDNS)
894 random_bytes(&DNS_PACKET_HEADER(p)->id, sizeof(uint16_t));
895
a4076574
LP
896 DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
897 DNS_PACKET_HEADER(p)->arcount = htobe16(1);
898
58ab31d5 899 r = dns_packet_append_key(p, rr->key, 0, NULL);
a4076574
LP
900 if (r < 0)
901 return r;
902
58ab31d5 903 r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
a4076574
LP
904 if (r < 0)
905 return r;
906
1cc6c93a 907 *ret = TAKE_PTR(p);
a4076574
LP
908
909 return 0;
910}
911
912static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
913 DnsScope *scope = userdata;
914 int r;
915
916 assert(es);
917 assert(scope);
918
919 scope->conflict_event_source = sd_event_source_unref(scope->conflict_event_source);
920
921 for (;;) {
432d108c 922 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
a4076574
LP
923 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
924 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
925
432d108c
DR
926 key = ordered_hashmap_first_key(scope->conflict_queue);
927 if (!key)
a4076574
LP
928 break;
929
432d108c
DR
930 rr = ordered_hashmap_remove(scope->conflict_queue, key);
931 assert(rr);
932
a4076574
LP
933 r = dns_scope_make_conflict_packet(scope, rr, &p);
934 if (r < 0) {
da927ba9 935 log_error_errno(r, "Failed to make conflict packet: %m");
a4076574
LP
936 return 0;
937 }
938
519ef046 939 r = dns_scope_emit_udp(scope, -1, p);
a4076574 940 if (r < 0)
da927ba9 941 log_debug_errno(r, "Failed to send conflict packet: %m");
a4076574
LP
942 }
943
944 return 0;
945}
946
947int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
948 usec_t jitter;
949 int r;
950
951 assert(scope);
952 assert(rr);
953
954 /* We don't send these queries immediately. Instead, we queue
955 * them, and send them after some jitter delay. */
1e43061b 956 r = ordered_hashmap_ensure_allocated(&scope->conflict_queue, &dns_resource_key_hash_ops);
a4076574
LP
957 if (r < 0) {
958 log_oom();
959 return r;
960 }
961
962 /* We only place one RR per key in the conflict
963 * messages, not all of them. That should be enough to
964 * indicate where there might be a conflict */
1e43061b 965 r = ordered_hashmap_put(scope->conflict_queue, rr->key, rr);
4c701096 966 if (IN_SET(r, 0, -EEXIST))
a4076574 967 return 0;
f647962d
MS
968 if (r < 0)
969 return log_debug_errno(r, "Failed to queue conflicting RR: %m");
a4076574 970
432d108c 971 dns_resource_key_ref(rr->key);
a4076574
LP
972 dns_resource_record_ref(rr);
973
974 if (scope->conflict_event_source)
975 return 0;
976
977 random_bytes(&jitter, sizeof(jitter));
978 jitter %= LLMNR_JITTER_INTERVAL_USEC;
979
980 r = sd_event_add_time(scope->manager->event,
981 &scope->conflict_event_source,
982 clock_boottime_or_monotonic(),
983 now(clock_boottime_or_monotonic()) + jitter,
984 LLMNR_JITTER_INTERVAL_USEC,
985 on_conflict_dispatch, scope);
f647962d
MS
986 if (r < 0)
987 return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
a4076574 988
aa4a9deb
LP
989 (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
990
a4076574
LP
991 return 0;
992}
993
994void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
c1227a18 995 DnsResourceRecord *rr;
a4076574
LP
996 int r;
997
998 assert(scope);
999 assert(p);
1000
53fda2bb 1001 if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
a4076574
LP
1002 return;
1003
1004 if (DNS_PACKET_RRCOUNT(p) <= 0)
1005 return;
1006
53fda2bb
DR
1007 if (p->protocol == DNS_PROTOCOL_LLMNR) {
1008 if (DNS_PACKET_LLMNR_C(p) != 0)
1009 return;
a4076574 1010
53fda2bb
DR
1011 if (DNS_PACKET_LLMNR_T(p) != 0)
1012 return;
1013 }
a4076574
LP
1014
1015 if (manager_our_packet(scope->manager, p))
1016 return;
1017
1018 r = dns_packet_extract(p);
1019 if (r < 0) {
da927ba9 1020 log_debug_errno(r, "Failed to extract packet: %m");
a4076574
LP
1021 return;
1022 }
1023
1024 log_debug("Checking for conflicts...");
1025
c1227a18 1026 DNS_ANSWER_FOREACH(rr, p->answer) {
cfcc8dcc 1027 /* No conflict if it is DNS-SD RR used for service enumeration. */
c1227a18 1028 if (dns_resource_key_is_dnssd_ptr(rr->key))
cfcc8dcc
DR
1029 continue;
1030
a4076574
LP
1031 /* Check for conflicts against the local zone. If we
1032 * found one, we won't check any further */
c1227a18 1033 r = dns_zone_check_conflicts(&scope->zone, rr);
a4076574
LP
1034 if (r != 0)
1035 continue;
1036
1037 /* Check for conflicts against the local cache. If so,
1038 * send out an advisory query, to inform everybody */
c1227a18 1039 r = dns_cache_check_conflicts(&scope->cache, rr, p->family, &p->sender);
a4076574
LP
1040 if (r <= 0)
1041 continue;
1042
c1227a18 1043 dns_scope_notify_conflict(scope, rr);
a4076574
LP
1044 }
1045}
4d506d6b
LP
1046
1047void dns_scope_dump(DnsScope *s, FILE *f) {
1048 assert(s);
1049
1050 if (!f)
1051 f = stdout;
1052
1053 fputs("[Scope protocol=", f);
1054 fputs(dns_protocol_to_string(s->protocol), f);
1055
1056 if (s->link) {
1057 fputs(" interface=", f);
1058 fputs(s->link->name, f);
1059 }
1060
1061 if (s->family != AF_UNSPEC) {
1062 fputs(" family=", f);
1063 fputs(af_to_name(s->family), f);
1064 }
1065
1066 fputs("]\n", f);
1067
1068 if (!dns_zone_is_empty(&s->zone)) {
1069 fputs("ZONE:\n", f);
1070 dns_zone_dump(&s->zone, f);
1071 }
1072
1073 if (!dns_cache_is_empty(&s->cache)) {
1074 fputs("CACHE:\n", f);
1075 dns_cache_dump(&s->cache, f);
1076 }
1077}
a51c1048
LP
1078
1079DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
801ad6a6
LP
1080 assert(s);
1081
a51c1048
LP
1082 if (s->protocol != DNS_PROTOCOL_DNS)
1083 return NULL;
1084
1085 if (s->link)
1086 return s->link->search_domains;
1087
28b9b764 1088 return s->manager->search_domains;
801ad6a6
LP
1089}
1090
dc477e73 1091bool dns_scope_name_needs_search_domain(DnsScope *s, const char *name) {
801ad6a6
LP
1092 assert(s);
1093
1094 if (s->protocol != DNS_PROTOCOL_DNS)
dc477e73 1095 return false;
801ad6a6 1096
dc477e73 1097 return dns_name_is_single_label(name);
801ad6a6 1098}
edbcc1fd
LP
1099
1100bool dns_scope_network_good(DnsScope *s) {
edbcc1fd
LP
1101 /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
1102 * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
1103 * DNS scope we check whether there are any links that are up and have an address. */
1104
1105 if (s->link)
1106 return true;
1107
011696f7 1108 return manager_routable(s->manager, AF_UNSPEC);
edbcc1fd 1109}
97ebebbc
LP
1110
1111int dns_scope_ifindex(DnsScope *s) {
1112 assert(s);
1113
1114 if (s->link)
1115 return s->link->ifindex;
1116
1117 return 0;
1118}
53fda2bb
DR
1119
1120static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1121 DnsScope *scope = userdata;
1122
1123 assert(s);
1124
1125 scope->announce_event_source = sd_event_source_unref(scope->announce_event_source);
1126
1a63fc54 1127 (void) dns_scope_announce(scope, false);
53fda2bb
DR
1128 return 0;
1129}
1130
1a63fc54 1131int dns_scope_announce(DnsScope *scope, bool goodbye) {
53fda2bb
DR
1132 _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
1133 _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
a2bf8a19
DR
1134 _cleanup_set_free_ Set *types = NULL;
1135 DnsTransaction *t;
400f54fb 1136 DnsZoneItem *z, *i;
a2bf8a19
DR
1137 unsigned size = 0;
1138 Iterator iterator;
1139 char *service_type;
53fda2bb
DR
1140 int r;
1141
1142 if (!scope)
1a63fc54 1143 return 0;
53fda2bb
DR
1144
1145 if (scope->protocol != DNS_PROTOCOL_MDNS)
1a63fc54 1146 return 0;
53fda2bb 1147
a2bf8a19
DR
1148 /* Check if we're done with probing. */
1149 LIST_FOREACH(transactions_by_scope, t, scope->transactions)
1150 if (DNS_TRANSACTION_IS_LIVE(t->state))
1151 return 0;
1152
e7c1b0e4
DR
1153 /* Check if there're services pending conflict resolution. */
1154 if (manager_next_dnssd_names(scope->manager))
1155 return 0; /* we reach this point only if changing hostname didn't help */
1156
a2bf8a19
DR
1157 /* Calculate answer's size. */
1158 HASHMAP_FOREACH(z, scope->zone.by_key, iterator) {
1159 if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
1160 continue;
1161
1162 if (z->rr->key->type == DNS_TYPE_PTR &&
1163 !dns_zone_contains_name(&scope->zone, z->rr->ptr.name)) {
1164 char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1165
1166 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));
1167 z->state = DNS_ZONE_ITEM_WITHDRAWN;
1168 continue;
1169 }
1170
1171 /* Collect service types for _services._dns-sd._udp.local RRs in a set */
1172 if (!scope->announced &&
1173 dns_resource_key_is_dnssd_ptr(z->rr->key)) {
1174 if (!set_contains(types, dns_resource_key_name(z->rr->key))) {
1175 r = set_ensure_allocated(&types, &dns_name_hash_ops);
1176 if (r < 0)
1177 return log_debug_errno(r, "Failed to allocate set: %m");
1178
1179 r = set_put(types, dns_resource_key_name(z->rr->key));
1180 if (r < 0)
1181 return log_debug_errno(r, "Failed to add item to set: %m");
1182 }
1183 }
1184
400f54fb
DR
1185 LIST_FOREACH(by_key, i, z)
1186 size++;
a2bf8a19
DR
1187 }
1188
1189 answer = dns_answer_new(size + set_size(types));
1a63fc54
LP
1190 if (!answer)
1191 return log_oom();
1192
a2bf8a19 1193 /* Second iteration, actually add RRs to the answer. */
400f54fb
DR
1194 HASHMAP_FOREACH(z, scope->zone.by_key, iterator)
1195 LIST_FOREACH (by_key, i, z) {
1196 DnsAnswerFlags flags;
a2bf8a19 1197
400f54fb
DR
1198 if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
1199 continue;
a2bf8a19 1200
400f54fb
DR
1201 if (dns_resource_key_is_dnssd_ptr(i->rr->key))
1202 flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
1203 else
1204 flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
a2bf8a19 1205
400f54fb
DR
1206 r = dns_answer_add(answer, i->rr, 0 , flags);
1207 if (r < 0)
1208 return log_debug_errno(r, "Failed to add RR to announce: %m");
1209 }
a2bf8a19
DR
1210
1211 /* Since all the active services are in the zone make them discoverable now. */
1212 SET_FOREACH(service_type, types, iterator) {
1213 _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr;
1214
1215 rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
1216 "_services._dns-sd._udp.local");
1217 rr->ptr.name = strdup(service_type);
1218 rr->ttl = MDNS_DEFAULT_TTL;
1219
1220 r = dns_zone_put(&scope->zone, scope, rr, false);
1a63fc54 1221 if (r < 0)
a2bf8a19 1222 log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone: %m");
1a63fc54 1223
a2bf8a19 1224 r = dns_answer_add(answer, rr, 0 , 0);
1a63fc54 1225 if (r < 0)
a2bf8a19 1226 return log_debug_errno(r, "Failed to add RR to announce: %m");
53fda2bb
DR
1227 }
1228
1229 if (dns_answer_isempty(answer))
1a63fc54 1230 return 0;
53fda2bb
DR
1231
1232 r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
1a63fc54
LP
1233 if (r < 0)
1234 return log_debug_errno(r, "Failed to build reply packet: %m");
1235
53fda2bb 1236 r = dns_scope_emit_udp(scope, -1, p);
1a63fc54
LP
1237 if (r < 0)
1238 return log_debug_errno(r, "Failed to send reply packet: %m");
53fda2bb
DR
1239
1240 /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
1241 * responses, one second apart." */
1242 if (!scope->announced) {
1243 usec_t ts;
1244
1245 scope->announced = true;
1246
1247 assert_se(sd_event_now(scope->manager->event, clock_boottime_or_monotonic(), &ts) >= 0);
1248 ts += MDNS_ANNOUNCE_DELAY;
1249
1250 r = sd_event_add_time(
1251 scope->manager->event,
1252 &scope->announce_event_source,
1253 clock_boottime_or_monotonic(),
1254 ts,
1255 MDNS_JITTER_RANGE_USEC,
1256 on_announcement_timeout, scope);
1257 if (r < 0)
1a63fc54 1258 return log_debug_errno(r, "Failed to schedule second announcement: %m");
19fee3ef
LP
1259
1260 (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
53fda2bb 1261 }
1a63fc54
LP
1262
1263 return 0;
53fda2bb 1264}
6db6a464
DR
1265
1266int dns_scope_add_dnssd_services(DnsScope *scope) {
1267 Iterator i;
1268 DnssdService *service;
400f54fb 1269 DnssdTxtData *txt_data;
6db6a464
DR
1270 int r;
1271
1272 assert(scope);
1273
1274 if (hashmap_size(scope->manager->dnssd_services) == 0)
1275 return 0;
1276
1277 scope->announced = false;
1278
1279 HASHMAP_FOREACH(service, scope->manager->dnssd_services, i) {
c3036641
DR
1280 service->withdrawn = false;
1281
6db6a464
DR
1282 r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
1283 if (r < 0)
1284 log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
1285
1286 r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
1287 if (r < 0)
1288 log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
1289
400f54fb
DR
1290 LIST_FOREACH(items, txt_data, service->txt_data_items) {
1291 r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
1292 if (r < 0)
1293 log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
1294 }
6db6a464
DR
1295 }
1296
1297 return 0;
1298}
1299
1300int dns_scope_remove_dnssd_services(DnsScope *scope) {
1301 _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1302 Iterator i;
1303 DnssdService *service;
400f54fb 1304 DnssdTxtData *txt_data;
6db6a464
DR
1305 int r;
1306
1307 assert(scope);
1308
1309 key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
1310 "_services._dns-sd._udp.local");
1311 if (!key)
1312 return log_oom();
1313
1314 r = dns_zone_remove_rrs_by_key(&scope->zone, key);
1315 if (r < 0)
1316 return r;
1317
1318 HASHMAP_FOREACH(service, scope->manager->dnssd_services, i) {
1319 dns_zone_remove_rr(&scope->zone, service->ptr_rr);
1320 dns_zone_remove_rr(&scope->zone, service->srv_rr);
400f54fb
DR
1321 LIST_FOREACH(items, txt_data, service->txt_data_items)
1322 dns_zone_remove_rr(&scope->zone, txt_data->rr);
6db6a464
DR
1323 }
1324
1325 return 0;
1326}