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