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