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