Coverage Report

Created: 2025-11-16 06:36

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/systemd/src/resolve/resolved-dns-scope.c
Line
Count
Source
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3
#include <netinet/tcp.h>
4
5
#include "sd-event.h"
6
#include "sd-json.h"
7
8
#include "af-list.h"
9
#include "alloc-util.h"
10
#include "dns-answer.h"
11
#include "dns-domain.h"
12
#include "dns-packet.h"
13
#include "dns-question.h"
14
#include "dns-rr.h"
15
#include "dns-type.h"
16
#include "errno-util.h"
17
#include "fd-util.h"
18
#include "hostname-util.h"
19
#include "log.h"
20
#include "random-util.h"
21
#include "resolved-dns-browse-services.h"
22
#include "resolved-dns-delegate.h"
23
#include "resolved-dns-query.h"
24
#include "resolved-dns-scope.h"
25
#include "resolved-dns-search-domain.h"
26
#include "resolved-dns-server.h"
27
#include "resolved-dns-synthesize.h"
28
#include "resolved-dns-transaction.h"
29
#include "resolved-dns-zone.h"
30
#include "resolved-dnssd.h"
31
#include "resolved-link.h"
32
#include "resolved-llmnr.h"
33
#include "resolved-manager.h"
34
#include "resolved-mdns.h"
35
#include "resolved-timeouts.h"
36
#include "set.h"
37
#include "socket-util.h"
38
#include "string-table.h"
39
40
0
#define MULTICAST_RATELIMIT_INTERVAL_USEC (1*USEC_PER_SEC)
41
0
#define MULTICAST_RATELIMIT_BURST 1000
42
43
/* After how much time to repeat LLMNR requests, see RFC 4795 Section 7 */
44
0
#define MULTICAST_RESEND_TIMEOUT_MIN_USEC (100 * USEC_PER_MSEC)
45
#define MULTICAST_RESEND_TIMEOUT_MAX_USEC (1 * USEC_PER_SEC)
46
47
int dns_scope_new(
48
                Manager *m,
49
                DnsScope **ret,
50
                DnsScopeOrigin origin,
51
                Link *link,
52
                DnsDelegate *delegate,
53
                DnsProtocol protocol,
54
0
                int family) {
55
56
0
        DnsScope *s;
57
58
0
        assert(m);
59
0
        assert(ret);
60
0
        assert(origin >= 0);
61
0
        assert(origin < _DNS_SCOPE_ORIGIN_MAX);
62
63
0
        assert(!!link == (origin == DNS_SCOPE_LINK));
64
0
        assert(!!delegate == (origin == DNS_SCOPE_DELEGATE));
65
66
0
        s = new(DnsScope, 1);
67
0
        if (!s)
68
0
                return -ENOMEM;
69
70
0
        *s = (DnsScope) {
71
0
                .manager = m,
72
0
                .link = link,
73
0
                .delegate = delegate,
74
0
                .origin = origin,
75
0
                .protocol = protocol,
76
0
                .family = family,
77
0
                .resend_timeout = MULTICAST_RESEND_TIMEOUT_MIN_USEC,
78
79
                /* Enforce ratelimiting for the multicast protocols */
80
0
                .ratelimit = { MULTICAST_RATELIMIT_INTERVAL_USEC, MULTICAST_RATELIMIT_BURST },
81
0
        };
82
83
0
        if (protocol == DNS_PROTOCOL_DNS) {
84
                /* Copy DNSSEC mode from the link if it is set there,
85
                 * otherwise take the manager's DNSSEC mode. Note that
86
                 * we copy this only at scope creation time, and do
87
                 * not update it from the on, even if the setting
88
                 * changes. */
89
90
0
                if (link) {
91
0
                        s->dnssec_mode = link_get_dnssec_mode(link);
92
0
                        s->dns_over_tls_mode = link_get_dns_over_tls_mode(link);
93
0
                } else {
94
0
                        s->dnssec_mode = manager_get_dnssec_mode(m);
95
0
                        s->dns_over_tls_mode = manager_get_dns_over_tls_mode(m);
96
0
                }
97
98
0
        } else {
99
0
                s->dnssec_mode = DNSSEC_NO;
100
0
                s->dns_over_tls_mode = DNS_OVER_TLS_NO;
101
0
        }
102
103
0
        LIST_PREPEND(scopes, m->dns_scopes, s);
104
105
0
        dns_scope_llmnr_membership(s, true);
106
0
        dns_scope_mdns_membership(s, true);
107
108
0
        log_debug("New scope on link %s, protocol %s, family %s, origin %s, delegate %s",
109
0
                  link ? link->ifname : "*",
110
0
                  dns_protocol_to_string(protocol),
111
0
                  family == AF_UNSPEC ? "*" : af_to_name(family),
112
0
                  dns_scope_origin_to_string(origin),
113
0
                  s->delegate ? s->delegate->id : "n/a");
114
115
0
        *ret = s;
116
0
        return 0;
117
0
}
118
119
0
static void dns_scope_abort_transactions(DnsScope *s) {
120
0
        assert(s);
121
122
0
        while (s->transactions) {
123
0
                DnsTransaction *t = s->transactions;
124
125
                /* Abort the transaction, but make sure it is not
126
                 * freed while we still look at it */
127
128
0
                t->block_gc++;
129
0
                if (DNS_TRANSACTION_IS_LIVE(t->state))
130
0
                        dns_transaction_complete(t, DNS_TRANSACTION_ABORTED);
131
0
                t->block_gc--;
132
133
0
                dns_transaction_free(t);
134
0
        }
135
0
}
136
137
0
DnsScope* dns_scope_free(DnsScope *s) {
138
0
        if (!s)
139
0
                return NULL;
140
141
0
        log_debug("Removing scope on link %s, protocol %s, family %s, origin %s, delegate %s",
142
0
                  s->link ? s->link->ifname : "*",
143
0
                  dns_protocol_to_string(s->protocol),
144
0
                  s->family == AF_UNSPEC ? "*" : af_to_name(s->family),
145
0
                  dns_scope_origin_to_string(s->origin),
146
0
                  s->delegate ? s->delegate->id : "n/a");
147
148
0
        dns_scope_llmnr_membership(s, false);
149
0
        dns_scope_mdns_membership(s, false);
150
0
        dns_scope_abort_transactions(s);
151
152
0
        while (s->query_candidates)
153
0
                dns_query_candidate_unref(s->query_candidates);
154
155
0
        hashmap_free(s->transactions_by_key);
156
157
0
        ordered_hashmap_free(s->conflict_queue);
158
0
        sd_event_source_disable_unref(s->conflict_event_source);
159
160
0
        sd_event_source_disable_unref(s->announce_event_source);
161
162
0
        sd_event_source_disable_unref(s->mdns_goodbye_event_source);
163
164
0
        dns_cache_flush(&s->cache);
165
0
        dns_zone_flush(&s->zone);
166
167
        /* Clear records of mDNS service browse subscriber, since cache bas been flushed */
168
0
        dns_browse_services_purge(s->manager, s->family);
169
170
0
        LIST_REMOVE(scopes, s->manager->dns_scopes, s);
171
0
        return mfree(s);
172
0
}
173
174
0
DnsServer *dns_scope_get_dns_server(DnsScope *s) {
175
0
        assert(s);
176
177
0
        if (s->protocol != DNS_PROTOCOL_DNS)
178
0
                return NULL;
179
180
0
        if (s->link) {
181
0
                assert(!s->delegate);
182
0
                return link_get_dns_server(s->link);
183
0
        } else if (s->delegate)
184
0
                return dns_delegate_get_dns_server(s->delegate);
185
0
        else
186
0
                return manager_get_dns_server(s->manager);
187
0
}
188
189
0
unsigned dns_scope_get_n_dns_servers(DnsScope *s) {
190
0
        assert(s);
191
192
0
        if (s->protocol != DNS_PROTOCOL_DNS)
193
0
                return 0;
194
195
0
        if (s->link) {
196
0
                assert(!s->delegate);
197
0
                return s->link->n_dns_servers;
198
0
        } else if (s->delegate)
199
0
                return s->delegate->n_dns_servers;
200
0
        else
201
0
                return s->manager->n_dns_servers;
202
0
}
203
204
0
void dns_scope_next_dns_server(DnsScope *s, DnsServer *if_current) {
205
0
        assert(s);
206
207
0
        if (s->protocol != DNS_PROTOCOL_DNS)
208
0
                return;
209
210
        /* Changes to the next DNS server in the list. If 'if_current' is passed will do so only if the
211
         * current DNS server still matches it. */
212
213
0
        if (s->link)
214
0
                link_next_dns_server(s->link, if_current);
215
0
        else if (s->delegate)
216
0
                dns_delegate_next_dns_server(s->delegate, if_current);
217
0
        else
218
0
                manager_next_dns_server(s->manager, if_current);
219
0
}
220
221
0
void dns_scope_packet_received(DnsScope *s, usec_t rtt) {
222
0
        assert(s);
223
224
0
        if (rtt <= s->max_rtt)
225
0
                return;
226
227
0
        s->max_rtt = rtt;
228
0
        s->resend_timeout = MIN(MAX(MULTICAST_RESEND_TIMEOUT_MIN_USEC, s->max_rtt * 2), MULTICAST_RESEND_TIMEOUT_MAX_USEC);
229
0
}
230
231
0
void dns_scope_packet_lost(DnsScope *s, usec_t usec) {
232
0
        assert(s);
233
234
0
        if (s->resend_timeout <= usec)
235
0
                s->resend_timeout = MIN(s->resend_timeout * 2, MULTICAST_RESEND_TIMEOUT_MAX_USEC);
236
0
}
237
238
0
static int dns_scope_emit_one(DnsScope *s, int fd, int family, DnsPacket *p) {
239
0
        int r;
240
241
0
        assert(s);
242
0
        assert(p);
243
0
        assert(p->protocol == s->protocol);
244
245
0
        if (family == AF_UNSPEC) {
246
0
                if (s->family == AF_UNSPEC)
247
0
                        return -EAFNOSUPPORT;
248
249
0
                family = s->family;
250
0
        }
251
252
0
        switch (s->protocol) {
253
254
0
        case DNS_PROTOCOL_DNS: {
255
0
                size_t mtu, udp_size, min_mtu, socket_mtu = 0;
256
257
0
                assert(fd >= 0);
258
259
0
                if (DNS_PACKET_QDCOUNT(p) > 1) /* Classic DNS only allows one question per packet */
260
0
                        return -EOPNOTSUPP;
261
262
0
                if (p->size > DNS_PACKET_UNICAST_SIZE_MAX)
263
0
                        return -EMSGSIZE;
264
265
                /* Determine the local most accurate MTU */
266
0
                if (s->link)
267
0
                        mtu = s->link->mtu;
268
0
                else
269
0
                        mtu = manager_find_mtu(s->manager);
270
271
                /* Acquire the socket's PMDU MTU */
272
0
                r = socket_get_mtu(fd, family, &socket_mtu);
273
0
                if (r < 0 && !ERRNO_IS_DISCONNECT(r)) /* Will return ENOTCONN if no information is available yet */
274
0
                        return log_debug_errno(r, "Failed to read socket MTU: %m");
275
276
                /* Determine the appropriate UDP header size */
277
0
                udp_size = udp_header_size(family);
278
0
                min_mtu = udp_size + DNS_PACKET_HEADER_SIZE;
279
280
0
                log_debug("Emitting UDP, link MTU is %zu, socket MTU is %zu, minimal MTU is %zu",
281
0
                          mtu, socket_mtu, min_mtu);
282
283
                /* Clamp by the kernel's idea of the (path) MTU */
284
0
                if (socket_mtu != 0 && socket_mtu < mtu)
285
0
                        mtu = socket_mtu;
286
287
                /* Put a lower limit, in case all MTU data we acquired was rubbish */
288
0
                if (mtu < min_mtu)
289
0
                        mtu = min_mtu;
290
291
                /* Now check our packet size against the MTU we determined */
292
0
                if (udp_size + p->size > mtu)
293
0
                        return -EMSGSIZE; /* This means: try TCP instead */
294
295
0
                r = manager_write(s->manager, fd, p);
296
0
                if (r < 0)
297
0
                        return r;
298
299
0
                break;
300
0
        }
301
302
0
        case DNS_PROTOCOL_LLMNR: {
303
0
                union in_addr_union addr;
304
305
0
                assert(fd < 0);
306
307
0
                if (DNS_PACKET_QDCOUNT(p) > 1)
308
0
                        return -EOPNOTSUPP;
309
310
0
                if (!ratelimit_below(&s->ratelimit))
311
0
                        return -EBUSY;
312
313
0
                if (family == AF_INET) {
314
0
                        addr.in = LLMNR_MULTICAST_IPV4_ADDRESS;
315
0
                        fd = manager_llmnr_ipv4_udp_fd(s->manager);
316
0
                } else if (family == AF_INET6) {
317
0
                        addr.in6 = LLMNR_MULTICAST_IPV6_ADDRESS;
318
0
                        fd = manager_llmnr_ipv6_udp_fd(s->manager);
319
0
                } else
320
0
                        return -EAFNOSUPPORT;
321
0
                if (fd < 0)
322
0
                        return fd;
323
324
0
                assert(s->link);
325
0
                r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, LLMNR_PORT, NULL, p);
326
0
                if (r < 0)
327
0
                        return r;
328
329
0
                break;
330
0
        }
331
332
0
        case DNS_PROTOCOL_MDNS: {
333
0
                union in_addr_union addr;
334
0
                assert(fd < 0);
335
336
0
                if (!ratelimit_below(&s->ratelimit))
337
0
                        return -EBUSY;
338
339
0
                if (family == AF_INET) {
340
0
                        if (in4_addr_is_null(&p->destination.in))
341
0
                                addr.in = MDNS_MULTICAST_IPV4_ADDRESS;
342
0
                        else
343
0
                                addr = p->destination;
344
0
                        fd = manager_mdns_ipv4_fd(s->manager);
345
0
                } else if (family == AF_INET6) {
346
0
                        if (in6_addr_is_null(&p->destination.in6))
347
0
                                addr.in6 = MDNS_MULTICAST_IPV6_ADDRESS;
348
0
                        else
349
0
                                addr = p->destination;
350
0
                        fd = manager_mdns_ipv6_fd(s->manager);
351
0
                } else
352
0
                        return -EAFNOSUPPORT;
353
0
                if (fd < 0)
354
0
                        return fd;
355
356
0
                assert(s->link);
357
0
                r = manager_send(s->manager, fd, s->link->ifindex, family, &addr, p->destination_port ?: MDNS_PORT, NULL, p);
358
0
                if (r < 0)
359
0
                        return r;
360
361
0
                break;
362
0
        }
363
364
0
        default:
365
0
                return -EAFNOSUPPORT;
366
0
        }
367
368
0
        return 1;
369
0
}
370
371
0
int dns_scope_emit_udp(DnsScope *s, int fd, int af, DnsPacket *p) {
372
0
        int r;
373
374
0
        assert(s);
375
0
        assert(p);
376
0
        assert(p->protocol == s->protocol);
377
0
        assert((s->protocol == DNS_PROTOCOL_DNS) == (fd >= 0));
378
379
0
        do {
380
                /* If there are multiple linked packets, set the TC bit in all but the last of them */
381
0
                if (p->more) {
382
0
                        assert(p->protocol == DNS_PROTOCOL_MDNS);
383
0
                        dns_packet_set_flags(p, true, true);
384
0
                }
385
386
0
                r = dns_scope_emit_one(s, fd, af, p);
387
0
                if (r < 0)
388
0
                        return r;
389
390
0
                p = p->more;
391
0
        } while (p);
392
393
0
        return 0;
394
0
}
395
396
static int dns_scope_socket(
397
                DnsScope *s,
398
                int type,
399
                int family,
400
                const union in_addr_union *address,
401
                DnsServer *server,
402
                uint16_t port,
403
0
                union sockaddr_union *ret_socket_address) {
404
405
0
        _cleanup_close_ int fd = -EBADF;
406
0
        union sockaddr_union sa;
407
0
        socklen_t salen;
408
0
        int r, ifindex;
409
410
0
        assert(s);
411
412
0
        if (server) {
413
0
                assert(family == AF_UNSPEC);
414
0
                assert(!address);
415
416
0
                ifindex = dns_server_ifindex(server);
417
418
0
                switch (server->family) {
419
0
                case AF_INET:
420
0
                        sa = (union sockaddr_union) {
421
0
                                .in.sin_family = server->family,
422
0
                                .in.sin_port = htobe16(port),
423
0
                                .in.sin_addr = server->address.in,
424
0
                        };
425
0
                        salen = sizeof(sa.in);
426
0
                        break;
427
0
                case AF_INET6:
428
0
                        sa = (union sockaddr_union) {
429
0
                                .in6.sin6_family = server->family,
430
0
                                .in6.sin6_port = htobe16(port),
431
0
                                .in6.sin6_addr = server->address.in6,
432
0
                                .in6.sin6_scope_id = ifindex,
433
0
                        };
434
0
                        salen = sizeof(sa.in6);
435
0
                        break;
436
0
                default:
437
0
                        return -EAFNOSUPPORT;
438
0
                }
439
0
        } else {
440
0
                assert(family != AF_UNSPEC);
441
0
                assert(address);
442
443
0
                ifindex = dns_scope_ifindex(s);
444
445
0
                switch (family) {
446
0
                case AF_INET:
447
0
                        sa = (union sockaddr_union) {
448
0
                                .in.sin_family = family,
449
0
                                .in.sin_port = htobe16(port),
450
0
                                .in.sin_addr = address->in,
451
0
                        };
452
0
                        salen = sizeof(sa.in);
453
0
                        break;
454
0
                case AF_INET6:
455
0
                        sa = (union sockaddr_union) {
456
0
                                .in6.sin6_family = family,
457
0
                                .in6.sin6_port = htobe16(port),
458
0
                                .in6.sin6_addr = address->in6,
459
0
                                .in6.sin6_scope_id = ifindex,
460
0
                        };
461
0
                        salen = sizeof(sa.in6);
462
0
                        break;
463
0
                default:
464
0
                        return -EAFNOSUPPORT;
465
0
                }
466
0
        }
467
468
0
        fd = socket(sa.sa.sa_family, type|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
469
0
        if (fd < 0)
470
0
                return -errno;
471
472
0
        if (type == SOCK_STREAM) {
473
0
                r = setsockopt_int(fd, IPPROTO_TCP, TCP_NODELAY, true);
474
0
                if (r < 0)
475
0
                        return r;
476
0
        }
477
478
0
        bool addr_is_nonlocal = s->link &&
479
0
            !manager_find_link_address(s->manager, sa.sa.sa_family, sockaddr_in_addr(&sa.sa)) &&
480
0
            in_addr_is_localhost(sa.sa.sa_family, sockaddr_in_addr(&sa.sa)) == 0;
481
482
0
        if (addr_is_nonlocal && ifindex != 0) {
483
                /* As a special exception we don't use UNICAST_IF if we notice that the specified IP address
484
                 * is on the local host. Otherwise, destination addresses on the local host result in
485
                 * EHOSTUNREACH, since Linux won't send the packets out of the specified interface, but
486
                 * delivers them directly to the local socket. */
487
0
                r = socket_set_unicast_if(fd, sa.sa.sa_family, ifindex);
488
0
                if (r < 0)
489
0
                        return r;
490
0
        }
491
492
0
        if (s->protocol == DNS_PROTOCOL_LLMNR) {
493
                /* RFC 4795, section 2.5 requires the TTL to be set to 1 */
494
0
                r = socket_set_ttl(fd, sa.sa.sa_family, 1);
495
0
                if (r < 0)
496
0
                        return r;
497
0
        }
498
499
0
        if (type == SOCK_DGRAM) {
500
                /* Set IP_RECVERR or IPV6_RECVERR to get ICMP error feedback. See discussion in #10345. */
501
0
                r = socket_set_recverr(fd, sa.sa.sa_family, true);
502
0
                if (r < 0)
503
0
                        return r;
504
505
0
                r = socket_set_recvpktinfo(fd, sa.sa.sa_family, true);
506
0
                if (r < 0)
507
0
                        return r;
508
509
                /* Turn of path MTU discovery for security reasons */
510
0
                r = socket_disable_pmtud(fd, sa.sa.sa_family);
511
0
                if (r < 0)
512
0
                        log_debug_errno(r, "Failed to disable UDP PMTUD, ignoring: %m");
513
514
                /* Learn about fragmentation taking place */
515
0
                r = socket_set_recvfragsize(fd, sa.sa.sa_family, true);
516
0
                if (r < 0)
517
0
                        log_debug_errno(r, "Failed to enable fragment size reception, ignoring: %m");
518
0
        }
519
520
0
        if (ret_socket_address)
521
0
                *ret_socket_address = sa;
522
0
        else {
523
0
                bool bound = false;
524
525
                /* Let's temporarily bind the socket to the specified ifindex. Older kernels only take
526
                 * the SO_BINDTODEVICE/SO_BINDTOINDEX ifindex into account when making routing decisions
527
                 * in connect() — and not IP_UNICAST_IF. We don't really want any of the other semantics of
528
                 * SO_BINDTODEVICE/SO_BINDTOINDEX, hence we immediately unbind the socket after the fact
529
                 * again.
530
                 */
531
0
                if (addr_is_nonlocal) {
532
0
                        r = socket_bind_to_ifindex(fd, ifindex);
533
0
                        if (r < 0)
534
0
                                return r;
535
536
0
                        bound = true;
537
0
                }
538
539
0
                r = connect(fd, &sa.sa, salen);
540
0
                if (r < 0 && errno != EINPROGRESS)
541
0
                        return -errno;
542
543
0
                if (bound) {
544
0
                        r = socket_bind_to_ifindex(fd, 0);
545
0
                        if (r < 0)
546
0
                                return r;
547
0
                }
548
0
        }
549
550
0
        return TAKE_FD(fd);
551
0
}
552
553
0
int dns_scope_socket_udp(DnsScope *s, DnsServer *server) {
554
0
        return dns_scope_socket(s, SOCK_DGRAM, AF_UNSPEC, NULL, server, dns_server_port(server), NULL);
555
0
}
556
557
0
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) {
558
        /* If ret_socket_address is not NULL, the caller is responsible
559
         * for calling connect() or sendmsg(). This is required by TCP
560
         * Fast Open, to be able to send the initial SYN packet along
561
         * with the first data packet. */
562
0
        return dns_scope_socket(s, SOCK_STREAM, family, address, server, port, ret_socket_address);
563
0
}
564
565
0
static DnsScopeMatch match_link_local_reverse_lookups(const char *domain) {
566
0
        assert(domain);
567
568
0
        if (dns_name_endswith(domain, "254.169.in-addr.arpa") > 0)
569
0
                return DNS_SCOPE_YES_BASE + 4; /* 4 labels match */
570
571
0
        if (dns_name_endswith(domain, "8.e.f.ip6.arpa") > 0 ||
572
0
            dns_name_endswith(domain, "9.e.f.ip6.arpa") > 0 ||
573
0
            dns_name_endswith(domain, "a.e.f.ip6.arpa") > 0 ||
574
0
            dns_name_endswith(domain, "b.e.f.ip6.arpa") > 0)
575
0
                return DNS_SCOPE_YES_BASE + 5; /* 5 labels match */
576
577
0
        return _DNS_SCOPE_MATCH_INVALID;
578
0
}
579
580
static DnsScopeMatch match_subnet_reverse_lookups(
581
                DnsScope *s,
582
                const char *domain,
583
0
                bool exclude_own) {
584
585
0
        union in_addr_union ia;
586
0
        int f, r;
587
588
0
        assert(s);
589
0
        assert(domain);
590
591
        /* Checks whether the specified domain is a reverse address domain (i.e. in the .in-addr.arpa or
592
         * .ip6.arpa area), and if so, whether the address matches any of the local subnets of the link the
593
         * scope is associated with. If so, our scope should consider itself relevant for any lookup in the
594
         * domain, since it apparently refers to hosts on this link's subnet.
595
         *
596
         * If 'exclude_own' is true this will return DNS_SCOPE_NO for any IP addresses assigned locally. This
597
         * is useful for LLMNR/mDNS as we never want to look up our own hostname on LLMNR/mDNS but always use
598
         * the locally synthesized one. */
599
600
0
        if (!s->link)
601
0
                return _DNS_SCOPE_MATCH_INVALID; /* No link, hence no local addresses to check */
602
603
0
        r = dns_name_address(domain, &f, &ia);
604
0
        if (r < 0)
605
0
                log_debug_errno(r, "Failed to determine whether '%s' is an address domain: %m", domain);
606
0
        if (r <= 0)
607
0
                return _DNS_SCOPE_MATCH_INVALID;
608
609
0
        if (s->family != AF_UNSPEC && f != s->family)
610
0
                return _DNS_SCOPE_MATCH_INVALID; /* Don't look for IPv4 addresses on LLMNR/mDNS over IPv6 and vice versa */
611
612
0
        if (in_addr_is_null(f, &ia))
613
0
                return DNS_SCOPE_NO;
614
615
0
        LIST_FOREACH(addresses, a, s->link->addresses) {
616
617
0
                if (a->family != f)
618
0
                        continue;
619
620
                /* Equals our own address? nah, let's not use this scope. The local synthesizer will pick it up for us. */
621
0
                if (exclude_own &&
622
0
                    in_addr_equal(f, &a->in_addr, &ia) > 0)
623
0
                        return DNS_SCOPE_NO;
624
625
0
                if (a->prefixlen == UCHAR_MAX) /* don't know subnet mask */
626
0
                        continue;
627
628
                /* Don't send mDNS queries for the IPv4 broadcast address */
629
0
                if (f == AF_INET && in_addr_equal(f, &a->in_addr_broadcast, &ia) > 0)
630
0
                        return DNS_SCOPE_NO;
631
632
                /* Check if the address is in the local subnet */
633
0
                r = in_addr_prefix_covers(f, &a->in_addr, a->prefixlen, &ia);
634
0
                if (r < 0)
635
0
                        log_debug_errno(r, "Failed to determine whether link address covers lookup address '%s': %m", domain);
636
0
                if (r > 0)
637
                        /* Note that we only claim zero labels match. This is so that this is at the same
638
                         * priority a DNS scope with "." as routing domain is. */
639
0
                        return DNS_SCOPE_YES_BASE + 0;
640
0
        }
641
642
0
        return _DNS_SCOPE_MATCH_INVALID;
643
0
}
644
645
/* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml */
646
/* https://www.iana.org/assignments/locally-served-dns-zones/locally-served-dns-zones.xhtml */
647
0
static bool dns_refuse_special_use_domain(const char *domain, DnsQuestion *question) {
648
        /* RFC9462 § 6.4: resolvers SHOULD respond to queries of any type other than SVCB for
649
         * _dns.resolver.arpa. with NODATA and queries of any type for any domain name under
650
         * resolver.arpa with NODATA. */
651
0
        if (dns_name_equal(domain, "_dns.resolver.arpa") > 0) {
652
0
                DnsResourceKey *t;
653
654
                /* Only SVCB is permitted to _dns.resolver.arpa */
655
0
                DNS_QUESTION_FOREACH(t, question)
656
0
                        if (t->type == DNS_TYPE_SVCB)
657
0
                                return false;
658
659
0
                return true;
660
0
        }
661
662
0
        if (dns_name_endswith(domain, "resolver.arpa") > 0)
663
0
                return true;
664
665
0
        return false;
666
0
}
667
668
DnsScopeMatch dns_scope_good_domain(
669
                DnsScope *s,
670
                DnsQuery *q,
671
0
                uint64_t query_flags) {
672
673
0
        DnsQuestion *question;
674
0
        const char *domain;
675
0
        uint64_t flags;
676
0
        int ifindex, r;
677
678
        /* This returns the following return values:
679
         *
680
         *    DNS_SCOPE_NO         → This scope is not suitable for lookups of this domain, at all
681
         *    DNS_SCOPE_LAST_RESORT→ This scope is not suitable, unless we have no alternative
682
         *    DNS_SCOPE_MAYBE      → This scope is suitable, but only if nothing else wants it
683
         *    DNS_SCOPE_YES_BASE+n → This scope is suitable, and 'n' suffix labels match
684
         *
685
         *  (The idea is that the caller will only use the scopes with the longest 'n' returned. If no scopes return
686
         *  DNS_SCOPE_YES_BASE+n, then it should use those which returned DNS_SCOPE_MAYBE. It should never use those
687
         *  which returned DNS_SCOPE_NO.)
688
         */
689
690
0
        assert(s);
691
0
        assert(q);
692
693
0
        question = dns_query_question_for_protocol(q, s->protocol);
694
0
        if (!question)
695
0
                return DNS_SCOPE_NO;
696
697
0
        domain = dns_question_first_name(question);
698
0
        if (!domain)
699
0
                return DNS_SCOPE_NO;
700
701
0
        ifindex = q->ifindex;
702
0
        flags = q->flags;
703
704
        /* Checks if the specified domain is something to look up on this scope. Note that this accepts
705
         * non-qualified hostnames, i.e. those without any search path suffixed. */
706
707
0
        if (ifindex != 0 && (!s->link || s->link->ifindex != ifindex))
708
0
                return DNS_SCOPE_NO;
709
710
0
        if ((SD_RESOLVED_FLAGS_MAKE(s->protocol, s->family, false, false) & flags) == 0)
711
0
                return DNS_SCOPE_NO;
712
713
        /* Never resolve any loopback hostname or IP address via DNS, LLMNR or mDNS. Instead, always rely on
714
         * synthesized RRs for these. */
715
0
        if (is_localhost(domain) ||
716
0
            dns_name_endswith(domain, "127.in-addr.arpa") > 0 ||
717
0
            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)
718
0
                return DNS_SCOPE_NO;
719
720
        /* Never respond to some of the domains listed in RFC6303 + RFC6761 */
721
0
        if (dns_name_dont_resolve(domain))
722
0
                return DNS_SCOPE_NO;
723
724
        /* Avoid asking invalid questions of some special use domains */
725
0
        if (dns_refuse_special_use_domain(domain, question))
726
0
                return DNS_SCOPE_NO;
727
728
        /* Never go to network for the _gateway, _outbound, _localdnsstub, _localdnsproxy domain — they're something special, synthesized locally. */
729
0
        if (is_gateway_hostname(domain) ||
730
0
            is_outbound_hostname(domain) ||
731
0
            is_dns_stub_hostname(domain) ||
732
0
            is_dns_proxy_stub_hostname(domain))
733
0
                return DNS_SCOPE_NO;
734
735
        /* Don't look up the local host name via the network, unless user turned of local synthesis of it */
736
0
        if (manager_is_own_hostname(s->manager, domain) && shall_synthesize_own_hostname_rrs())
737
0
                return DNS_SCOPE_NO;
738
739
        /* Never send SOA or NS or DNSSEC request to LLMNR, where they make little sense. */
740
0
        r = dns_question_types_suitable_for_protocol(question, s->protocol);
741
0
        if (r <= 0)
742
0
                return DNS_SCOPE_NO;
743
744
0
        switch (s->protocol) {
745
746
0
        case DNS_PROTOCOL_DNS: {
747
0
                bool has_search_domains = false;
748
0
                DnsScopeMatch m;
749
0
                int n_best = -1;
750
751
0
                if (dns_name_is_root(domain)) {
752
0
                        DnsResourceKey *t;
753
0
                        bool found = false;
754
755
                        /* Refuse root name if only A and/or AAAA records are requested. */
756
757
0
                        DNS_QUESTION_FOREACH(t, question)
758
0
                                if (!IN_SET(t->type, DNS_TYPE_A, DNS_TYPE_AAAA)) {
759
0
                                        found = true;
760
0
                                        break;
761
0
                                }
762
763
0
                        if (!found)
764
0
                                return DNS_SCOPE_NO;
765
0
                }
766
767
                /* Never route things to scopes that lack DNS servers */
768
0
                if (!dns_scope_get_dns_server(s))
769
0
                        return DNS_SCOPE_NO;
770
771
                /* Always honour search domains for routing queries, except if this scope lacks DNS servers. Note that
772
                 * we return DNS_SCOPE_YES here, rather than just DNS_SCOPE_MAYBE, which means other wildcard scopes
773
                 * won't be considered anymore. */
774
0
                LIST_FOREACH(domains, d, dns_scope_get_search_domains(s)) {
775
776
0
                        if (!d->route_only && !dns_name_is_root(d->name))
777
0
                                has_search_domains = true;
778
779
0
                        if (dns_name_endswith(domain, d->name) > 0) {
780
0
                                int c;
781
782
0
                                c = dns_name_count_labels(d->name);
783
0
                                if (c < 0)
784
0
                                        continue;
785
786
0
                                if (c > n_best)
787
0
                                        n_best = c;
788
0
                        }
789
0
                }
790
791
                /* If there's a true search domain defined for this scope, and the query is single-label,
792
                 * then let's resolve things here, preferably. Note that LLMNR considers itself
793
                 * authoritative for single-label names too, at the same preference, see below. */
794
0
                if (has_search_domains && dns_name_is_single_label(domain))
795
0
                        return DNS_SCOPE_YES_BASE + 1;
796
797
                /* If ResolveUnicastSingleLabel=yes and the query is single-label, then bump match result
798
                   to prevent LLMNR monopoly among candidates. */
799
0
                if ((s->manager->resolve_unicast_single_label || (query_flags & SD_RESOLVED_RELAX_SINGLE_LABEL)) &&
800
0
                    dns_name_is_single_label(domain))
801
0
                        return DNS_SCOPE_YES_BASE + 1;
802
803
                /* Let's return the number of labels in the best matching result */
804
0
                if (n_best >= 0) {
805
0
                        assert(n_best <= DNS_SCOPE_YES_END - DNS_SCOPE_YES_BASE);
806
0
                        return DNS_SCOPE_YES_BASE + n_best;
807
0
                }
808
809
                /* Exclude link-local IP ranges */
810
0
                if (match_link_local_reverse_lookups(domain) >= DNS_SCOPE_YES_BASE ||
811
                    /* If networks use .local in their private setups, they are supposed to also add .local
812
                     * to their search domains, which we already checked above. Otherwise, we consider .local
813
                     * specific to mDNS and won't send such queries ordinary DNS servers. */
814
0
                    dns_name_endswith(domain, "local") > 0)
815
0
                        return DNS_SCOPE_NO;
816
817
                /* If the IP address to look up matches the local subnet, then implicitly synthesizes
818
                 * DNS_SCOPE_YES_BASE + 0 on this interface, i.e. preferably resolve IP addresses via the DNS
819
                 * server belonging to this interface. */
820
0
                m = match_subnet_reverse_lookups(s, domain, false);
821
0
                if (m >= 0)
822
0
                        return m;
823
824
                /* If there was no match at all, then see if this scope is suitable as default route. */
825
0
                if (!dns_scope_is_default_route(s))
826
0
                        return DNS_SCOPE_NO;
827
828
                /* Prefer suitable per-link scopes where possible */
829
0
                if (dns_server_is_fallback(dns_scope_get_dns_server(s)))
830
0
                        return DNS_SCOPE_LAST_RESORT;
831
832
0
                return DNS_SCOPE_MAYBE;
833
0
        }
834
835
0
        case DNS_PROTOCOL_MDNS: {
836
0
                DnsScopeMatch m;
837
838
0
                m = match_link_local_reverse_lookups(domain);
839
0
                if (m >= 0)
840
0
                        return m;
841
842
0
                m = match_subnet_reverse_lookups(s, domain, true);
843
0
                if (m >= 0)
844
0
                        return m;
845
846
0
                if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
847
0
                    (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
848
0
                        return DNS_SCOPE_LAST_RESORT;
849
850
0
                if ((dns_name_endswith(domain, "local") > 0 && /* only resolve names ending in .local via mDNS */
851
0
                     dns_name_equal(domain, "local") == 0 &&   /* but not the single-label "local" name itself */
852
0
                     manager_is_own_hostname(s->manager, domain) <= 0)) /* never resolve the local hostname via mDNS */
853
0
                        return DNS_SCOPE_YES_BASE + 1; /* Return +1, as the top-level .local domain matches, i.e. one label */
854
855
0
                return DNS_SCOPE_NO;
856
0
        }
857
858
0
        case DNS_PROTOCOL_LLMNR: {
859
0
                DnsScopeMatch m;
860
861
0
                m = match_link_local_reverse_lookups(domain);
862
0
                if (m >= 0)
863
0
                        return m;
864
865
0
                m = match_subnet_reverse_lookups(s, domain, true);
866
0
                if (m >= 0)
867
0
                        return m;
868
869
0
                if ((s->family == AF_INET && dns_name_endswith(domain, "in-addr.arpa") > 0) ||
870
0
                    (s->family == AF_INET6 && dns_name_endswith(domain, "ip6.arpa") > 0))
871
0
                        return DNS_SCOPE_LAST_RESORT;
872
873
0
                if ((dns_name_is_single_label(domain) && /* only resolve single label names via LLMNR */
874
0
                     dns_name_equal(domain, "local") == 0 && /* don't resolve "local" with LLMNR, it's the top-level domain of mDNS after all, see above */
875
0
                     manager_is_own_hostname(s->manager, domain) <= 0))  /* never resolve the local hostname via LLMNR */
876
0
                        return DNS_SCOPE_YES_BASE + 1; /* Return +1, as we consider ourselves authoritative
877
                                                        * for single-label names, i.e. one label. This is
878
                                                        * particularly relevant as it means a "." route on some
879
                                                        * other scope won't pull all traffic away from
880
                                                        * us. (If people actually want to pull traffic away
881
                                                        * from us they should turn off LLMNR on the
882
                                                        * link). Note that unicast DNS scopes with search
883
                                                        * domains also consider themselves authoritative for
884
                                                        * single-label domains, at the same preference (see
885
                                                        * above). */
886
887
0
                return DNS_SCOPE_NO;
888
0
        }
889
890
0
        default:
891
0
                assert_not_reached();
892
0
        }
893
0
}
894
895
0
bool dns_scope_good_key(DnsScope *s, const DnsResourceKey *key) {
896
0
        int key_family;
897
898
0
        assert(s);
899
0
        assert(key);
900
901
        /* Check if it makes sense to resolve the specified key on this scope. Note that this call assumes a
902
         * fully qualified name, i.e. the search suffixes already appended. */
903
904
0
        if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
905
0
                return false;
906
907
0
        if (s->protocol == DNS_PROTOCOL_DNS) {
908
909
                /* On classic DNS, looking up non-address RRs is always fine. (Specifically, we want to
910
                 * permit looking up DNSKEY and DS records on the root and top-level domains.) */
911
0
                if (!dns_resource_key_is_address(key))
912
0
                        return true;
913
914
                /* Unless explicitly overridden, we refuse to look up A and AAAA RRs on the root and
915
                 * single-label domains, under the assumption that those should be resolved via LLMNR or
916
                 * search path only, and should not be leaked onto the internet. */
917
0
                const char* name = dns_resource_key_name(key);
918
919
0
                if (!s->manager->resolve_unicast_single_label &&
920
0
                    dns_name_is_single_label(name))
921
0
                        return false;
922
923
0
                return !dns_name_is_root(name);
924
0
        }
925
926
        /* Never route DNSSEC RR queries to LLMNR/mDNS scopes */
927
0
        if (dns_type_is_dnssec(key->type))
928
0
                return false;
929
930
        /* On mDNS and LLMNR, send A and AAAA queries only on the respective scopes */
931
932
0
        key_family = dns_type_to_af(key->type);
933
0
        if (key_family < 0)
934
0
                return true;
935
936
0
        return key_family == s->family;
937
0
}
938
939
0
static int dns_scope_multicast_membership(DnsScope *s, bool b, struct in_addr in, struct in6_addr in6) {
940
0
        int fd;
941
942
0
        assert(s);
943
0
        assert(s->link);
944
945
0
        if (s->family == AF_INET) {
946
0
                struct ip_mreqn mreqn = {
947
0
                        .imr_multiaddr = in,
948
0
                        .imr_ifindex = s->link->ifindex,
949
0
                };
950
951
0
                if (s->protocol == DNS_PROTOCOL_LLMNR)
952
0
                        fd = manager_llmnr_ipv4_udp_fd(s->manager);
953
0
                else
954
0
                        fd = manager_mdns_ipv4_fd(s->manager);
955
956
0
                if (fd < 0)
957
0
                        return fd;
958
959
                /* Always first try to drop membership before we add
960
                 * one. This is necessary on some devices, such as
961
                 * veth. */
962
0
                if (b)
963
0
                        (void) setsockopt(fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn));
964
965
0
                if (setsockopt(fd, IPPROTO_IP, b ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, &mreqn, sizeof(mreqn)) < 0)
966
0
                        return -errno;
967
968
0
        } else if (s->family == AF_INET6) {
969
0
                struct ipv6_mreq mreq = {
970
0
                        .ipv6mr_multiaddr = in6,
971
0
                        .ipv6mr_ifindex = s->link->ifindex,
972
0
                };
973
974
0
                if (s->protocol == DNS_PROTOCOL_LLMNR)
975
0
                        fd = manager_llmnr_ipv6_udp_fd(s->manager);
976
0
                else
977
0
                        fd = manager_mdns_ipv6_fd(s->manager);
978
979
0
                if (fd < 0)
980
0
                        return fd;
981
982
0
                if (b)
983
0
                        (void) setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
984
985
0
                if (setsockopt(fd, IPPROTO_IPV6, b ? IPV6_ADD_MEMBERSHIP : IPV6_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
986
0
                        return -errno;
987
0
        } else
988
0
                return -EAFNOSUPPORT;
989
990
0
        return 0;
991
0
}
992
993
0
int dns_scope_llmnr_membership(DnsScope *s, bool b) {
994
0
        assert(s);
995
996
0
        if (s->protocol != DNS_PROTOCOL_LLMNR)
997
0
                return 0;
998
999
0
        return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
1000
0
}
1001
1002
0
int dns_scope_mdns_membership(DnsScope *s, bool b) {
1003
0
        assert(s);
1004
1005
0
        if (s->protocol != DNS_PROTOCOL_MDNS)
1006
0
                return 0;
1007
1008
0
        return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
1009
0
}
1010
1011
int dns_scope_make_reply_packet(
1012
                DnsScope *s,
1013
                uint16_t id,
1014
                int rcode,
1015
                DnsQuestion *q,
1016
                DnsAnswer *answer,
1017
                DnsAnswer *soa,
1018
                bool tentative,
1019
0
                DnsPacket **ret) {
1020
1021
0
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1022
0
        unsigned n_answer = 0, n_soa = 0;
1023
0
        int r;
1024
0
        bool c_or_aa;
1025
1026
0
        assert(s);
1027
0
        assert(ret);
1028
1029
0
        if (dns_question_isempty(q) &&
1030
0
            dns_answer_isempty(answer) &&
1031
0
            dns_answer_isempty(soa))
1032
0
                return -EINVAL;
1033
1034
0
        r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1035
0
        if (r < 0)
1036
0
                return r;
1037
1038
        /* mDNS answers must have the Authoritative Answer bit set, see RFC 6762, section 18.4. */
1039
0
        c_or_aa = s->protocol == DNS_PROTOCOL_MDNS;
1040
1041
0
        DNS_PACKET_HEADER(p)->id = id;
1042
0
        DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1043
0
                                                              1 /* qr */,
1044
0
                                                              0 /* opcode */,
1045
0
                                                              c_or_aa,
1046
0
                                                              0 /* tc */,
1047
0
                                                              tentative,
1048
0
                                                              0 /* (ra) */,
1049
0
                                                              0 /* (ad) */,
1050
0
                                                              0 /* (cd) */,
1051
0
                                                              rcode));
1052
1053
0
        r = dns_packet_append_question(p, q);
1054
0
        if (r < 0)
1055
0
                return r;
1056
0
        DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
1057
1058
0
        r = dns_packet_append_answer(p, answer, &n_answer);
1059
0
        if (r < 0)
1060
0
                return r;
1061
0
        DNS_PACKET_HEADER(p)->ancount = htobe16(n_answer);
1062
1063
0
        r = dns_packet_append_answer(p, soa, &n_soa);
1064
0
        if (r < 0)
1065
0
                return r;
1066
0
        DNS_PACKET_HEADER(p)->arcount = htobe16(n_soa);
1067
1068
0
        *ret = TAKE_PTR(p);
1069
1070
0
        return 0;
1071
0
}
1072
1073
0
static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
1074
0
        DnsResourceRecord *rr;
1075
0
        DnsResourceKey *key;
1076
1077
0
        assert(s);
1078
0
        assert(p);
1079
1080
0
        DNS_QUESTION_FOREACH(key, p->question)
1081
0
                dns_zone_verify_conflicts(&s->zone, key);
1082
1083
0
        DNS_ANSWER_FOREACH(rr, p->answer)
1084
0
                dns_zone_verify_conflicts(&s->zone, rr->key);
1085
0
}
1086
1087
0
void dns_scope_process_query(DnsScope *s, DnsStream *stream, DnsPacket *p) {
1088
0
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL, *soa = NULL;
1089
0
        _cleanup_(dns_packet_unrefp) DnsPacket *reply = NULL;
1090
0
        DnsResourceKey *key = NULL;
1091
0
        bool tentative = false;
1092
0
        int r;
1093
1094
0
        assert(s);
1095
0
        assert(p);
1096
1097
0
        if (p->protocol != DNS_PROTOCOL_LLMNR)
1098
0
                return;
1099
1100
0
        if (p->ipproto == IPPROTO_UDP) {
1101
                /* Don't accept UDP queries directed to anything but
1102
                 * the LLMNR multicast addresses. See RFC 4795,
1103
                 * section 2.5. */
1104
1105
0
                if (p->family == AF_INET && !in4_addr_equal(&p->destination.in, &LLMNR_MULTICAST_IPV4_ADDRESS))
1106
0
                        return;
1107
1108
0
                if (p->family == AF_INET6 && !in6_addr_equal(&p->destination.in6, &LLMNR_MULTICAST_IPV6_ADDRESS))
1109
0
                        return;
1110
0
        }
1111
1112
0
        r = dns_packet_extract(p);
1113
0
        if (r < 0) {
1114
0
                log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
1115
0
                return;
1116
0
        }
1117
1118
0
        if (DNS_PACKET_LLMNR_C(p)) {
1119
                /* Somebody notified us about a possible conflict */
1120
0
                dns_scope_verify_conflicts(s, p);
1121
0
                return;
1122
0
        }
1123
1124
0
        if (dns_question_size(p->question) != 1)
1125
0
                return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
1126
1127
0
        key = dns_question_first_key(p->question);
1128
1129
0
        r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
1130
0
        if (r < 0) {
1131
0
                log_debug_errno(r, "Failed to look up key: %m");
1132
0
                return;
1133
0
        }
1134
0
        if (r == 0)
1135
0
                return;
1136
1137
0
        if (answer)
1138
0
                dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
1139
1140
0
        r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
1141
0
        if (r < 0) {
1142
0
                log_debug_errno(r, "Failed to build reply packet: %m");
1143
0
                return;
1144
0
        }
1145
1146
0
        if (stream) {
1147
0
                r = dns_stream_write_packet(stream, reply);
1148
0
                if (r < 0) {
1149
0
                        log_debug_errno(r, "Failed to enqueue reply packet: %m");
1150
0
                        return;
1151
0
                }
1152
1153
                /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
1154
                 * will be dangling until the stream is disconnected, and the default completion handler of the stream
1155
                 * will then unref the stream and destroy it */
1156
0
                if (DNS_STREAM_QUEUED(stream))
1157
0
                        dns_stream_ref(stream);
1158
0
        } else {
1159
0
                int fd;
1160
1161
0
                if (!ratelimit_below(&s->ratelimit))
1162
0
                        return;
1163
1164
0
                if (p->family == AF_INET)
1165
0
                        fd = manager_llmnr_ipv4_udp_fd(s->manager);
1166
0
                else if (p->family == AF_INET6)
1167
0
                        fd = manager_llmnr_ipv6_udp_fd(s->manager);
1168
0
                else {
1169
0
                        log_debug("Unknown protocol");
1170
0
                        return;
1171
0
                }
1172
0
                if (fd < 0) {
1173
0
                        log_debug_errno(fd, "Failed to get reply socket: %m");
1174
0
                        return;
1175
0
                }
1176
1177
                /* Note that we always immediately reply to all LLMNR
1178
                 * requests, and do not wait any time, since we
1179
                 * verified uniqueness for all records. Also see RFC
1180
                 * 4795, Section 2.7 */
1181
1182
0
                r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
1183
0
                if (r < 0) {
1184
0
                        log_debug_errno(r, "Failed to send reply packet: %m");
1185
0
                        return;
1186
0
                }
1187
0
        }
1188
0
}
1189
1190
DnsTransaction *dns_scope_find_transaction(
1191
                DnsScope *scope,
1192
                DnsResourceKey *key,
1193
0
                uint64_t query_flags) {
1194
1195
0
        DnsTransaction *first;
1196
1197
0
        assert(scope);
1198
0
        assert(key);
1199
1200
        /* Iterate through the list of transactions with a matching key */
1201
0
        first = hashmap_get(scope->transactions_by_key, key);
1202
0
        LIST_FOREACH(transactions_by_key, t, first) {
1203
1204
                /* These four flags must match exactly: we cannot use a validated response for a
1205
                 * non-validating client, and we cannot use a non-validated response for a validating
1206
                 * client. Similar, if the sources don't match things aren't usable either. */
1207
0
                if (((query_flags ^ t->query_flags) &
1208
0
                     (SD_RESOLVED_NO_VALIDATE|
1209
0
                     SD_RESOLVED_NO_ZONE|
1210
0
                      SD_RESOLVED_NO_TRUST_ANCHOR|
1211
0
                      SD_RESOLVED_NO_NETWORK)) != 0)
1212
0
                        continue;
1213
1214
                /* We can reuse a primary query if a regular one is requested, but not vice versa */
1215
0
                if ((query_flags & SD_RESOLVED_REQUIRE_PRIMARY) &&
1216
0
                    !(t->query_flags & SD_RESOLVED_REQUIRE_PRIMARY))
1217
0
                        continue;
1218
1219
                /* Don't reuse a transaction that allowed caching when we got told not to use it */
1220
0
                if ((query_flags & SD_RESOLVED_NO_CACHE) &&
1221
0
                    !(t->query_flags & SD_RESOLVED_NO_CACHE))
1222
0
                        continue;
1223
1224
                /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
1225
                 * reuse */
1226
0
                if ((query_flags & SD_RESOLVED_CLAMP_TTL) &&
1227
0
                    !(t->query_flags & SD_RESOLVED_CLAMP_TTL))
1228
0
                        continue;
1229
1230
0
                return t;
1231
0
        }
1232
1233
0
        return NULL;
1234
0
}
1235
1236
static int dns_scope_make_conflict_packet(
1237
                DnsScope *s,
1238
                DnsResourceRecord *rr,
1239
0
                DnsPacket **ret) {
1240
1241
0
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1242
0
        int r;
1243
1244
0
        assert(s);
1245
0
        assert(rr);
1246
0
        assert(ret);
1247
1248
0
        r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
1249
0
        if (r < 0)
1250
0
                return r;
1251
1252
0
        DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
1253
0
                                                              0 /* qr */,
1254
0
                                                              0 /* opcode */,
1255
0
                                                              1 /* conflict */,
1256
0
                                                              0 /* tc */,
1257
0
                                                              0 /* t */,
1258
0
                                                              0 /* (ra) */,
1259
0
                                                              0 /* (ad) */,
1260
0
                                                              0 /* (cd) */,
1261
0
                                                              0));
1262
1263
        /* For mDNS, the transaction ID should always be 0 */
1264
0
        if (s->protocol != DNS_PROTOCOL_MDNS)
1265
0
                random_bytes(&DNS_PACKET_HEADER(p)->id, sizeof(uint16_t));
1266
1267
0
        DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
1268
0
        DNS_PACKET_HEADER(p)->arcount = htobe16(1);
1269
1270
0
        r = dns_packet_append_key(p, rr->key, 0, NULL);
1271
0
        if (r < 0)
1272
0
                return r;
1273
1274
0
        r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
1275
0
        if (r < 0)
1276
0
                return r;
1277
1278
0
        *ret = TAKE_PTR(p);
1279
1280
0
        return 0;
1281
0
}
1282
1283
0
static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
1284
0
        DnsScope *scope = ASSERT_PTR(userdata);
1285
0
        int r;
1286
1287
0
        assert(es);
1288
1289
0
        scope->conflict_event_source = sd_event_source_disable_unref(scope->conflict_event_source);
1290
1291
0
        for (;;) {
1292
0
                _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1293
0
                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1294
0
                _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1295
1296
0
                rr = ordered_hashmap_steal_first_key_and_value(scope->conflict_queue, (void**) &key);
1297
0
                if (!rr)
1298
0
                        break;
1299
1300
0
                r = dns_scope_make_conflict_packet(scope, rr, &p);
1301
0
                if (r < 0) {
1302
0
                        log_error_errno(r, "Failed to make conflict packet: %m");
1303
0
                        return 0;
1304
0
                }
1305
1306
0
                r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1307
0
                if (r < 0)
1308
0
                        log_debug_errno(r, "Failed to send conflict packet: %m");
1309
0
        }
1310
1311
0
        return 0;
1312
0
}
1313
1314
0
int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
1315
0
        int r;
1316
1317
0
        assert(scope);
1318
0
        assert(rr);
1319
1320
        /* We don't send these queries immediately. Instead, we queue them, and send them after some jitter
1321
         * delay.  We only place one RR per key in the conflict messages, not all of them. That should be
1322
         * enough to indicate where there might be a conflict */
1323
0
        r = ordered_hashmap_ensure_put(&scope->conflict_queue, &dns_resource_record_hash_ops_by_key, rr->key, rr);
1324
0
        if (IN_SET(r, 0, -EEXIST))
1325
0
                return 0;
1326
0
        if (r < 0)
1327
0
                return log_debug_errno(r, "Failed to queue conflicting RR: %m");
1328
1329
0
        dns_resource_key_ref(rr->key);
1330
0
        dns_resource_record_ref(rr);
1331
1332
0
        if (scope->conflict_event_source)
1333
0
                return 0;
1334
1335
0
        r = sd_event_add_time_relative(
1336
0
                        scope->manager->event,
1337
0
                        &scope->conflict_event_source,
1338
0
                        CLOCK_BOOTTIME,
1339
0
                        random_u64_range(LLMNR_JITTER_INTERVAL_USEC),
1340
0
                        0,
1341
0
                        on_conflict_dispatch, scope);
1342
0
        if (r < 0)
1343
0
                return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
1344
1345
0
        (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
1346
1347
0
        return 0;
1348
0
}
1349
1350
0
void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
1351
0
        DnsResourceRecord *rr;
1352
0
        int r;
1353
1354
0
        assert(scope);
1355
0
        assert(p);
1356
1357
0
        if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
1358
0
                return;
1359
1360
0
        if (DNS_PACKET_RRCOUNT(p) <= 0)
1361
0
                return;
1362
1363
0
        if (p->protocol == DNS_PROTOCOL_LLMNR) {
1364
0
                if (DNS_PACKET_LLMNR_C(p) != 0)
1365
0
                        return;
1366
1367
0
                if (DNS_PACKET_LLMNR_T(p) != 0)
1368
0
                        return;
1369
0
        }
1370
1371
0
        if (manager_packet_from_local_address(scope->manager, p))
1372
0
                return;
1373
1374
0
        r = dns_packet_extract(p);
1375
0
        if (r < 0) {
1376
0
                log_debug_errno(r, "Failed to extract packet: %m");
1377
0
                return;
1378
0
        }
1379
1380
0
        log_debug("Checking for conflicts...");
1381
1382
0
        DNS_ANSWER_FOREACH(rr, p->answer) {
1383
                /* No conflict if it is DNS-SD RR used for service enumeration. */
1384
0
                if (dns_resource_key_is_dnssd_ptr(rr->key))
1385
0
                        continue;
1386
1387
                /* Check for conflicts against the local zone. If we
1388
                 * found one, we won't check any further */
1389
0
                r = dns_zone_check_conflicts(&scope->zone, rr);
1390
0
                if (r != 0)
1391
0
                        continue;
1392
1393
                /* Check for conflicts against the local cache. If so,
1394
                 * send out an advisory query, to inform everybody */
1395
0
                r = dns_cache_check_conflicts(&scope->cache, rr, p->family, &p->sender);
1396
0
                if (r <= 0)
1397
0
                        continue;
1398
1399
0
                dns_scope_notify_conflict(scope, rr);
1400
0
        }
1401
0
}
1402
1403
0
void dns_scope_dump(DnsScope *s, FILE *f) {
1404
0
        assert(s);
1405
1406
0
        if (!f)
1407
0
                f = stdout;
1408
1409
0
        fputs("[Scope protocol=", f);
1410
0
        fputs(dns_protocol_to_string(s->protocol), f);
1411
1412
0
        if (s->link) {
1413
0
                fputs(" interface=", f);
1414
0
                fputs(s->link->ifname, f);
1415
0
        }
1416
1417
0
        if (s->family != AF_UNSPEC) {
1418
0
                fputs(" family=", f);
1419
0
                fputs(af_to_name(s->family), f);
1420
0
        }
1421
1422
0
        fputs(" origin=", f);
1423
0
        fputs(dns_scope_origin_to_string(s->origin), f);
1424
1425
0
        if (s->delegate) {
1426
0
                fputs(" id=", f);
1427
0
                fputs(s->delegate->id, f);
1428
0
        }
1429
1430
0
        if (s->protocol == DNS_PROTOCOL_DNS) {
1431
0
                fputs(" DNSSEC=", f);
1432
0
                fputs(dnssec_mode_to_string(s->dnssec_mode), f);
1433
1434
0
                fputs(" DNSOverTLS=", f);
1435
0
                fputs(dns_over_tls_mode_to_string(s->dns_over_tls_mode), f);
1436
0
        }
1437
1438
0
        fputs("]\n", f);
1439
1440
0
        if (!dns_zone_is_empty(&s->zone)) {
1441
0
                fputs("ZONE:\n", f);
1442
0
                dns_zone_dump(&s->zone, f);
1443
0
        }
1444
1445
0
        if (!dns_cache_is_empty(&s->cache)) {
1446
0
                fputs("CACHE:\n", f);
1447
0
                dns_cache_dump(&s->cache, f);
1448
0
        }
1449
0
}
1450
1451
0
DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
1452
0
        assert(s);
1453
1454
0
        if (s->protocol != DNS_PROTOCOL_DNS)
1455
0
                return NULL;
1456
1457
0
        if (s->link)
1458
0
                return s->link->search_domains;
1459
0
        if (s->delegate)
1460
0
                return s->delegate->search_domains;
1461
1462
0
        return s->manager->search_domains;
1463
0
}
1464
1465
0
bool dns_scope_name_wants_search_domain(DnsScope *s, const char *name) {
1466
0
        assert(s);
1467
1468
0
        if (s->protocol != DNS_PROTOCOL_DNS)
1469
0
                return false;
1470
1471
0
        if (!dns_name_is_single_label(name))
1472
0
                return false;
1473
1474
        /* If we allow single-label domain lookups on unicast DNS, and this scope has a search domain that matches
1475
         * _exactly_ this name, then do not use search domains. */
1476
0
        if (s->manager->resolve_unicast_single_label)
1477
0
                LIST_FOREACH(domains, d, dns_scope_get_search_domains(s))
1478
0
                        if (dns_name_equal(name, d->name) > 0)
1479
0
                                return false;
1480
1481
0
        return true;
1482
0
}
1483
1484
0
bool dns_scope_network_good(DnsScope *s) {
1485
        /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
1486
         * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
1487
         * DNS scope we check whether there are any links that are up and have an address.
1488
         *
1489
         * Note that Linux routing is complex and even systems that superficially have no IPv4 address might
1490
         * be able to route IPv4 (and similar for IPv6), hence let's make a check here independent of address
1491
         * family. */
1492
1493
0
        if (s->link)
1494
0
                return true;
1495
1496
0
        return manager_routable(s->manager);
1497
0
}
1498
1499
0
int dns_scope_ifindex(DnsScope *s) {
1500
0
        assert(s);
1501
1502
0
        if (s->link)
1503
0
                return s->link->ifindex;
1504
1505
0
        return 0;
1506
0
}
1507
1508
0
const char* dns_scope_ifname(DnsScope *s) {
1509
0
        assert(s);
1510
1511
0
        if (s->link)
1512
0
                return s->link->ifname;
1513
1514
0
        return NULL;
1515
0
}
1516
1517
0
static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
1518
0
        DnsScope *scope = userdata;
1519
1520
0
        assert(s);
1521
1522
0
        scope->announce_event_source = sd_event_source_disable_unref(scope->announce_event_source);
1523
1524
0
        (void) dns_scope_announce(scope, false);
1525
0
        return 0;
1526
0
}
1527
1528
0
int dns_scope_announce(DnsScope *scope, bool goodbye) {
1529
0
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
1530
0
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
1531
0
        _cleanup_set_free_ Set *types = NULL;
1532
0
        DnsZoneItem *z;
1533
0
        unsigned size = 0;
1534
0
        char *service_type;
1535
0
        int r;
1536
1537
0
        if (!scope)
1538
0
                return 0;
1539
1540
0
        if (scope->protocol != DNS_PROTOCOL_MDNS)
1541
0
                return 0;
1542
1543
0
        r = sd_event_get_state(scope->manager->event);
1544
0
        if (r < 0)
1545
0
                return log_debug_errno(r, "Failed to get event loop state: %m");
1546
1547
        /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
1548
0
        if (r == SD_EVENT_FINISHED)
1549
0
                return 0;
1550
1551
        /* Check if we're done with probing. */
1552
0
        LIST_FOREACH(transactions_by_scope, t, scope->transactions)
1553
0
                if (t->probing && DNS_TRANSACTION_IS_LIVE(t->state))
1554
0
                        return 0;
1555
1556
        /* Check if there're services pending conflict resolution. */
1557
0
        if (manager_next_dnssd_names(scope->manager))
1558
0
                return 0; /* we reach this point only if changing hostname didn't help */
1559
1560
        /* Calculate answer's size. */
1561
0
        HASHMAP_FOREACH(z, scope->zone.by_key) {
1562
0
                if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
1563
0
                        continue;
1564
1565
0
                if (z->rr->key->type == DNS_TYPE_PTR &&
1566
0
                    !dns_zone_contains_name(&scope->zone, z->rr->ptr.name)) {
1567
0
                        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
1568
1569
0
                        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));
1570
0
                        z->state = DNS_ZONE_ITEM_WITHDRAWN;
1571
0
                        continue;
1572
0
                }
1573
1574
                /* Collect service types for _services._dns-sd._udp.local RRs in a set. Only two-label names
1575
                 * (not selective names) are considered according to RFC6763 § 9. */
1576
0
                if (!scope->announced &&
1577
0
                    dns_resource_key_is_dnssd_two_label_ptr(z->rr->key)) {
1578
0
                        if (!set_contains(types, dns_resource_key_name(z->rr->key))) {
1579
0
                                r = set_ensure_put(&types, &dns_name_hash_ops, dns_resource_key_name(z->rr->key));
1580
0
                                if (r < 0)
1581
0
                                        return log_debug_errno(r, "Failed to add item to set: %m");
1582
0
                        }
1583
0
                }
1584
1585
0
                LIST_FOREACH(by_key, i, z)
1586
0
                        size++;
1587
0
        }
1588
1589
0
        answer = dns_answer_new(size + set_size(types));
1590
0
        if (!answer)
1591
0
                return log_oom();
1592
1593
        /* Second iteration, actually add RRs to the answer. */
1594
0
        HASHMAP_FOREACH(z, scope->zone.by_key)
1595
0
                LIST_FOREACH (by_key, i, z) {
1596
0
                        DnsAnswerFlags flags;
1597
1598
0
                        if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
1599
0
                                continue;
1600
1601
0
                        if (dns_resource_key_is_dnssd_ptr(i->rr->key))
1602
0
                                flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
1603
0
                        else
1604
0
                                flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
1605
1606
0
                        r = dns_answer_add(answer, i->rr, 0, flags, NULL);
1607
0
                        if (r < 0)
1608
0
                                return log_debug_errno(r, "Failed to add RR to announce: %m");
1609
0
                }
1610
1611
        /* Since all the active services are in the zone make them discoverable now. */
1612
0
        SET_FOREACH(service_type, types) {
1613
0
                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
1614
1615
0
                rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
1616
0
                                                  "_services._dns-sd._udp.local");
1617
0
                if (!rr)
1618
0
                        return log_oom();
1619
1620
0
                rr->ptr.name = strdup(service_type);
1621
0
                if (!rr->ptr.name)
1622
0
                        return log_oom();
1623
1624
0
                rr->ttl = MDNS_DEFAULT_TTL;
1625
1626
0
                r = dns_zone_put(&scope->zone, scope, rr, false);
1627
0
                if (r < 0)
1628
0
                        log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
1629
1630
0
                r = dns_answer_add(answer, rr, 0, 0, NULL);
1631
0
                if (r < 0)
1632
0
                        return log_debug_errno(r, "Failed to add RR to announce: %m");
1633
0
        }
1634
1635
0
        if (dns_answer_isempty(answer))
1636
0
                return 0;
1637
1638
0
        r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
1639
0
        if (r < 0)
1640
0
                return log_debug_errno(r, "Failed to build reply packet: %m");
1641
1642
0
        r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
1643
0
        if (r < 0)
1644
0
                return log_debug_errno(r, "Failed to send reply packet: %m");
1645
1646
        /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
1647
         * responses, one second apart." */
1648
0
        if (!scope->announced) {
1649
0
                scope->announced = true;
1650
1651
0
                r = sd_event_add_time_relative(
1652
0
                                scope->manager->event,
1653
0
                                &scope->announce_event_source,
1654
0
                                CLOCK_BOOTTIME,
1655
0
                                MDNS_ANNOUNCE_DELAY,
1656
0
                                0,
1657
0
                                on_announcement_timeout, scope);
1658
0
                if (r < 0)
1659
0
                        return log_debug_errno(r, "Failed to schedule second announcement: %m");
1660
1661
0
                (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
1662
0
        }
1663
1664
0
        return 0;
1665
0
}
1666
1667
0
int dns_scope_add_dnssd_registered_services(DnsScope *scope) {
1668
0
        DnssdRegisteredService *service;
1669
0
        int r;
1670
1671
0
        assert(scope);
1672
1673
0
        if (hashmap_isempty(scope->manager->dnssd_registered_services))
1674
0
                return 0;
1675
1676
0
        scope->announced = false;
1677
1678
0
        HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
1679
0
                service->withdrawn = false;
1680
1681
0
                r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
1682
0
                if (r < 0)
1683
0
                        log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
1684
1685
0
                if (service->sub_ptr_rr) {
1686
0
                        r = dns_zone_put(&scope->zone, scope, service->sub_ptr_rr, false);
1687
0
                        if (r < 0)
1688
0
                                log_warning_errno(r, "Failed to add selective PTR record to MDNS zone: %m");
1689
0
                }
1690
1691
0
                r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
1692
0
                if (r < 0)
1693
0
                        log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
1694
1695
0
                LIST_FOREACH(items, txt_data, service->txt_data_items) {
1696
0
                        r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
1697
0
                        if (r < 0)
1698
0
                                log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
1699
0
                }
1700
0
        }
1701
1702
0
        return 0;
1703
0
}
1704
1705
0
int dns_scope_remove_dnssd_registered_services(DnsScope *scope) {
1706
0
        _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
1707
0
        DnssdRegisteredService *service;
1708
0
        int r;
1709
1710
0
        assert(scope);
1711
1712
0
        key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
1713
0
                                   "_services._dns-sd._udp.local");
1714
0
        if (!key)
1715
0
                return log_oom();
1716
1717
0
        r = dns_zone_remove_rrs_by_key(&scope->zone, key);
1718
0
        if (r < 0)
1719
0
                return r;
1720
1721
0
        HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
1722
0
                dns_zone_remove_rr(&scope->zone, service->ptr_rr);
1723
0
                dns_zone_remove_rr(&scope->zone, service->sub_ptr_rr);
1724
0
                dns_zone_remove_rr(&scope->zone, service->srv_rr);
1725
0
                LIST_FOREACH(items, txt_data, service->txt_data_items)
1726
0
                        dns_zone_remove_rr(&scope->zone, txt_data->rr);
1727
0
        }
1728
1729
0
        return 0;
1730
0
}
1731
1732
0
static bool dns_scope_has_route_only_domains(DnsScope *scope) {
1733
0
        DnsSearchDomain *first;
1734
0
        bool route_only = false;
1735
1736
0
        assert(scope);
1737
0
        assert(scope->protocol == DNS_PROTOCOL_DNS);
1738
1739
        /* Returns 'true' if this scope is suitable for queries to specific domains only. For that we check
1740
         * if there are any route-only domains on this interface, as a heuristic to discern VPN-style links
1741
         * from non-VPN-style links. Returns 'false' for all other cases, i.e. if the scope is intended to
1742
         * take queries to arbitrary domains, i.e. has no routing domains set. */
1743
1744
0
        if (scope->link)
1745
0
                first = scope->link->search_domains;
1746
0
        else if (scope->delegate)
1747
0
                first = scope->delegate->search_domains;
1748
0
        else
1749
0
                first = scope->manager->search_domains;
1750
1751
0
        LIST_FOREACH(domains, domain, first) {
1752
                /* "." means "any domain", thus the interface takes any kind of traffic. Thus, we exit early
1753
                 * here, as it doesn't really matter whether this link has any route-only domains or not,
1754
                 * "~."  really trumps everything and clearly indicates that this interface shall receive all
1755
                 * traffic it can get. */
1756
0
                if (dns_name_is_root(DNS_SEARCH_DOMAIN_NAME(domain)))
1757
0
                        return false;
1758
1759
0
                if (domain->route_only)
1760
0
                        route_only = true;
1761
0
        }
1762
1763
0
        return route_only;
1764
0
}
1765
1766
0
bool dns_scope_is_default_route(DnsScope *scope) {
1767
0
        assert(scope);
1768
1769
        /* Only use DNS scopes as default routes */
1770
0
        if (scope->protocol != DNS_PROTOCOL_DNS)
1771
0
                return false;
1772
1773
0
        if (scope->link) {
1774
1775
                /* Honour whatever is explicitly configured. This is really the best approach, and trumps any
1776
                 * automatic logic. */
1777
0
                if (scope->link->default_route >= 0)
1778
0
                        return scope->link->default_route;
1779
1780
                /* Otherwise check if we have any route-only domains, as a sensible heuristic: if so, let's not
1781
                 * volunteer as default route. */
1782
0
                return !dns_scope_has_route_only_domains(scope);
1783
1784
0
        } else  if (scope->delegate) {
1785
1786
0
                if (scope->delegate->default_route >= 0)
1787
0
                        return scope->delegate->default_route;
1788
1789
                /* Delegates are by default not used as default route */
1790
0
                return false;
1791
0
        } else
1792
                /* The global DNS scope is always suitable as default route */
1793
0
                return true;
1794
0
}
1795
1796
0
int dns_scope_to_json(DnsScope *scope, bool with_cache, sd_json_variant **ret) {
1797
0
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *cache = NULL;
1798
0
        int r;
1799
1800
0
        assert(scope);
1801
0
        assert(ret);
1802
1803
0
        if (with_cache) {
1804
0
                r = dns_cache_dump_to_json(&scope->cache, &cache);
1805
0
                if (r < 0)
1806
0
                        return r;
1807
0
        }
1808
1809
0
        return sd_json_buildo(
1810
0
                        ret,
1811
0
                        SD_JSON_BUILD_PAIR_STRING("protocol", dns_protocol_to_string(scope->protocol)),
1812
0
                        SD_JSON_BUILD_PAIR_CONDITION(scope->family != AF_UNSPEC, "family", SD_JSON_BUILD_INTEGER(scope->family)),
1813
0
                        SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifindex", SD_JSON_BUILD_INTEGER(dns_scope_ifindex(scope))),
1814
0
                        SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifname", SD_JSON_BUILD_STRING(dns_scope_ifname(scope))),
1815
0
                        SD_JSON_BUILD_PAIR_CONDITION(with_cache, "cache", SD_JSON_BUILD_VARIANT(cache)),
1816
0
                        SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
1817
0
                                                     "dnssec",
1818
0
                                                     SD_JSON_BUILD_STRING(dnssec_mode_to_string(scope->dnssec_mode))),
1819
0
                        SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
1820
0
                                                     "dnsOverTLS",
1821
0
                                                     SD_JSON_BUILD_STRING(dns_over_tls_mode_to_string(scope->dns_over_tls_mode))));
1822
0
}
1823
1824
0
int dns_type_suitable_for_protocol(uint16_t type, DnsProtocol protocol) {
1825
1826
        /* Tests whether it makes sense to route queries for the specified DNS RR types to the specified
1827
         * protocol. For classic DNS pretty much all RR types are suitable, but for LLMNR/mDNS let's
1828
         * allowlist only a few that make sense. We use this when routing queries so that we can more quickly
1829
         * return errors for queries that will almost certainly fail/time out otherwise. For example, this
1830
         * ensures that SOA, NS, or DS/DNSKEY queries are never routed to mDNS/LLMNR where they simply make
1831
         * no sense. */
1832
1833
0
        if (dns_type_is_obsolete(type))
1834
0
                return false;
1835
1836
0
        if (!dns_type_is_valid_query(type))
1837
0
                return false;
1838
1839
0
        switch (protocol) {
1840
1841
0
        case DNS_PROTOCOL_DNS:
1842
0
                return true;
1843
1844
0
        case DNS_PROTOCOL_LLMNR:
1845
0
                return IN_SET(type,
1846
0
                              DNS_TYPE_ANY,
1847
0
                              DNS_TYPE_A,
1848
0
                              DNS_TYPE_AAAA,
1849
0
                              DNS_TYPE_CNAME,
1850
0
                              DNS_TYPE_PTR,
1851
0
                              DNS_TYPE_TXT);
1852
1853
0
        case DNS_PROTOCOL_MDNS:
1854
0
                return IN_SET(type,
1855
0
                              DNS_TYPE_ANY,
1856
0
                              DNS_TYPE_A,
1857
0
                              DNS_TYPE_AAAA,
1858
0
                              DNS_TYPE_CNAME,
1859
0
                              DNS_TYPE_PTR,
1860
0
                              DNS_TYPE_TXT,
1861
0
                              DNS_TYPE_SRV,
1862
0
                              DNS_TYPE_NSEC,
1863
0
                              DNS_TYPE_HINFO);
1864
1865
0
        default:
1866
0
                return -EPROTONOSUPPORT;
1867
0
        }
1868
0
}
1869
1870
0
int dns_question_types_suitable_for_protocol(DnsQuestion *q, DnsProtocol protocol) {
1871
0
        DnsResourceKey *key;
1872
0
        int r;
1873
1874
        /* Tests whether the types in the specified question make any sense to be routed to the specified
1875
         * protocol, i.e. if dns_type_suitable_for_protocol() is true for any of the contained RR types */
1876
1877
0
        DNS_QUESTION_FOREACH(key, q) {
1878
0
                r = dns_type_suitable_for_protocol(key->type, protocol);
1879
0
                if (r != 0)
1880
0
                        return r;
1881
0
        }
1882
1883
0
        return false;
1884
0
}
1885
1886
static const char* const dns_scope_origin_table[_DNS_SCOPE_ORIGIN_MAX] = {
1887
        [DNS_SCOPE_GLOBAL]   = "global",
1888
        [DNS_SCOPE_LINK]     = "link",
1889
        [DNS_SCOPE_DELEGATE] = "delegate",
1890
};
1891
1892
DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin, DnsScopeOrigin);