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