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