HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/resolve/resolved-dns-scope.c

74,476 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 2a030ba30c867926f460b8b6ac35e0790f983a3e

Lines 1001–1946 of 1,946

int dns_scope_llmnr_membership(DnsScope *s, bool b) {
        assert(s);
 
        if (s->protocol != DNS_PROTOCOL_LLMNR)
                return 0;
 
        return dns_scope_multicast_membership(s, b, LLMNR_MULTICAST_IPV4_ADDRESS, LLMNR_MULTICAST_IPV6_ADDRESS);
}
 
int dns_scope_mdns_membership(DnsScope *s, bool b) {
        assert(s);
 
        if (s->protocol != DNS_PROTOCOL_MDNS)
                return 0;
 
        return dns_scope_multicast_membership(s, b, MDNS_MULTICAST_IPV4_ADDRESS, MDNS_MULTICAST_IPV6_ADDRESS);
}
 
int dns_scope_make_reply_packet(
                DnsScope *s,
                uint16_t id,
                int rcode,
                DnsQuestion *q,
                DnsAnswer *answer,
                DnsAnswer *soa,
                bool tentative,
                DnsPacket **ret) {
 
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
        unsigned n_answer = 0, n_soa = 0;
        int r;
        bool c_or_aa;
 
        assert(s);
        assert(ret);
 
        if (dns_question_isempty(q) &&
            dns_answer_isempty(answer) &&
            dns_answer_isempty(soa))
                return -EINVAL;
 
        r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
        if (r < 0)
                return r;
 
        /* mDNS answers must have the Authoritative Answer bit set, see RFC 6762, section 18.4. */
        c_or_aa = s->protocol == DNS_PROTOCOL_MDNS;
 
        DNS_PACKET_HEADER(p)->id = id;
        DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
                                                              1 /* qr */,
                                                              0 /* opcode */,
                                                              c_or_aa,
                                                              0 /* tc */,
                                                              tentative,
                                                              0 /* (ra) */,
                                                              0 /* (ad) */,
                                                              0 /* (cd) */,
                                                              rcode));
 
        r = dns_packet_append_question(p, q);
        if (r < 0)
                return r;
        DNS_PACKET_HEADER(p)->qdcount = htobe16(dns_question_size(q));
 
        r = dns_packet_append_answer(p, answer, &n_answer);
        if (r < 0)
                return r;
        DNS_PACKET_HEADER(p)->ancount = htobe16(n_answer);
 
        r = dns_packet_append_answer(p, soa, &n_soa);
        if (r < 0)
                return r;
        DNS_PACKET_HEADER(p)->arcount = htobe16(n_soa);
 
        *ret = TAKE_PTR(p);
 
        return 0;
}
 
static void dns_scope_verify_conflicts(DnsScope *s, DnsPacket *p) {
        DnsResourceRecord *rr;
        DnsResourceKey *key;
 
        assert(s);
        assert(p);
 
        DNS_QUESTION_FOREACH(key, p->question)
                dns_zone_verify_conflicts(&s->zone, key);
 
        DNS_ANSWER_FOREACH(rr, p->answer)
                dns_zone_verify_conflicts(&s->zone, rr->key);
}
 
void dns_scope_process_query(DnsScope *s, DnsStream *stream, DnsPacket *p) {
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL, *soa = NULL;
        _cleanup_(dns_packet_unrefp) DnsPacket *reply = NULL;
        DnsResourceKey *key = NULL;
        bool tentative = false;
        int r;
 
        assert(s);
        assert(p);
 
        if (p->protocol != DNS_PROTOCOL_LLMNR)
                return;
 
        if (p->ipproto == IPPROTO_UDP) {
                /* Don't accept UDP queries directed to anything but
                 * the LLMNR multicast addresses. See RFC 4795,
                 * section 2.5. */
 
                if (p->family == AF_INET && !in4_addr_equal(&p->destination.in, &LLMNR_MULTICAST_IPV4_ADDRESS))
                        return;
 
                if (p->family == AF_INET6 && !in6_addr_equal(&p->destination.in6, &LLMNR_MULTICAST_IPV6_ADDRESS))
                        return;
        }
 
        r = dns_packet_extract(p);
        if (r < 0) {
                log_debug_errno(r, "Failed to extract resource records from incoming packet: %m");
                return;
        }
 
        if (DNS_PACKET_LLMNR_C(p)) {
                /* Somebody notified us about a possible conflict */
                dns_scope_verify_conflicts(s, p);
                return;
        }
 
        if (dns_question_size(p->question) != 1)
                return (void) log_debug("Received LLMNR query without question or multiple questions, ignoring.");
 
        key = dns_question_first_key(p->question);
 
        r = dns_zone_lookup(&s->zone, key, 0, &answer, &soa, &tentative);
        if (r < 0) {
                log_debug_errno(r, "Failed to look up key: %m");
                return;
        }
        if (r == 0)
                return;
 
        if (answer)
                dns_answer_order_by_scope(answer, in_addr_is_link_local(p->family, &p->sender) > 0);
 
        r = dns_scope_make_reply_packet(s, DNS_PACKET_ID(p), DNS_RCODE_SUCCESS, p->question, answer, soa, tentative, &reply);
        if (r < 0) {
                log_debug_errno(r, "Failed to build reply packet: %m");
                return;
        }
 
        if (stream) {
                r = dns_stream_write_packet(stream, reply);
                if (r < 0) {
                        log_debug_errno(r, "Failed to enqueue reply packet: %m");
                        return;
                }
 
                /* Let's take an extra reference on this stream, so that it stays around after returning. The reference
                 * will be dangling until the stream is disconnected, and the default completion handler of the stream
                 * will then unref the stream and destroy it */
                if (DNS_STREAM_QUEUED(stream))
                        dns_stream_ref(stream);
        } else {
                int fd;
 
                if (!ratelimit_below(&s->ratelimit))
                        return;
 
                if (p->family == AF_INET)
                        fd = manager_llmnr_ipv4_udp_fd(s->manager);
                else if (p->family == AF_INET6)
                        fd = manager_llmnr_ipv6_udp_fd(s->manager);
                else {
                        log_debug("Unknown protocol");
                        return;
                }
                if (fd < 0) {
                        log_debug_errno(fd, "Failed to get reply socket: %m");
                        return;
                }
 
                /* Note that we always immediately reply to all LLMNR
                 * requests, and do not wait any time, since we
                 * verified uniqueness for all records. Also see RFC
                 * 4795, Section 2.7 */
 
                r = manager_send(s->manager, fd, p->ifindex, p->family, &p->sender, p->sender_port, NULL, reply);
                if (r < 0) {
                        log_debug_errno(r, "Failed to send reply packet: %m");
                        return;
                }
        }
}
 
DnsTransaction *dns_scope_find_transaction(
                DnsScope *scope,
                DnsResourceKey *key,
                uint64_t query_flags) {
 
        DnsTransaction *first;
 
        assert(scope);
        assert(key);
 
        /* Iterate through the list of transactions with a matching key */
        first = hashmap_get(scope->transactions_by_key, key);
        LIST_FOREACH(transactions_by_key, t, first) {
 
                /* These four flags must match exactly: we cannot use a validated response for a
                 * non-validating client, and we cannot use a non-validated response for a validating
                 * client. Similar, if the sources don't match things aren't usable either. */
                if (((query_flags ^ t->query_flags) &
                     (SD_RESOLVED_NO_VALIDATE|
                     SD_RESOLVED_NO_ZONE|
                      SD_RESOLVED_NO_TRUST_ANCHOR|
                      SD_RESOLVED_NO_NETWORK)) != 0)
                        continue;
 
                /* We can reuse a primary query if a regular one is requested, but not vice versa */
                if ((query_flags & SD_RESOLVED_REQUIRE_PRIMARY) &&
                    !(t->query_flags & SD_RESOLVED_REQUIRE_PRIMARY))
                        continue;
 
                /* Don't reuse a transaction that allowed caching when we got told not to use it */
                if ((query_flags & SD_RESOLVED_NO_CACHE) &&
                    !(t->query_flags & SD_RESOLVED_NO_CACHE))
                        continue;
 
                /* If we are asked to clamp ttls and the existing transaction doesn't do it, we can't
                 * reuse */
                if ((query_flags & SD_RESOLVED_CLAMP_TTL) &&
                    !(t->query_flags & SD_RESOLVED_CLAMP_TTL))
                        continue;
 
                return t;
        }
 
        return NULL;
}
 
static int dns_scope_make_conflict_packet(
                DnsScope *s,
                DnsResourceRecord *rr,
                DnsPacket **ret) {
 
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
        int r;
 
        assert(s);
        assert(rr);
        assert(ret);
 
        r = dns_packet_new(&p, s->protocol, 0, DNS_PACKET_SIZE_MAX);
        if (r < 0)
                return r;
 
        DNS_PACKET_HEADER(p)->flags = htobe16(DNS_PACKET_MAKE_FLAGS(
                                                              0 /* qr */,
                                                              0 /* opcode */,
                                                              1 /* conflict */,
                                                              0 /* tc */,
                                                              0 /* t */,
                                                              0 /* (ra) */,
                                                              0 /* (ad) */,
                                                              0 /* (cd) */,
                                                              0));
 
        /* For mDNS, the transaction ID should always be 0 */
        if (s->protocol != DNS_PROTOCOL_MDNS)
                random_bytes(&DNS_PACKET_HEADER(p)->id, sizeof(uint16_t));
 
        DNS_PACKET_HEADER(p)->qdcount = htobe16(1);
        DNS_PACKET_HEADER(p)->arcount = htobe16(1);
 
        r = dns_packet_append_key(p, rr->key, 0, NULL);
        if (r < 0)
                return r;
 
        r = dns_packet_append_rr(p, rr, 0, NULL, NULL);
        if (r < 0)
                return r;
 
        *ret = TAKE_PTR(p);
 
        return 0;
}
 
static int on_conflict_dispatch(sd_event_source *es, usec_t usec, void *userdata) {
        DnsScope *scope = ASSERT_PTR(userdata);
        int r;
 
        assert(es);
 
        scope->conflict_event_source = sd_event_source_disable_unref(scope->conflict_event_source);
 
        for (;;) {
                _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
                _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
 
                rr = ordered_hashmap_steal_first_key_and_value(scope->conflict_queue, (void**) &key);
                if (!rr)
                        break;
 
                r = dns_scope_make_conflict_packet(scope, rr, &p);
                if (r < 0) {
                        log_error_errno(r, "Failed to make conflict packet: %m");
                        return 0;
                }
 
                r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
                if (r < 0)
                        log_debug_errno(r, "Failed to send conflict packet: %m");
        }
 
        return 0;
}
 
int dns_scope_notify_conflict(DnsScope *scope, DnsResourceRecord *rr) {
        int r;
 
        assert(scope);
        assert(scope->protocol == DNS_PROTOCOL_LLMNR);
        assert(rr);
 
        /* We don't send these queries immediately. Instead, we queue them, and send them after some jitter
         * delay.  We only place one RR per key in the conflict messages, not all of them. That should be
         * enough to indicate where there might be a conflict */
        r = ordered_hashmap_ensure_put(&scope->conflict_queue, &dns_resource_record_hash_ops_by_key, rr->key, rr);
        if (IN_SET(r, 0, -EEXIST))
                return 0;
        if (r < 0)
                return log_debug_errno(r, "Failed to queue conflicting RR: %m");
 
        dns_resource_key_ref(rr->key);
        dns_resource_record_ref(rr);
 
        if (scope->conflict_event_source)
                return 0;
 
        r = sd_event_add_time_relative(
                        scope->manager->event,
                        &scope->conflict_event_source,
                        CLOCK_BOOTTIME,
                        random_u64_range(LLMNR_JITTER_INTERVAL_USEC),
                        0,
                        on_conflict_dispatch, scope);
        if (r < 0)
                return log_debug_errno(r, "Failed to add conflict dispatch event: %m");
 
        (void) sd_event_source_set_description(scope->conflict_event_source, "scope-conflict");
 
        return 0;
}
 
void dns_scope_check_conflicts(DnsScope *scope, DnsPacket *p) {
        DnsResourceRecord *rr;
        int r;
 
        assert(scope);
        assert(p);
 
        if (!IN_SET(p->protocol, DNS_PROTOCOL_LLMNR, DNS_PROTOCOL_MDNS))
                return;
 
        if (DNS_PACKET_RRCOUNT(p) <= 0)
                return;
 
        if (p->protocol == DNS_PROTOCOL_LLMNR) {
                if (DNS_PACKET_LLMNR_C(p) != 0)
                        return;
 
                if (DNS_PACKET_LLMNR_T(p) != 0)
                        return;
        }
 
        if (manager_packet_from_local_address(scope->manager, p))
                return;
 
        r = dns_packet_extract(p);
        if (r < 0) {
                log_debug_errno(r, "Failed to extract packet: %m");
                return;
        }
 
        log_debug("Checking for conflicts...");
 
        DNS_ANSWER_FOREACH(rr, p->answer) {
                /* No conflict if it is DNS-SD RR used for service enumeration. */
                if (dns_resource_key_is_dnssd_ptr(rr->key))
                        continue;
 
                /* Check for conflicts against the local zone. If we
                 * found one, we won't check any further */
                r = dns_zone_check_conflicts(&scope->zone, rr);
                if (r != 0)
                        continue;
 
                /* Advisory conflict queries only exist in LLMNR (RFC 4795, section 4.2). In mDNS several
                 * responders may legitimately answer for the same name (e.g. the SRP advertising proxies
                 * of Thread border routers), only conflicts with our own records matter (RFC 6762,
                 * section 9), and queries must not have the AA bit set (RFC 6762, section 18.4). Every
                 * responder would answer the advisory again, which we'd take as yet another conflict. */
                if (scope->protocol != DNS_PROTOCOL_LLMNR)
                        continue;
 
                /* Check for conflicts against the local cache. If so,
                 * send out an advisory query, to inform everybody */
                r = dns_cache_check_conflicts(&scope->cache, rr, p->family, &p->sender);
                if (r <= 0)
                        continue;
 
                dns_scope_notify_conflict(scope, rr);
        }
}
 
void dns_scope_dump(DnsScope *s, FILE *f) {
        assert(s);
 
        if (!f)
                f = stdout;
 
        fputs("[Scope protocol=", f);
        fputs(dns_protocol_to_string(s->protocol), f);
 
        if (s->link) {
                fputs(" interface=", f);
                fputs(s->link->ifname, f);
        }
 
        if (s->family != AF_UNSPEC) {
                fputs(" family=", f);
                fputs(af_to_name(s->family), f);
        }
 
        fputs(" origin=", f);
        fputs(dns_scope_origin_to_string(s->origin), f);
 
        if (s->delegate) {
                fputs(" id=", f);
                fputs(s->delegate->id, f);
        }
 
        if (s->protocol == DNS_PROTOCOL_DNS) {
                fputs(" DNSSEC=", f);
                fputs(dnssec_mode_to_string(s->dnssec_mode), f);
 
                fputs(" DNSOverTLS=", f);
                fputs(dns_over_tls_mode_to_string(s->dns_over_tls_mode), f);
        }
 
        fputs("]\n", f);
 
        if (!dns_zone_is_empty(&s->zone)) {
                fputs("ZONE:\n", f);
                dns_zone_dump(&s->zone, f);
        }
 
        if (!dns_cache_is_empty(&s->cache)) {
                fputs("CACHE:\n", f);
                dns_cache_dump(&s->cache, f);
        }
}
 
DnsSearchDomain *dns_scope_get_search_domains(DnsScope *s) {
        assert(s);
 
        if (s->protocol != DNS_PROTOCOL_DNS)
                return NULL;
 
        if (s->link)
                return s->link->search_domains;
        if (s->delegate)
                return s->delegate->search_domains;
 
        return s->manager->search_domains;
}
 
bool dns_scope_name_wants_search_domain(DnsScope *s, const char *name) {
        assert(s);
 
        if (s->protocol != DNS_PROTOCOL_DNS)
                return false;
 
        if (!dns_name_is_single_label(name))
                return false;
 
        /* If we allow single-label domain lookups on unicast DNS, and this scope has a search domain that matches
         * _exactly_ this name, then do not use search domains. */
        if (s->manager->resolve_unicast_single_label)
                LIST_FOREACH(domains, d, dns_scope_get_search_domains(s))
                        if (dns_name_equal(name, d->name) > 0)
                                return false;
 
        return true;
}
 
bool dns_scope_network_good(DnsScope *s) {
        /* Checks whether the network is in good state for lookups on this scope. For mDNS/LLMNR/Classic DNS scopes
         * bound to links this is easy, as they don't even exist if the link isn't in a suitable state. For the global
         * DNS scope we check whether there are any links that are up and have an address.
         *
         * Note that Linux routing is complex and even systems that superficially have no IPv4 address might
         * be able to route IPv4 (and similar for IPv6), hence let's make a check here independent of address
         * family. */
 
        if (s->link)
                return true;
 
        return manager_routable(s->manager);
}
 
int dns_scope_ifindex(DnsScope *s) {
        assert(s);
 
        if (s->link)
                return s->link->ifindex;
 
        return 0;
}
 
const char* dns_scope_ifname(DnsScope *s) {
        assert(s);
 
        if (s->link)
                return s->link->ifname;
 
        return NULL;
}
 
static int on_announcement_timeout(sd_event_source *s, usec_t usec, void *userdata) {
        DnsScope *scope = userdata;
 
        assert(s);
 
        scope->announce_event_source = sd_event_source_disable_unref(scope->announce_event_source);
 
        (void) dns_scope_announce(scope, false);
        return 0;
}
 
int dns_scope_send_goodbye(DnsScope *scope, DnsAnswer *answer) {
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
        int r;
 
        assert(scope);
        assert(answer);
 
        /* Sends an unsolicited response withdrawing the specified RRs, which are expected to be flagged as
         * goodbye (TTL 0), without touching anything else published in the zone. */
 
        if (scope->protocol != DNS_PROTOCOL_MDNS)
                return 0;
 
        r = sd_event_get_state(scope->manager->event);
        if (r < 0)
                return log_debug_errno(r, "Failed to get event loop state: %m");
 
        /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
        if (r == SD_EVENT_FINISHED)
                return 0;
 
        if (dns_answer_isempty(answer))
                return 0;
 
        r = dns_scope_make_reply_packet(scope, /* id= */ 0, DNS_RCODE_SUCCESS, /* q= */ NULL, answer,
                                        /* soa= */ NULL, /* tentative= */ false, &p);
        if (r < 0)
                return log_debug_errno(r, "Failed to build reply packet: %m");
 
        r = dns_scope_emit_udp(scope, -EBADF, AF_UNSPEC, p);
        if (r < 0)
                return log_debug_errno(r, "Failed to send reply packet: %m");
 
        return 0;
}
 
int dns_scope_announce(DnsScope *scope, bool goodbye) {
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
        _cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
        _cleanup_set_free_ Set *types = NULL;
        DnsZoneItem *z;
        unsigned size = 0;
        char *service_type;
        int r;
 
        if (!scope)
                return 0;
 
        if (scope->protocol != DNS_PROTOCOL_MDNS)
                return 0;
 
        r = sd_event_get_state(scope->manager->event);
        if (r < 0)
                return log_debug_errno(r, "Failed to get event loop state: %m");
 
        /* If this is called on exit, through manager_free() -> link_free(), then we cannot announce. */
        if (r == SD_EVENT_FINISHED)
                return 0;
 
        /* Check if we're done with probing. */
        LIST_FOREACH(transactions_by_scope, t, scope->transactions)
                if (t->probing && DNS_TRANSACTION_IS_LIVE(t->state))
                        return 0;
 
        /* Check if there're services pending conflict resolution. */
        if (manager_next_dnssd_names(scope->manager))
                return 0; /* we reach this point only if changing hostname didn't help */
 
        /* Calculate answer's size. */
        HASHMAP_FOREACH(z, scope->zone.by_key) {
                if (z->state != DNS_ZONE_ITEM_ESTABLISHED)
                        continue;
 
                if (z->rr->key->type == DNS_TYPE_PTR &&
                    !dns_zone_contains_name(&scope->zone, z->rr->ptr.name)) {
                        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
 
                        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));
                        z->state = DNS_ZONE_ITEM_WITHDRAWN;
                        continue;
                }
 
                /* Collect service types for _services._dns-sd._udp.local RRs in a set. Only two-label names
                 * (not selective names) are considered according to RFC6763 § 9. */
                if (!scope->announced &&
                    dns_resource_key_is_dnssd_two_label_ptr(z->rr->key)) {
                        if (!set_contains(types, dns_resource_key_name(z->rr->key))) {
                                r = set_ensure_put(&types, &dns_name_hash_ops, dns_resource_key_name(z->rr->key));
                                if (r < 0)
                                        return log_debug_errno(r, "Failed to add item to set: %m");
                        }
                }
 
                LIST_FOREACH(by_key, i, z)
                        size++;
        }
 
        answer = dns_answer_new(size + set_size(types));
        if (!answer)
                return log_oom();
 
        /* Second iteration, actually add RRs to the answer. */
        HASHMAP_FOREACH(z, scope->zone.by_key)
                LIST_FOREACH (by_key, i, z) {
                        DnsAnswerFlags flags;
 
                        if (i->state != DNS_ZONE_ITEM_ESTABLISHED)
                                continue;
 
                        if (dns_resource_key_is_dnssd_ptr(i->rr->key))
                                flags = goodbye ? DNS_ANSWER_GOODBYE : 0;
                        else
                                flags = goodbye ? (DNS_ANSWER_GOODBYE|DNS_ANSWER_CACHE_FLUSH) : DNS_ANSWER_CACHE_FLUSH;
 
                        r = dns_answer_add(answer, i->rr, 0, flags, NULL);
                        if (r < 0)
                                return log_debug_errno(r, "Failed to add RR to announce: %m");
                }
 
        /* Since all the active services are in the zone make them discoverable now. */
        SET_FOREACH(service_type, types) {
                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
 
                rr = dns_resource_record_new_full(DNS_CLASS_IN, DNS_TYPE_PTR,
                                                  "_services._dns-sd._udp.local");
                if (!rr)
                        return log_oom();
 
                rr->ptr.name = strdup(service_type);
                if (!rr->ptr.name)
                        return log_oom();
 
                rr->ttl = MDNS_DEFAULT_TTL;
 
                r = dns_zone_put(&scope->zone, scope, rr, false);
                if (r < 0)
                        log_warning_errno(r, "Failed to add DNS-SD PTR record to MDNS zone, ignoring: %m");
 
                r = dns_answer_add(answer, rr, 0, 0, NULL);
                if (r < 0)
                        return log_debug_errno(r, "Failed to add RR to announce: %m");
        }
 
        if (dns_answer_isempty(answer))
                return 0;
 
        r = dns_scope_make_reply_packet(scope, 0, DNS_RCODE_SUCCESS, NULL, answer, NULL, false, &p);
        if (r < 0)
                return log_debug_errno(r, "Failed to build reply packet: %m");
 
        r = dns_scope_emit_udp(scope, -1, AF_UNSPEC, p);
        if (r < 0)
                return log_debug_errno(r, "Failed to send reply packet: %m");
 
        /* In section 8.3 of RFC6762: "The Multicast DNS responder MUST send at least two unsolicited
         * responses, one second apart." */
        if (!scope->announced) {
                scope->announced = true;
 
                r = sd_event_add_time_relative(
                                scope->manager->event,
                                &scope->announce_event_source,
                                CLOCK_BOOTTIME,
                                MDNS_ANNOUNCE_DELAY,
                                0,
                                on_announcement_timeout, scope);
                if (r < 0)
                        return log_debug_errno(r, "Failed to schedule second announcement: %m");
 
                (void) sd_event_source_set_description(scope->announce_event_source, "mdns-announce");
        }
 
        return 0;
}
 
int dns_scope_add_dnssd_registered_services(DnsScope *scope) {
        DnssdRegisteredService *service;
        int r;
 
        assert(scope);
 
        if (hashmap_isempty(scope->manager->dnssd_registered_services))
                return 0;
 
        scope->announced = false;
 
        HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
                service->withdrawn = false;
 
                r = dns_zone_put(&scope->zone, scope, service->ptr_rr, false);
                if (r < 0)
                        log_warning_errno(r, "Failed to add PTR record to MDNS zone: %m");
 
                if (service->sub_ptr_rr) {
                        r = dns_zone_put(&scope->zone, scope, service->sub_ptr_rr, false);
                        if (r < 0)
                                log_warning_errno(r, "Failed to add selective PTR record to MDNS zone: %m");
                }
 
                r = dns_zone_put(&scope->zone, scope, service->srv_rr, true);
                if (r < 0)
                        log_warning_errno(r, "Failed to add SRV record to MDNS zone: %m");
 
                LIST_FOREACH(items, txt_data, service->txt_data_items) {
                        r = dns_zone_put(&scope->zone, scope, txt_data->rr, true);
                        if (r < 0)
                                log_warning_errno(r, "Failed to add TXT record to MDNS zone: %m");
                }
        }
 
        return 0;
}
 
int dns_scope_remove_dnssd_registered_services(DnsScope *scope) {
        _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
        DnssdRegisteredService *service;
        int r;
 
        assert(scope);
 
        key = dns_resource_key_new(DNS_CLASS_IN, DNS_TYPE_PTR,
                                   "_services._dns-sd._udp.local");
        if (!key)
                return log_oom();
 
        r = dns_zone_remove_rrs_by_key(&scope->zone, key);
        if (r < 0)
                return r;
 
        HASHMAP_FOREACH(service, scope->manager->dnssd_registered_services) {
                dns_zone_remove_rr(&scope->zone, service->ptr_rr);
                dns_zone_remove_rr(&scope->zone, service->sub_ptr_rr);
                dns_zone_remove_rr(&scope->zone, service->srv_rr);
                LIST_FOREACH(items, txt_data, service->txt_data_items)
                        dns_zone_remove_rr(&scope->zone, txt_data->rr);
        }
 
        return 0;
}
 
static bool dns_scope_has_route_only_domains(DnsScope *scope) {
        DnsSearchDomain *first;
        bool route_only = false;
 
        assert(scope);
        assert(scope->protocol == DNS_PROTOCOL_DNS);
 
        /* Returns 'true' if this scope is suitable for queries to specific domains only. For that we check
         * if there are any route-only domains on this interface, as a heuristic to discern VPN-style links
         * from non-VPN-style links. Returns 'false' for all other cases, i.e. if the scope is intended to
         * take queries to arbitrary domains, i.e. has no routing domains set. */
 
        if (scope->link)
                first = scope->link->search_domains;
        else if (scope->delegate)
                first = scope->delegate->search_domains;
        else
                first = scope->manager->search_domains;
 
        LIST_FOREACH(domains, domain, first) {
                /* "." means "any domain", thus the interface takes any kind of traffic. Thus, we exit early
                 * here, as it doesn't really matter whether this link has any route-only domains or not,
                 * "~."  really trumps everything and clearly indicates that this interface shall receive all
                 * traffic it can get. */
                if (dns_name_is_root(DNS_SEARCH_DOMAIN_NAME(domain)))
                        return false;
 
                if (domain->route_only)
                        route_only = true;
        }
 
        return route_only;
}
 
bool dns_scope_is_default_route(DnsScope *scope) {
        assert(scope);
 
        /* Only use DNS scopes as default routes */
        if (scope->protocol != DNS_PROTOCOL_DNS)
                return false;
 
        if (scope->link) {
 
                /* Honour whatever is explicitly configured. This is really the best approach, and trumps any
                 * automatic logic. */
                if (scope->link->default_route >= 0)
                        return scope->link->default_route;
 
                /* Otherwise check if we have any route-only domains, as a sensible heuristic: if so, let's not
                 * volunteer as default route. */
                return !dns_scope_has_route_only_domains(scope);
 
        } else  if (scope->delegate) {
 
                if (scope->delegate->default_route >= 0)
                        return scope->delegate->default_route;
 
                /* Delegates are by default not used as default route */
                return false;
        } else
                /* The global DNS scope is always suitable as default route */
                return true;
}
 
int dns_scope_to_json(DnsScope *scope, bool with_cache, sd_json_variant **ret) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *cache = NULL;
        int r;
 
        assert(scope);
        assert(ret);
 
        if (with_cache) {
                r = dns_cache_dump_to_json(&scope->cache, &cache);
                if (r < 0)
                        return r;
        }
 
        return sd_json_buildo(
                        ret,
                        JSON_BUILD_PAIR_ENUM("protocol", dns_protocol_to_string(scope->protocol)),
                        SD_JSON_BUILD_PAIR_CONDITION(scope->family != AF_UNSPEC, "family", SD_JSON_BUILD_INTEGER(scope->family)),
                        SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifindex", SD_JSON_BUILD_INTEGER(dns_scope_ifindex(scope))),
                        SD_JSON_BUILD_PAIR_CONDITION(!!scope->link, "ifname", SD_JSON_BUILD_STRING(dns_scope_ifname(scope))),
                        SD_JSON_BUILD_PAIR_CONDITION(with_cache, "cache", SD_JSON_BUILD_VARIANT(cache)),
                        SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
                                                     "dnssec",
                                                     SD_JSON_BUILD_STRING(dnssec_mode_to_string(scope->dnssec_mode))),
                        SD_JSON_BUILD_PAIR_CONDITION(scope->protocol == DNS_PROTOCOL_DNS,
                                                     "dnsOverTLS",
                                                     SD_JSON_BUILD_STRING(dns_over_tls_mode_to_string(scope->dns_over_tls_mode))));
}
 
int dns_type_suitable_for_protocol(uint16_t type, DnsProtocol protocol) {
 
        /* Tests whether it makes sense to route queries for the specified DNS RR types to the specified
         * protocol. For classic DNS pretty much all RR types are suitable, but for LLMNR/mDNS let's
         * allowlist only a few that make sense. We use this when routing queries so that we can more quickly
         * return errors for queries that will almost certainly fail/time out otherwise. For example, this
         * ensures that SOA, NS, or DS/DNSKEY queries are never routed to mDNS/LLMNR where they simply make
         * no sense. */
 
        if (dns_type_is_obsolete(type))
                return false;
 
        if (!dns_type_is_valid_query(type))
                return false;
 
        switch (protocol) {
 
        case DNS_PROTOCOL_DNS:
                return true;
 
        case DNS_PROTOCOL_LLMNR:
                return IN_SET(type,
                              DNS_TYPE_ANY,
                              DNS_TYPE_A,
                              DNS_TYPE_AAAA,
                              DNS_TYPE_CNAME,
                              DNS_TYPE_PTR,
                              DNS_TYPE_TXT);
 
        case DNS_PROTOCOL_MDNS:
                return IN_SET(type,
                              DNS_TYPE_ANY,
                              DNS_TYPE_A,
                              DNS_TYPE_AAAA,
                              DNS_TYPE_CNAME,
                              DNS_TYPE_PTR,
                              DNS_TYPE_TXT,
                              DNS_TYPE_SRV,
                              DNS_TYPE_NSEC,
                              DNS_TYPE_HINFO);
 
        default:
                return -EPROTONOSUPPORT;
        }
}
 
int dns_question_types_suitable_for_protocol(DnsQuestion *q, DnsProtocol protocol) {
        DnsResourceKey *key;
        int r;
 
        /* Tests whether the types in the specified question make any sense to be routed to the specified
         * protocol, i.e. if dns_type_suitable_for_protocol() is true for any of the contained RR types */
 
        DNS_QUESTION_FOREACH(key, q) {
                r = dns_type_suitable_for_protocol(key->type, protocol);
                if (r != 0)
                        return r;
        }
 
        return false;
}
 
static const char* const dns_scope_origin_table[_DNS_SCOPE_ORIGIN_MAX] = {
        [DNS_SCOPE_GLOBAL]   = "global",
        [DNS_SCOPE_LINK]     = "link",
        [DNS_SCOPE_DELEGATE] = "delegate",
};
 
DEFINE_STRING_TABLE_LOOKUP(dns_scope_origin, DnsScopeOrigin);