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