HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/resolve/resolved-dns-transaction.c

163,582 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 7acad458341057b625463484a08179dca3da17c4

Lines 1–1000 of 3,879

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include "sd-event.h"
#include "sd-messages.h"
 
#include "af-list.h"
#include "alloc-util.h"
#include "dns-answer.h"
#include "dns-domain.h"
#include "dns-packet.h"
#include "dns-question.h"
#include "dns-rr.h"
#include "errno-list.h"
#include "errno-util.h"
#include "fd-util.h"
#include "glyph-util.h"
#include "log.h"
#include "random-util.h"
#include "resolved-dns-cache.h"
#include "resolved-dns-query.h"
#include "resolved-dns-scope.h"
#include "resolved-dns-server.h"
#include "resolved-dns-stream.h"
#include "resolved-dns-transaction.h"
#include "resolved-dnstls.h"
#include "resolved-link.h"
#include "resolved-llmnr.h"
#include "resolved-manager.h"
#include "resolved-socket-graveyard.h"
#include "resolved-timeouts.h"
#include "set.h"
#include "string-table.h"
#include "string-util.h"
 
#define TRANSACTIONS_MAX 4096
 
static void dns_transaction_reset_answer(DnsTransaction *t) {
        assert(t);
 
        t->received = dns_packet_unref(t->received);
        t->answer = dns_answer_unref(t->answer);
        t->answer_rcode = 0;
        t->answer_ede_rcode = _DNS_EDE_RCODE_INVALID;
        t->answer_ede_msg = mfree(t->answer_ede_msg);
        t->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
        t->answer_source = _DNS_TRANSACTION_SOURCE_INVALID;
        t->answer_query_flags = 0;
        t->answer_nsec_ttl = UINT32_MAX;
        t->answer_errno = 0;
}
 
static void dns_transaction_flush_dnssec_transactions(DnsTransaction *t) {
        DnsTransaction *z;
 
        assert(t);
 
        while ((z = set_steal_first(t->dnssec_transactions))) {
                set_remove(z->notify_transactions, t);
                set_remove(z->notify_transactions_done, t);
                dns_transaction_gc(z);
        }
}
 
static void dns_transaction_close_connection(
                DnsTransaction *t,
                bool use_graveyard) { /* Set use_graveyard = false when you know the connection is already
                                       * dead, for example because you got a connection error back from the
                                       * kernel. In that case there's no point in keeping the fd around,
                                       * hence don't. */
        int r;
 
        assert(t);
 
        if (t->stream) {
                /* Let's detach the stream from our transaction, in case something else keeps a reference to it. */
                LIST_REMOVE(transactions_by_stream, t->stream->transactions, t);
 
                /* Remove packet in case it's still in the queue */
                dns_packet_unref(ordered_set_remove(t->stream->write_queue, t->sent));
 
                t->stream = dns_stream_unref(t->stream);
        }
 
        t->dns_udp_event_source = sd_event_source_disable_unref(t->dns_udp_event_source);
 
        /* If we have a UDP socket where we sent a packet, but never received one, then add it to the socket
         * graveyard, instead of closing it right away. That way it will stick around for a moment longer,
         * and the reply we might still get from the server will be eaten up instead of resulting in an ICMP
         * port unreachable error message. */
 
        /* Skip the graveyard stuff when we're shutting down, since that requires running event loop.
         * Note that this is also called from dns_transaction_free(). In that case, scope may be NULL. */
        if (!t->scope ||
            !t->scope->manager ||
            !t->scope->manager->event ||
            sd_event_get_state(t->scope->manager->event) == SD_EVENT_FINISHED)
                use_graveyard = false;
 
        if (use_graveyard && t->dns_udp_fd >= 0 && t->sent && !t->received) {
                r = manager_add_socket_to_graveyard(t->scope->manager, t->dns_udp_fd);
                if (r < 0)
                        log_debug_errno(r, "Failed to add UDP socket to graveyard, closing immediately: %m");
                else
                        TAKE_FD(t->dns_udp_fd);
        }
 
        t->dns_udp_fd = safe_close(t->dns_udp_fd);
}
 
static void dns_transaction_stop_timeout(DnsTransaction *t) {
        assert(t);
 
        t->timeout_event_source = sd_event_source_disable_unref(t->timeout_event_source);
}
 
DnsTransaction* dns_transaction_free(DnsTransaction *t) {
        DnsQueryCandidate *c;
        DnsZoneItem *i;
        DnsTransaction *z;
 
        if (!t)
                return NULL;
 
        log_debug("Freeing transaction %" PRIu16 ".", t->id);
 
        dns_transaction_close_connection(t, true);
        dns_transaction_stop_timeout(t);
 
        dns_packet_unref(t->sent);
        dns_transaction_reset_answer(t);
 
        dns_server_unref(t->server);
 
        if (t->scope) {
                if (t->key) {
                        DnsTransaction *first;
 
                        first = hashmap_get(t->scope->transactions_by_key, t->key);
                        LIST_REMOVE(transactions_by_key, first, t);
                        if (first)
                                hashmap_replace(t->scope->transactions_by_key, first->key, first);
                        else
                                hashmap_remove(t->scope->transactions_by_key, t->key);
                }
 
                LIST_REMOVE(transactions_by_scope, t->scope->transactions, t);
 
                if (t->id != 0)
                        hashmap_remove(t->scope->manager->dns_transactions, UINT_TO_PTR(t->id));
        }
 
        while ((c = set_steal_first(t->notify_query_candidates)))
                set_remove(c->transactions, t);
        set_free(t->notify_query_candidates);
 
        while ((c = set_steal_first(t->notify_query_candidates_done)))
                set_remove(c->transactions, t);
        set_free(t->notify_query_candidates_done);
 
        while ((i = set_steal_first(t->notify_zone_items)))
                i->probe_transaction = NULL;
        set_free(t->notify_zone_items);
 
        while ((i = set_steal_first(t->notify_zone_items_done)))
                i->probe_transaction = NULL;
        set_free(t->notify_zone_items_done);
 
        while ((z = set_steal_first(t->notify_transactions)))
                set_remove(z->dnssec_transactions, t);
        set_free(t->notify_transactions);
 
        while ((z = set_steal_first(t->notify_transactions_done)))
                set_remove(z->dnssec_transactions, t);
        set_free(t->notify_transactions_done);
 
        dns_transaction_flush_dnssec_transactions(t);
        set_free(t->dnssec_transactions);
 
        dns_answer_unref(t->validated_keys);
        dns_resource_key_unref(t->key);
        dns_packet_unref(t->bypass);
 
        return mfree(t);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(DnsTransaction*, dns_transaction_free);
 
DnsTransaction* dns_transaction_gc(DnsTransaction *t) {
        assert(t);
 
        /* Returns !NULL if we can't gc yet. */
 
        if (t->block_gc > 0)
                return t;
 
        if (t->wait_for_answer && IN_SET(t->state, DNS_TRANSACTION_PENDING, DNS_TRANSACTION_VALIDATING))
                return t;
 
        if (set_isempty(t->notify_query_candidates) &&
            set_isempty(t->notify_query_candidates_done) &&
            set_isempty(t->notify_zone_items) &&
            set_isempty(t->notify_zone_items_done) &&
            set_isempty(t->notify_transactions) &&
            set_isempty(t->notify_transactions_done))
                return dns_transaction_free(t);
 
        return t;
}
 
static uint16_t pick_new_id(Manager *m) {
        uint16_t new_id;
 
        /* Find a fresh, unused transaction id. Note that this loop is bounded because there's a limit on the
         * number of transactions, and it's much lower than the space of IDs. */
 
        assert_cc(TRANSACTIONS_MAX < 0xFFFF);
 
        do
                random_bytes(&new_id, sizeof(new_id));
        while (new_id == 0 ||
               hashmap_get(m->dns_transactions, UINT_TO_PTR(new_id)));
 
        return new_id;
}
 
static int key_ok(
                DnsScope *scope,
                DnsResourceKey *key) {
 
        /* Don't allow looking up invalid or pseudo RRs */
        if (!dns_type_is_valid_query(key->type))
                return -EINVAL;
        if (dns_type_is_obsolete(key->type))
                return -EOPNOTSUPP;
 
        /* We only support the IN class */
        if (!IN_SET(key->class, DNS_CLASS_IN, DNS_CLASS_ANY))
                return -EOPNOTSUPP;
 
        /* Don't allows DNSSEC RRs to be looked up via LLMNR/mDNS. They don't really make sense
         * there, and it speeds up our queries if we refuse this early */
        if (scope->protocol != DNS_PROTOCOL_DNS &&
            dns_type_is_dnssec(key->type))
                return -EOPNOTSUPP;
 
        return 0;
}
 
int dns_transaction_new(
                DnsTransaction **ret,
                DnsScope *s,
                DnsResourceKey *key,
                DnsPacket *bypass,
                uint64_t query_flags) {
 
        _cleanup_(dns_transaction_freep) DnsTransaction *t = NULL;
        int r;
 
        assert(ret);
        assert(s);
 
        if (key) {
                assert(!bypass);
 
                r = key_ok(s, key);
                if (r < 0)
                        return r;
        } else {
                DnsResourceKey *qk;
                assert(bypass);
 
                r = dns_packet_validate_query(bypass);
                if (r < 0)
                        return r;
 
                DNS_QUESTION_FOREACH(qk, bypass->question) {
                        r = key_ok(s, qk);
                        if (r < 0)
                                return r;
                }
        }
 
        if (hashmap_size(s->manager->dns_transactions) >= TRANSACTIONS_MAX)
                return -EBUSY;
 
        r = hashmap_ensure_allocated(&s->manager->dns_transactions, NULL);
        if (r < 0)
                return r;
 
        if (key) {
                r = hashmap_ensure_allocated(&s->transactions_by_key, &dns_resource_key_hash_ops);
                if (r < 0)
                        return r;
        }
 
        t = new(DnsTransaction, 1);
        if (!t)
                return -ENOMEM;
 
        *t = (DnsTransaction) {
                .dns_udp_fd = -EBADF,
                .answer_source = _DNS_TRANSACTION_SOURCE_INVALID,
                .answer_dnssec_result = _DNSSEC_RESULT_INVALID,
                .answer_ede_rcode = _DNS_EDE_RCODE_INVALID,
                .answer_nsec_ttl = UINT32_MAX,
                .key = dns_resource_key_ref(key),
                .query_flags = query_flags,
                .bypass = dns_packet_ref(bypass),
                .current_feature_level = _DNS_SERVER_FEATURE_LEVEL_INVALID,
                .clamp_feature_level_servfail = _DNS_SERVER_FEATURE_LEVEL_INVALID,
                .id = pick_new_id(s->manager),
        };
 
        r = hashmap_put(s->manager->dns_transactions, UINT_TO_PTR(t->id), t);
        if (r < 0) {
                t->id = 0;
                return r;
        }
 
        if (t->key) {
                DnsTransaction *first;
 
                first = hashmap_get(s->transactions_by_key, t->key);
                LIST_PREPEND(transactions_by_key, first, t);
 
                r = hashmap_replace(s->transactions_by_key, first->key, first);
                if (r < 0) {
                        LIST_REMOVE(transactions_by_key, first, t);
                        hashmap_remove(s->manager->dns_transactions, UINT_TO_PTR(t->id));
                        t->id = 0;
                        return r;
                }
        }
 
        LIST_PREPEND(transactions_by_scope, s->transactions, t);
        t->scope = s;
 
        s->manager->n_transactions_total++;
 
        if (ret)
                *ret = t;
 
        TAKE_PTR(t);
        return 0;
}
 
static void dns_transaction_shuffle_id(DnsTransaction *t) {
        uint16_t new_id;
        assert(t);
 
        /* Pick a new ID for this transaction. */
 
        new_id = pick_new_id(t->scope->manager);
        assert_se(hashmap_remove_and_put(t->scope->manager->dns_transactions, UINT_TO_PTR(t->id), UINT_TO_PTR(new_id), t) >= 0);
 
        log_debug("Transaction %" PRIu16 " is now %" PRIu16 ".", t->id, new_id);
        t->id = new_id;
 
        /* Make sure we generate a new packet with the new ID */
        t->sent = dns_packet_unref(t->sent);
}
 
static void dns_transaction_tentative(DnsTransaction *t, DnsPacket *p) {
        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
        DnsZoneItem *z;
 
        assert(t);
        assert(p);
        assert(t->scope->protocol == DNS_PROTOCOL_LLMNR);
 
        if (manager_packet_from_local_address(t->scope->manager, p) != 0)
                return;
 
        log_debug("Transaction %" PRIu16 " for <%s> on scope %s on %s/%s got tentative packet from %s.",
                  t->id,
                  dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str),
                  dns_protocol_to_string(t->scope->protocol),
                  t->scope->link ? t->scope->link->ifname : "*",
                  af_to_name_short(t->scope->family),
                  IN_ADDR_TO_STRING(p->family, &p->sender));
 
        /* RFC 4795, Section 4.1 says that the peer with the
         * lexicographically smaller IP address loses */
        if (memcmp(&p->sender, &p->destination, FAMILY_ADDRESS_SIZE(p->family)) >= 0) {
                log_debug("Peer has lexicographically larger IP address and thus lost in the conflict.");
                return;
        }
 
        log_debug("We have the lexicographically larger IP address and thus lost in the conflict.");
 
        t->block_gc++;
 
        while ((z = set_first(t->notify_zone_items))) {
                /* First, make sure the zone item drops the reference
                 * to us */
                dns_zone_item_probe_stop(z);
 
                /* Secondly, report this as conflict, so that we might
                 * look for a different hostname */
                dns_zone_item_conflict(z);
        }
        t->block_gc--;
 
        dns_transaction_gc(t);
}
 
void dns_transaction_complete(DnsTransaction *t, DnsTransactionState state) {
        DnsQueryCandidate *c;
        DnsZoneItem *z;
        DnsTransaction *d;
        char key_str[DNS_RESOURCE_KEY_STRING_MAX];
 
        assert(t);
        assert(!DNS_TRANSACTION_IS_LIVE(state));
 
        if (state == DNS_TRANSACTION_DNSSEC_FAILED) {
                dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str);
 
                log_struct(LOG_NOTICE,
                           LOG_MESSAGE_ID(SD_MESSAGE_DNSSEC_FAILURE_STR),
                           LOG_MESSAGE("DNSSEC validation failed for question %s: %s",
                                       key_str, dnssec_result_to_string(t->answer_dnssec_result)),
                           LOG_ITEM("DNS_TRANSACTION=%" PRIu16, t->id),
                           LOG_ITEM("DNS_QUESTION=%s", key_str),
                           LOG_ITEM("DNSSEC_RESULT=%s", dnssec_result_to_string(t->answer_dnssec_result)),
                           LOG_ITEM("DNS_SERVER=%s", strna(dns_server_string_full(t->server))),
                           LOG_ITEM("DNS_SERVER_FEATURE_LEVEL=%s", dns_server_feature_level_to_string(t->server->possible_feature_level)));
        }
 
        /* Note that this call might invalidate the query. Callers
         * should hence not attempt to access the query or transaction
         * after calling this function. */
 
        log_debug("%s transaction %" PRIu16 " for <%s> on scope %s on %s/%s now complete with <%s> from %s (%s; %s).",
                  t->bypass ? "Bypass" : "Regular",
                  t->id,
                  dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str),
                  dns_protocol_to_string(t->scope->protocol),
                  t->scope->link ? t->scope->link->ifname : "*",
                  af_to_name_short(t->scope->family),
                  state == DNS_TRANSACTION_ERRNO ? ERRNO_NAME(t->answer_errno) : dns_transaction_state_to_string(state),
                  t->answer_source < 0 ? "none" : dns_transaction_source_to_string(t->answer_source),
                  FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) ? "not validated" :
                  (FLAGS_SET(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED) ? "authenticated" : "unsigned"),
                  FLAGS_SET(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL) ? "confidential" : "non-confidential");
 
        t->state = state;
 
        dns_transaction_close_connection(t, true);
        dns_transaction_stop_timeout(t);
 
        /* Notify all queries that are interested, but make sure the
         * transaction isn't freed while we are still looking at it */
        t->block_gc++;
 
        SET_FOREACH_MOVE(c, t->notify_query_candidates_done, t->notify_query_candidates)
                dns_query_candidate_notify(c);
        SWAP_TWO(t->notify_query_candidates, t->notify_query_candidates_done);
 
        SET_FOREACH_MOVE(z, t->notify_zone_items_done, t->notify_zone_items)
                dns_zone_item_notify(z);
        SWAP_TWO(t->notify_zone_items, t->notify_zone_items_done);
        if (t->probing && t->state == DNS_TRANSACTION_ATTEMPTS_MAX_REACHED)
                (void) dns_scope_announce(t->scope, false);
 
        SET_FOREACH_MOVE(d, t->notify_transactions_done, t->notify_transactions)
                dns_transaction_notify(d, t);
        SWAP_TWO(t->notify_transactions, t->notify_transactions_done);
 
        t->block_gc--;
        dns_transaction_gc(t);
}
 
static void dns_transaction_complete_errno(DnsTransaction *t, int error) {
        assert(t);
        assert(error != 0);
 
        t->answer_errno = ABS(error);
        dns_transaction_complete(t, DNS_TRANSACTION_ERRNO);
}
 
static int dns_transaction_pick_server(DnsTransaction *t) {
        DnsServer *server;
 
        assert(t);
        assert(t->scope->protocol == DNS_PROTOCOL_DNS);
 
        /* Pick a DNS server and a feature level for it. */
 
        server = dns_scope_get_dns_server(t->scope);
        if (!server)
                return -ESRCH;
 
        /* If we changed the server invalidate the feature level clamping, as the new server might have completely
         * different properties. */
        if (server != t->server)
                t->clamp_feature_level_servfail = _DNS_SERVER_FEATURE_LEVEL_INVALID;
 
        t->current_feature_level = dns_server_possible_feature_level(server);
 
        /* Clamp the feature level if that is requested. */
        if (t->clamp_feature_level_servfail != _DNS_SERVER_FEATURE_LEVEL_INVALID &&
            t->current_feature_level > t->clamp_feature_level_servfail)
                t->current_feature_level = t->clamp_feature_level_servfail;
 
        log_debug("Using feature level %s for transaction %u.", dns_server_feature_level_to_string(t->current_feature_level), t->id);
 
        if (server == t->server)
                return 0;
 
        dns_server_unref(t->server);
        t->server = dns_server_ref(server);
 
        t->n_picked_servers++;
 
        log_debug("Using DNS server %s for transaction %u.", strna(dns_server_string_full(t->server)), t->id);
 
        return 1;
}
 
static void dns_transaction_retry(DnsTransaction *t, bool next_server) {
        int r;
 
        assert(t);
 
        /* Retries the transaction as it is, possibly on a different server */
 
        if (next_server && t->scope->protocol == DNS_PROTOCOL_DNS)
                log_debug("Retrying transaction %" PRIu16 ", after switching servers.", t->id);
        else
                log_debug("Retrying transaction %" PRIu16 ".", t->id);
 
        /* Before we try again, switch to a new server. */
        if (next_server)
                dns_scope_next_dns_server(t->scope, t->server);
 
        r = dns_transaction_go(t);
        if (r < 0)
                dns_transaction_complete_errno(t, r);
}
 
static bool dns_transaction_limited_retry(DnsTransaction *t) {
        assert(t);
 
        /* If we haven't tried all different servers yet, let's try again with a different server */
 
        if (t->n_picked_servers >= dns_scope_get_n_dns_servers(t->scope))
                return false;
 
        dns_transaction_retry(t, /* next_server= */ true);
        return true;
}
 
static int dns_transaction_maybe_restart(DnsTransaction *t) {
        int r;
 
        assert(t);
 
        /* Restarts the transaction, under a new ID if the feature level of the server changed since we first
         * tried, without changing DNS server. Returns > 0 if the transaction was restarted, 0 if not. */
 
        if (!t->server)
                return 0;
 
        if (t->current_feature_level <= dns_server_possible_feature_level(t->server))
                return 0;
 
        /* The server's current feature level is lower than when we sent the original query. We learnt something from
           the response or possibly an auxiliary DNSSEC response that we didn't know before.  We take that as reason to
           restart the whole transaction. This is a good idea to deal with servers that respond rubbish if we include
           OPT RR or DO bit. One of these cases is documented here, for example:
           https://open.nlnetlabs.nl/pipermail/dnssec-trigger/2014-November/000376.html */
 
        log_debug("Server feature level is now lower than when we began our transaction. Restarting with new ID.");
        dns_transaction_shuffle_id(t);
 
        r = dns_transaction_go(t);
        if (r < 0)
                return r;
 
        return 1;
}
 
static void on_transaction_stream_error(DnsTransaction *t, int error) {
        assert(t);
 
        dns_transaction_close_connection(t, true);
 
        if (ERRNO_IS_DISCONNECT(error)) {
                if (t->scope->protocol == DNS_PROTOCOL_LLMNR) {
                        /* If the LLMNR/TCP connection failed, the host doesn't support LLMNR, and we cannot answer the
                         * question on this scope. */
                        dns_transaction_complete(t, DNS_TRANSACTION_NOT_FOUND);
                        return;
                }
 
                dns_transaction_retry(t, true);
                return;
        }
        if (error != 0)
                dns_transaction_complete_errno(t, error);
}
 
static int dns_transaction_on_stream_packet(DnsTransaction *t, DnsStream *s, DnsPacket *p) {
        bool encrypted;
 
        assert(t);
        assert(s);
        assert(p);
 
        encrypted = s->encrypted;
 
        dns_transaction_close_connection(t, true);
 
        if (dns_packet_validate_reply(p) <= 0) {
                log_debug("Invalid TCP reply packet.");
                dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
                return 0;
        }
 
        dns_scope_check_conflicts(t->scope, p);
 
        t->block_gc++;
        dns_transaction_process_reply(t, p, encrypted);
        t->block_gc--;
 
        /* If the response wasn't useful, then complete the transition
         * now. After all, we are the worst feature set now with TCP
         * sockets, and there's really no point in retrying. */
        if (t->state == DNS_TRANSACTION_PENDING)
                dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
        else
                dns_transaction_gc(t);
 
        return 0;
}
 
static int on_stream_complete(DnsStream *s, int error) {
        assert(s);
 
        if (ERRNO_IS_DISCONNECT(error) && s->protocol != DNS_PROTOCOL_LLMNR) {
                log_debug_errno(error, "Connection failure for DNS TCP stream: %m");
 
                if (error != ECONNRESET && s->transactions) {
                        DnsTransaction *t;
 
                        t = s->transactions;
                        dns_server_packet_lost(t->server, IPPROTO_TCP, t->current_feature_level);
                }
        }
 
        if (error != 0) {
                /* First, detach the stream from the server. Otherwise, transactions attached to this stream
                 * may be restarted by on_transaction_stream_error() below with this stream. */
                dns_stream_detach(s);
 
                /* Do not use LIST_FOREACH() here, as
                 *     on_transaction_stream_error()
                 *         -> dns_transaction_complete_errno()
                 *             -> dns_transaction_free()
                 * may free multiple transactions in the list. */
                DnsTransaction *t;
                while ((t = s->transactions))
                        on_transaction_stream_error(t, error);
        }
 
        return 0;
}
 
static int on_stream_packet(DnsStream *s, DnsPacket *p) {
        DnsTransaction *t;
 
        assert(s);
        assert(s->manager);
        assert(p);
 
        t = hashmap_get(s->manager->dns_transactions, UINT_TO_PTR(DNS_PACKET_ID(p)));
        if (t && t->stream == s) /* Validate that the stream we got this on actually is the stream the
                                  * transaction was using. */
                return dns_transaction_on_stream_packet(t, s, p);
 
        /* Ignore incorrect transaction id as an old transaction can have been canceled. */
        log_debug("Received unexpected TCP reply packet with id %" PRIu16 ", ignoring.", DNS_PACKET_ID(p));
        return 0;
}
 
static uint16_t dns_transaction_port(DnsTransaction *t) {
        assert(t);
 
        if (t->server->port > 0)
                return t->server->port;
 
        return DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) ? 853 : 53;
}
 
static int dns_transaction_emit_tcp(DnsTransaction *t) {
        usec_t stream_timeout_usec = DNS_STREAM_DEFAULT_TIMEOUT_USEC;
        _cleanup_(dns_stream_unrefp) DnsStream *s = NULL;
        _cleanup_close_ int fd = -EBADF;
        union sockaddr_union sa;
        DnsStreamType type;
        int r;
 
        assert(t);
        assert(t->sent);
 
        dns_transaction_close_connection(t, true);
 
        switch (t->scope->protocol) {
 
        case DNS_PROTOCOL_DNS:
                r = dns_transaction_pick_server(t);
                if (r < 0)
                        return r;
 
                if (manager_server_is_stub(t->scope->manager, t->server))
                        return -ELOOP;
 
                if (!t->bypass) {
                        if (!dns_server_dnssec_supported(t->server) && dns_type_is_dnssec(dns_transaction_key(t)->type))
                                return -EOPNOTSUPP;
 
                        r = dns_server_adjust_opt(t->server, t->sent, t->current_feature_level);
                        if (r < 0)
                                return r;
                }
 
                if (t->server->stream && (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) == t->server->stream->encrypted))
                        s = dns_stream_ref(t->server->stream);
                else
                        fd = dns_scope_socket_tcp(t->scope, AF_UNSPEC, NULL, t->server, dns_transaction_port(t), &sa);
 
                /* Lower timeout in DNS-over-TLS opportunistic mode. In environments where DoT is blocked
                 * without ICMP response overly long delays when contacting DoT servers are nasty, in
                 * particular if multiple DNS servers are defined which we try in turn and all are
                 * blocked. Hence, substantially lower the timeout in that case. */
                if (DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level) &&
                    dns_server_get_dns_over_tls_mode(t->server) == DNS_OVER_TLS_OPPORTUNISTIC)
                        stream_timeout_usec = DNS_STREAM_OPPORTUNISTIC_TLS_TIMEOUT_USEC;
 
                type = DNS_STREAM_LOOKUP;
                break;
 
        case DNS_PROTOCOL_LLMNR:
                /* When we already received a reply to this (but it was truncated), send to its sender address */
                if (t->received)
                        fd = dns_scope_socket_tcp(t->scope, t->received->family, &t->received->sender, NULL, t->received->sender_port, &sa);
                else {
                        union in_addr_union address;
                        int family = AF_UNSPEC;
 
                        /* Otherwise, try to talk to the owner of a
                         * the IP address, in case this is a reverse
                         * PTR lookup */
 
                        r = dns_name_address(dns_resource_key_name(dns_transaction_key(t)), &family, &address);
                        if (r < 0)
                                return r;
                        if (r == 0)
                                return -EINVAL;
                        if (family != t->scope->family)
                                return -ESRCH;
 
                        fd = dns_scope_socket_tcp(t->scope, family, &address, NULL, LLMNR_PORT, &sa);
                }
 
                type = DNS_STREAM_LLMNR_SEND;
                break;
 
        default:
                return -EAFNOSUPPORT;
        }
 
        if (!s) {
                if (fd < 0)
                        return fd;
 
                r = dns_stream_new(t->scope->manager, &s, type, t->scope->protocol, fd, &sa,
                                   on_stream_packet, on_stream_complete, stream_timeout_usec);
                if (r < 0)
                        return r;
 
                fd = -EBADF;
 
#if ENABLE_DNS_OVER_TLS
                if (t->scope->protocol == DNS_PROTOCOL_DNS &&
                    DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level)) {
 
                        assert(t->server);
                        r = dnstls_stream_connect_tls(s, t->server);
                        if (r < 0) {
                                /* If libcrypto is not available treat this like a TLS connection loss, so
                                 * that opportunistic DNS-over-TLS downgrades to plaintext instead of
                                 * re-selecting a TLS feature level and failing on every attempt. */
                                if (r == -EOPNOTSUPP) {
                                        log_struct_once(LOG_WARNING,
                                                        LOG_MESSAGE_ID(SD_MESSAGE_MISSING_DEPENDENCY_STR),
                                                        LOG_ITEM("FEATURE=DNS-over-TLS"),
                                                        LOG_MESSAGE("DNS-over-TLS has been requested but the required TLS libraries (libssl/libcrypto) are not installed."));
                                        dns_server_packet_lost(t->server, IPPROTO_TCP, t->current_feature_level);
                                        return -ECONNREFUSED;
                                }
                                return r;
                        }
                }
#endif
 
                if (t->server) {
                        dns_server_unref_stream(t->server);
                        s->server = dns_server_ref(t->server);
                        t->server->stream = dns_stream_ref(s);
                }
 
                /* The interface index is difficult to determine if we are
                 * connecting to the local host, hence fill this in right away
                 * instead of determining it from the socket */
                s->ifindex = dns_scope_ifindex(t->scope);
        }
 
        t->stream = TAKE_PTR(s);
        LIST_PREPEND(transactions_by_stream, t->stream->transactions, t);
 
        r = dns_stream_write_packet(t->stream, t->sent);
        if (r < 0) {
                dns_transaction_close_connection(t, /* use_graveyard= */ false);
                return r;
        }
 
        dns_transaction_reset_answer(t);
 
        t->tried_stream = true;
 
        return 0;
}
 
static void dns_transaction_cache_answer(DnsTransaction *t) {
        assert(t);
 
        /* For mDNS we cache whenever we get the packet, rather than
         * in each transaction. */
        if (!IN_SET(t->scope->protocol, DNS_PROTOCOL_DNS, DNS_PROTOCOL_LLMNR))
                return;
 
        /* Caching disabled? */
        if (t->scope->manager->enable_cache == DNS_CACHE_MODE_NO)
                return;
 
        /* If validation is turned off for this transaction, but DNSSEC is on, then let's not cache this */
        if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_VALIDATE) && t->scope->dnssec_mode != DNSSEC_NO)
                return;
 
        /* Same if the reply could not be validated merely because the query went out without DO (e.g. a
         * bypass query without DO, or one sent while the server was degraded): later lookups may send DO
         * and validate again, and nothing guarantees that the cache gets flushed before they do. */
        if (t->server &&
            t->answer_dnssec_result == DNSSEC_INCOMPATIBLE_SERVER &&
            dns_server_dnssec_supported(t->server))
                return;
 
        /* Packet from localhost? */
        if (!t->scope->manager->cache_from_localhost &&
            in_addr_is_localhost(t->received->family, &t->received->sender) != 0)
                return;
 
        dns_cache_put(&t->scope->cache,
                      t->scope->manager->enable_cache,
                      t->scope->protocol,
                      dns_transaction_key(t),
                      t->answer_rcode,
                      t->answer,
                      /* If neither DO nor EDE is set, the full packet isn't useful to cache */
                      dns_packet_do(t->received) || t->answer_ede_rcode > 0 || t->answer_ede_msg ? t->received : NULL,
                      t->answer_query_flags,
                      t->answer_dnssec_result,
                      t->answer_nsec_ttl,
                      t->received->family,
                      &t->received->sender,
                      t->scope->manager->stale_retention_usec);
}
 
static bool dns_transaction_dnssec_is_live(DnsTransaction *t) {
        DnsTransaction *dt;
 
        assert(t);
 
        SET_FOREACH(dt, t->dnssec_transactions)
                if (DNS_TRANSACTION_IS_LIVE(dt->state))
                        return true;
 
        return false;
}
 
static int dns_transaction_dnssec_ready(DnsTransaction *t) {
        DnsTransaction *dt;
        int r;
 
        assert(t);
 
        /* Checks whether the auxiliary DNSSEC transactions of our transaction have completed, or are still
         * ongoing. Returns 0, if we aren't ready for the DNSSEC validation, positive if we are. */
 
        SET_FOREACH(dt, t->dnssec_transactions) {
 
                switch (dt->state) {
 
                case DNS_TRANSACTION_NULL:
                case DNS_TRANSACTION_PENDING:
                case DNS_TRANSACTION_VALIDATING:
                        /* Still ongoing */
                        return 0;
 
                case DNS_TRANSACTION_RCODE_FAILURE:
                        if (!IN_SET(dt->answer_rcode, DNS_RCODE_NXDOMAIN, DNS_RCODE_SERVFAIL)) {
                                log_debug("Auxiliary DNSSEC RR query failed with rcode=%s.", FORMAT_DNS_RCODE(dt->answer_rcode));
                                goto fail;
                        }
 
                        /* Fall-through: NXDOMAIN/SERVFAIL is good enough for us. This is because some DNS servers
                         * erroneously return NXDOMAIN/SERVFAIL for empty non-terminals (Akamai...) or missing DS
                         * records (Facebook), and we need to handle that nicely, when asking for parent SOA or similar
                         * RRs to make unsigned proofs. */
 
                case DNS_TRANSACTION_SUCCESS:
                        /* All good. */
                        break;
 
                case DNS_TRANSACTION_DNSSEC_FAILED:
                        /* We handle DNSSEC failures different from other errors, as we care about the DNSSEC
                         * validation result */
 
                        log_debug("Auxiliary DNSSEC RR query failed validation: %s%s%s%s%s%s",
                                  dnssec_result_to_string(dt->answer_dnssec_result),
                                  dt->answer_ede_rcode >= 0 ? " (" : "",
                                  dt->answer_ede_rcode >= 0 ? FORMAT_DNS_EDE_RCODE(dt->answer_ede_rcode) : "",
                                  (dt->answer_ede_rcode >= 0 && !isempty(dt->answer_ede_msg)) ? ": " : "",
                                  dt->answer_ede_rcode >= 0 ? strempty(dt->answer_ede_msg) : "",
                                  dt->answer_ede_rcode >= 0 ? ")" : "");
 
                        /* Copy error code over */
                        t->answer_dnssec_result = dt->answer_dnssec_result;
                        t->answer_ede_rcode = dt->answer_ede_rcode;
                        r = free_and_strdup(&t->answer_ede_msg, dt->answer_ede_msg);
                        if (r < 0)
                                log_oom_debug();
 
                        /* The answer would normally be replaced by the validated subset, but at this point
                         * we aren't going to bother validating the rest, so just drop it. */
                        t->answer = dns_answer_unref(t->answer);
 
                        dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
                        return 0;
 
                default:
                        log_debug("Auxiliary DNSSEC RR query failed with %s", dns_transaction_state_to_string(dt->state));
                        goto fail;
                }
        }
 
        /* All is ready, we can go and validate */
        return 1;
 
fail:
        /* Some auxiliary DNSSEC transaction failed for some reason. Maybe we learned something about the
         * server due to this failure, and the feature level is now different? Let's see and restart the
         * transaction if so. If not, let's propagate the auxiliary failure.
         *
         * This is particularly relevant if an auxiliary request figured out that DNSSEC doesn't work, and we
         * are in permissive DNSSEC mode, and thus should restart things without DNSSEC magic. */
        r = dns_transaction_maybe_restart(t);
        if (r < 0)
                return r;
        if (r > 0)
                return 0; /* don't validate just yet, we restarted things */
 
        t->answer_dnssec_result = DNSSEC_FAILED_AUXILIARY;
        dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
        return 0;
}
 
static void dns_transaction_process_dnssec(DnsTransaction *t) {
        int r;
 
        assert(t);
 
        /* Are there ongoing DNSSEC transactions? If so, let's wait for them. */
        r = dns_transaction_dnssec_ready(t);
        if (r < 0)
                goto fail;
        if (r == 0) /* We aren't ready yet (or one of our auxiliary transactions failed, and we shouldn't validate now */
                return;
 
        /* See if we learnt things from the additional DNSSEC transactions, that we didn't know before, and better
         * restart the lookup immediately. */
        r = dns_transaction_maybe_restart(t);
        if (r < 0)
                goto fail;
        if (r > 0) /* Transaction got restarted... */
                return;
 
        /* All our auxiliary DNSSEC transactions are complete now. Try