HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/resolve/resolved-dns-transaction.c
Git blob: 7acad458341057b625463484a08179dca3da17c4
Lines 1001–2000 of 3,879
* to validate our RRset now. */
r = dns_transaction_validate_dnssec(t);
if (r == -EBADMSG) {
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
if (r < 0)
goto fail;
if (t->answer_dnssec_result == DNSSEC_INCOMPATIBLE_SERVER &&
t->scope->dnssec_mode == DNSSEC_YES) {
/* We are not in automatic downgrade mode, and the server is bad. Let's try a different server, maybe
* that works. */
if (dns_transaction_limited_retry(t))
return;
/* OK, let's give up, apparently all servers we tried didn't work. */
dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
return;
}
if (!IN_SET(t->answer_dnssec_result,
_DNSSEC_RESULT_INVALID, /* No DNSSEC validation enabled */
DNSSEC_VALIDATED, /* Answer is signed and validated successfully */
DNSSEC_UNSIGNED, /* Answer is right-fully unsigned */
DNSSEC_INCOMPATIBLE_SERVER)) { /* Server does not do DNSSEC (Yay, we are downgrade attack vulnerable!) */
dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
return;
}
/* Don't blame the server if the query merely went out below DO, it may support DNSSEC just fine. */
if (t->answer_dnssec_result == DNSSEC_INCOMPATIBLE_SERVER && !dns_server_dnssec_supported(t->server))
dns_server_warn_downgrade(t->server);
dns_transaction_cache_answer(t);
if (t->answer_rcode == DNS_RCODE_SUCCESS)
dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
else
dns_transaction_complete(t, DNS_TRANSACTION_RCODE_FAILURE);
return;
fail:
dns_transaction_complete_errno(t, r);
}
static int dns_transaction_has_positive_answer(DnsTransaction *t, DnsAnswerFlags *flags) {
int r;
assert(t);
/* Checks whether the answer is positive, i.e. either a direct
* answer to the question, or a CNAME/DNAME for it */
r = dns_answer_match_key(t->answer, dns_transaction_key(t), flags);
if (r != 0)
return r;
r = dns_answer_find_cname_or_dname(t->answer, dns_transaction_key(t), NULL, flags);
if (r != 0)
return r;
return false;
}
static int dns_transaction_fix_rcode(DnsTransaction *t) {
int r;
assert(t);
/* Fix up the RCODE to SUCCESS if we get at least one matching RR in a response. Note that this contradicts the
* DNS RFCs a bit. Specifically, RFC 6604 Section 3 clarifies that the RCODE shall say something about a
* CNAME/DNAME chain element coming after the last chain element contained in the message, and not the first
* one included. However, it also indicates that not all DNS servers implement this correctly. Moreover, when
* using DNSSEC we usually only can prove the first element of a CNAME/DNAME chain anyway, hence let's settle
* on always processing the RCODE as referring to the immediate look-up we do, i.e. the first element of a
* CNAME/DNAME chain. This way, we uniformly handle CNAME/DNAME chains, regardless if the DNS server
* incorrectly implements RCODE, whether DNSSEC is in use, or whether the DNS server only supplied us with an
* incomplete CNAME/DNAME chain.
*
* Or in other words: if we get at least one positive reply in a message we patch NXDOMAIN to become SUCCESS,
* and then rely on the CNAME chasing logic to figure out that there's actually a CNAME error with a new
* lookup. */
if (t->answer_rcode != DNS_RCODE_NXDOMAIN)
return 0;
r = dns_transaction_has_positive_answer(t, NULL);
if (r <= 0)
return r;
t->answer_rcode = DNS_RCODE_SUCCESS;
return 0;
}
void dns_transaction_process_reply(DnsTransaction *t, DnsPacket *p, bool encrypted) {
bool retry_with_tcp = false;
int r;
assert(t);
assert(p);
assert(t->scope);
assert(t->scope->manager);
if (t->state != DNS_TRANSACTION_PENDING)
return;
/* Increment the total failure counter only when it is the first attempt at querying and the upstream
* server returns a failure response code. This ensures a more accurate count of the number of queries
* that received a failure response code, as it doesn't consider retries. */
if (t->n_attempts == 1 && !IN_SET(dns_packet_rcode(p), DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN))
t->scope->manager->n_failure_responses_total++;
/* 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("Processing incoming packet of size %zu on transaction %" PRIu16" (rcode=%s).",
p->size,
t->id, FORMAT_DNS_RCODE(dns_packet_rcode(p)));
switch (t->scope->protocol) {
case DNS_PROTOCOL_LLMNR:
/* For LLMNR we will not accept any packets from other interfaces */
if (p->ifindex != dns_scope_ifindex(t->scope))
return;
if (p->family != t->scope->family)
return;
/* Tentative packets are not full responses but still
* useful for identifying uniqueness conflicts during
* probing. */
if (DNS_PACKET_LLMNR_T(p)) {
dns_transaction_tentative(t, p);
return;
}
break;
case DNS_PROTOCOL_MDNS:
/* For mDNS we will not accept any packets from other interfaces */
if (p->ifindex != dns_scope_ifindex(t->scope))
return;
if (p->family != t->scope->family)
return;
break;
case DNS_PROTOCOL_DNS:
/* Note that we do not need to verify the
* addresses/port numbers of incoming traffic, as we
* invoked connect() on our UDP socket in which case
* the kernel already does the needed verification for
* us. */
break;
default:
assert_not_reached();
}
if (t->received != p)
DNS_PACKET_REPLACE(t->received, dns_packet_ref(p));
t->answer_source = DNS_TRANSACTION_NETWORK;
if (p->ipproto == IPPROTO_TCP) {
if (DNS_PACKET_TC(p)) {
/* Truncated via TCP? Somebody must be fucking with us */
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
if (DNS_PACKET_ID(p) != t->id) {
/* Not the reply to our query? Somebody must be fucking with us */
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
}
if (DNS_PACKET_TC(p)) {
/* Truncated packets for mDNS are not allowed. Give up immediately. */
if (t->scope->protocol == DNS_PROTOCOL_MDNS) {
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
/* Response was truncated, let's try again with good old TCP */
log_debug("Reply truncated, retrying via TCP.");
retry_with_tcp = true;
} else if (t->scope->protocol == DNS_PROTOCOL_DNS &&
DNS_PACKET_IS_FRAGMENTED(p)) {
/* Report the fragment size, so that we downgrade from LARGE to regular EDNS0 if needed */
if (t->server)
dns_server_packet_udp_fragmented(t->server, dns_packet_size_unfragmented(p));
if (t->current_feature_level > DNS_SERVER_FEATURE_LEVEL_UDP) {
/* Packet was fragmented. Let's retry with TCP to avoid fragmentation attack
* issues. (We don't do that on the lowest feature level however, since crappy DNS
* servers often do not implement TCP, hence falling back to TCP on fragmentation is
* counter-productive there.) */
log_debug("Reply fragmented, retrying via TCP. (Largest fragment size: %zu; Datagram size: %zu)",
p->fragsize, p->size);
retry_with_tcp = true;
}
}
if (retry_with_tcp) {
r = dns_transaction_emit_tcp(t);
if (r == -ESRCH) {
/* No servers found? Damn! */
dns_transaction_complete(t, DNS_TRANSACTION_NO_SERVERS);
return;
}
if (r == -EOPNOTSUPP) {
/* Tried to ask for DNSSEC RRs, on a server that doesn't do DNSSEC */
dns_transaction_complete(t, DNS_TRANSACTION_RR_TYPE_UNSUPPORTED);
return;
}
if (r < 0) {
/* On LLMNR, if we cannot connect to the host,
* we immediately give up */
if (t->scope->protocol != DNS_PROTOCOL_DNS)
goto fail;
/* On DNS, couldn't send? Try immediately again, with a new server */
if (dns_transaction_limited_retry(t))
return;
/* No new server to try, give up */
dns_transaction_complete(t, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED);
}
return;
}
/* After the superficial checks, actually parse the message. */
r = dns_packet_extract(p);
if (r < 0) {
if (t->server) {
dns_server_packet_invalid(t->server, t->current_feature_level);
r = dns_transaction_maybe_restart(t);
if (r < 0)
goto fail;
if (r > 0) /* Transaction got restarted... */
return;
}
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
switch (t->scope->protocol) {
case DNS_PROTOCOL_DNS: {
assert(t->server);
(void) dns_packet_ede_rcode(p, &t->answer_ede_rcode, &t->answer_ede_msg);
if (!t->bypass &&
IN_SET(dns_packet_rcode(p), DNS_RCODE_FORMERR, DNS_RCODE_SERVFAIL, DNS_RCODE_NOTIMP)) {
/* If the server has replied with detailed error data, using a degraded feature set
* will likely not help anyone. Examine the detailed error to determine the best
* course of action. */
if (t->answer_ede_rcode >= 0 && dns_packet_rcode(p) == DNS_RCODE_SERVFAIL) {
/* These codes are related to DNSSEC configuration errors. If accurate,
* this is the domain operator's problem, and retrying won't help. */
if (dns_ede_rcode_is_dnssec(t->answer_ede_rcode)) {
log_debug("Server returned error: %s (%s%s%s). Lookup failed.",
FORMAT_DNS_RCODE(dns_packet_rcode(p)),
FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
isempty(t->answer_ede_msg) ? "" : ": ",
strempty(t->answer_ede_msg));
t->answer_dnssec_result = DNSSEC_UPSTREAM_FAILURE;
dns_transaction_complete(t, DNS_TRANSACTION_DNSSEC_FAILED);
return;
}
/* These codes probably indicate a transient error. Let's try again. */
if (t->answer_ede_rcode == DNS_EDE_RCODE_NOT_READY) {
log_debug("Server returned error: %s (%s%s%s), retrying transaction.",
FORMAT_DNS_RCODE(dns_packet_rcode(p)),
FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
isempty(t->answer_ede_msg) ? "" : ": ",
strempty(t->answer_ede_msg));
dns_transaction_retry(t, false);
return;
}
/* OK, the query failed, but we still shouldn't degrade the feature set for
* this server. */
log_debug("Server returned error: %s (%s%s%s)",
FORMAT_DNS_RCODE(dns_packet_rcode(p)),
FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode),
isempty(t->answer_ede_msg) ? "" : ": ",
strempty(t->answer_ede_msg));
break;
}
/* Request failed, immediately try again with reduced features */
if (t->current_feature_level <= DNS_SERVER_FEATURE_LEVEL_UDP) {
/* This was already at UDP feature level? If so, it doesn't make sense to downgrade
* this transaction anymore, but let's see if it might make sense to send the request
* to a different DNS server instead. If not let's process the response, and accept the
* rcode. Note that we don't retry on TCP, since that's a suitable way to mitigate
* packet loss, but is not going to give us better rcodes should we actually have
* managed to get them already at UDP level. */
if (dns_transaction_limited_retry(t))
return;
/* Give up, accept the rcode */
log_debug("Server returned error: %s", FORMAT_DNS_RCODE(dns_packet_rcode(p)));
break;
}
/* SERVFAIL can happen for many reasons and may be transient.
* To avoid unnecessary downgrades retry once with the initial level.
* Check for clamp_feature_level_servfail having an invalid value as a sign that this is the
* first attempt to downgrade. If so, clamp to the current value so that the transaction
* is retried without actually downgrading. If the next try also fails we will downgrade by
* hitting the else branch below. */
if (dns_packet_rcode(p) == DNS_RCODE_SERVFAIL &&
t->clamp_feature_level_servfail < 0) {
t->clamp_feature_level_servfail = t->current_feature_level;
log_debug("Server returned error %s, retrying transaction.",
FORMAT_DNS_RCODE(dns_packet_rcode(p)));
} else {
/* Reduce this feature level by one and try again. */
switch (t->current_feature_level) {
case DNS_SERVER_FEATURE_LEVEL_TLS_DO:
t->clamp_feature_level_servfail = DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN;
break;
case DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN + 1:
/* Skip plain TLS when TLS is not supported */
t->clamp_feature_level_servfail = DNS_SERVER_FEATURE_LEVEL_TLS_PLAIN - 1;
break;
default:
t->clamp_feature_level_servfail = t->current_feature_level - 1;
}
log_debug("Server returned error %s, retrying transaction with reduced feature level %s.",
FORMAT_DNS_RCODE(dns_packet_rcode(p)),
dns_server_feature_level_to_string(t->clamp_feature_level_servfail));
}
dns_transaction_retry(t, false /* use the same server */);
return;
}
if (dns_packet_rcode(p) == DNS_RCODE_REFUSED) {
/* This server refused our request? If so, try again, use a different server */
if (t->answer_ede_rcode >= 0)
log_debug("Server returned REFUSED (%s), switching servers, and retrying.",
FORMAT_DNS_EDE_RCODE(t->answer_ede_rcode));
else
log_debug("Server returned REFUSED, switching servers, and retrying.");
if (dns_transaction_limited_retry(t))
return;
break;
}
if (DNS_PACKET_TC(p))
dns_server_packet_truncated(t->server, t->current_feature_level);
break;
}
case DNS_PROTOCOL_LLMNR:
case DNS_PROTOCOL_MDNS:
dns_scope_packet_received(t->scope, p->timestamp - t->start_usec);
break;
default:
assert_not_reached();
}
if (t->server) {
/* Report that we successfully received a valid packet with a good rcode after we initially got a bad
* rcode and subsequently downgraded the protocol */
if (IN_SET(dns_packet_rcode(p), DNS_RCODE_SUCCESS, DNS_RCODE_NXDOMAIN) &&
t->clamp_feature_level_servfail != _DNS_SERVER_FEATURE_LEVEL_INVALID)
dns_server_packet_rcode_downgrade(t->server, t->clamp_feature_level_servfail);
/* Report that the OPT RR was missing */
if (!p->opt)
dns_server_packet_bad_opt(t->server, t->current_feature_level);
/* Report that the server didn't copy our query DO bit from request to response */
if (dns_packet_do(t->sent) && !dns_packet_do(t->received))
dns_server_packet_do_off(t->server, t->current_feature_level);
/* Report that we successfully received a packet. We keep track of the largest packet
* size/fragment size we got. Which is useful for announcing the EDNS(0) packet size we can
* receive to our server. */
dns_server_packet_received(t->server, p->ipproto, t->current_feature_level, dns_packet_size_unfragmented(p));
}
/* See if we know things we didn't know before that indicate we better restart the lookup immediately. */
r = dns_transaction_maybe_restart(t);
if (r < 0)
goto fail;
if (r > 0) /* Transaction got restarted... */
return;
/* When dealing with protocols other than mDNS only consider responses with equivalent query section
* to the request. For mDNS this check doesn't make sense, because the section 6 of RFC6762 states
* that "Multicast DNS responses MUST NOT contain any questions in the Question Section". */
if (t->scope->protocol != DNS_PROTOCOL_MDNS) {
r = dns_packet_is_reply_for(p, dns_transaction_key(t));
if (r < 0)
goto fail;
if (r == 0) {
dns_transaction_complete(t, DNS_TRANSACTION_INVALID_REPLY);
return;
}
}
/* Install the answer as answer to the transaction. We ref the answer twice here: the main `answer`
* field is later replaced by the DNSSEC validated subset. The 'answer_auxiliary' field carries the
* original complete record set, including RRSIG and friends. We use this when passing data to
* clients that ask for DNSSEC metadata. */
DNS_ANSWER_REPLACE(t->answer, dns_answer_ref(p->answer));
t->answer_rcode = dns_packet_rcode(p);
t->answer_dnssec_result = _DNSSEC_RESULT_INVALID;
SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
SET_FLAG(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, encrypted);
r = dns_transaction_fix_rcode(t);
if (r < 0)
goto fail;
/* Block GC while starting requests for additional DNSSEC RRs */
t->block_gc++;
r = dns_transaction_request_dnssec_keys(t);
t->block_gc--;
/* Maybe the transaction is ready for GC'ing now? If so, free it and return. */
if (!dns_transaction_gc(t))
return;
/* Requesting additional keys might have resulted in this transaction to fail, since the auxiliary
* request failed for some reason. If so, we are not in pending state anymore, and we should exit
* quickly. */
if (t->state != DNS_TRANSACTION_PENDING)
return;
if (r < 0)
goto fail;
if (r > 0) {
/* There are DNSSEC transactions pending now. Update the state accordingly. */
t->state = DNS_TRANSACTION_VALIDATING;
dns_transaction_close_connection(t, true);
dns_transaction_stop_timeout(t);
return;
}
dns_transaction_process_dnssec(t);
return;
fail:
dns_transaction_complete_errno(t, r);
}
static int on_dns_packet(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
_cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
DnsTransaction *t = ASSERT_PTR(userdata);
int r;
assert(t->scope);
r = manager_recv(t->scope->manager, fd, DNS_PROTOCOL_DNS, &p);
if (r < 0) {
if (ERRNO_IS_DISCONNECT(r)) {
usec_t usec;
/* UDP connection failures get reported via ICMP and then are possibly delivered to us on the
* next recvmsg(). Treat this like a lost packet. */
log_debug_errno(r, "Connection failure for DNS UDP packet: %m");
assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &usec) >= 0);
dns_server_packet_lost(t->server, IPPROTO_UDP, t->current_feature_level);
dns_transaction_close_connection(t, /* use_graveyard= */ false);
if (dns_transaction_limited_retry(t)) /* Try a different server */
return 0;
}
dns_transaction_complete_errno(t, r);
return 0;
}
if (r == 0)
/* Spurious wakeup without any data */
return 0;
r = dns_packet_validate_reply(p);
if (r < 0) {
log_debug_errno(r, "Received invalid DNS packet as response, ignoring: %m");
return 0;
}
if (r == 0) {
log_debug("Received inappropriate DNS packet as response, ignoring.");
return 0;
}
if (DNS_PACKET_ID(p) != t->id) {
log_debug("Received packet with incorrect transaction ID, ignoring.");
return 0;
}
dns_transaction_process_reply(t, p, false);
return 0;
}
static int dns_transaction_emit_udp(DnsTransaction *t) {
int r;
assert(t);
if (t->scope->protocol == 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->current_feature_level < DNS_SERVER_FEATURE_LEVEL_UDP || DNS_SERVER_FEATURE_LEVEL_IS_TLS(t->current_feature_level))
return -EAGAIN; /* Sorry, can't do UDP, try TCP! */
if (!t->bypass && !dns_server_dnssec_supported(t->server) && dns_type_is_dnssec(dns_transaction_key(t)->type))
return -EOPNOTSUPP;
if (r > 0 || t->dns_udp_fd < 0) { /* Server changed, or no connection yet. */
int fd;
dns_transaction_close_connection(t, true);
/* Before we allocate a new UDP socket, let's process the graveyard a bit to free some fds */
manager_socket_graveyard_process(t->scope->manager);
fd = dns_scope_socket_udp(t->scope, t->server);
if (fd < 0)
return fd;
r = sd_event_add_io(t->scope->manager->event, &t->dns_udp_event_source, fd, EPOLLIN, on_dns_packet, t);
if (r < 0) {
safe_close(fd);
return r;
}
(void) sd_event_source_set_description(t->dns_udp_event_source, "dns-transaction-udp");
t->dns_udp_fd = fd;
}
if (!t->bypass) {
r = dns_server_adjust_opt(t->server, t->sent, t->current_feature_level);
if (r < 0)
return r;
}
} else
dns_transaction_close_connection(t, true);
r = dns_scope_emit_udp(t->scope, t->dns_udp_fd, t->server ? t->server->family : AF_UNSPEC, t->sent);
if (r < 0)
return r;
dns_transaction_reset_answer(t);
return 0;
}
static int on_transaction_timeout(sd_event_source *s, usec_t usec, void *userdata) {
DnsTransaction *t = ASSERT_PTR(userdata);
assert(s);
t->seen_timeout = true;
if (t->initial_jitter_scheduled && !t->initial_jitter_elapsed) {
log_debug("Initial jitter phase for transaction %" PRIu16 " elapsed.", t->id);
t->initial_jitter_elapsed = true;
} else {
/* Timeout reached? Increase the timeout for the server used */
switch (t->scope->protocol) {
case DNS_PROTOCOL_DNS:
assert(t->server);
dns_server_packet_lost(t->server, t->stream ? IPPROTO_TCP : IPPROTO_UDP, t->current_feature_level);
/* If the server's feature level changed meanwhile (packet loss degraded it, or the
* grace period ended), the retry goes out at a different level, possibly with or
* without DO. Use a new connection and ID for it, like
* dns_transaction_maybe_restart() does, so that a late reply to an earlier attempt
* cannot pass for a reply to the retry. Close the connection first, while t->sent
* still refers to the packet that may be queued on it. */
if (t->current_feature_level != dns_server_possible_feature_level(t->server)) {
dns_transaction_close_connection(t, /* use_graveyard= */ true);
dns_transaction_shuffle_id(t);
}
break;
case DNS_PROTOCOL_LLMNR:
case DNS_PROTOCOL_MDNS:
dns_scope_packet_lost(t->scope, usec - t->start_usec);
break;
default:
assert_not_reached();
}
log_debug("Timeout reached on transaction %" PRIu16 ".", t->id);
}
dns_transaction_retry(t, /* next_server= */ true); /* try a different server, but given this means
* packet loss, let's do so even if we already
* tried a bunch */
return 0;
}
static int dns_transaction_setup_timeout(
DnsTransaction *t,
usec_t timeout_usec /* relative */,
usec_t next_usec /* CLOCK_BOOTTIME */) {
int r;
assert(t);
dns_transaction_stop_timeout(t);
r = sd_event_add_time_relative(
t->scope->manager->event,
&t->timeout_event_source,
CLOCK_BOOTTIME,
timeout_usec, 0,
on_transaction_timeout, t);
if (r < 0)
return r;
(void) sd_event_source_set_description(t->timeout_event_source, "dns-transaction-timeout");
t->next_attempt_after = next_usec;
t->state = DNS_TRANSACTION_PENDING;
return 0;
}
static usec_t transaction_get_resend_timeout(DnsTransaction *t) {
assert(t);
assert(t->scope);
switch (t->scope->protocol) {
case DNS_PROTOCOL_DNS:
if (t->stream)
return TRANSACTION_TCP_TIMEOUT_USEC;
return TRANSACTION_UDP_TIMEOUT_USEC;
case DNS_PROTOCOL_MDNS:
if (t->probing)
return MDNS_PROBING_INTERVAL_USEC;
/* See RFC 6762 Section 5.1 suggests that timeout should be a few seconds. */
assert(t->n_attempts > 0);
return (1 << (t->n_attempts - 1)) * USEC_PER_SEC;
case DNS_PROTOCOL_LLMNR:
return t->scope->resend_timeout;
default:
assert_not_reached();
}
}
static void dns_transaction_randomize_answer(DnsTransaction *t) {
int r;
assert(t);
/* Randomizes the order of the answer array. This is done for all cached responses, so that we return
* a different order each time. We do this only for DNS traffic, in order to do some minimal, crappy
* load balancing. We don't do this for LLMNR or mDNS, since the order (preferring link-local
* addresses, and such like) might have meaning there, and load balancing is pointless. */
if (t->scope->protocol != DNS_PROTOCOL_DNS)
return;
/* No point in randomizing, if there's just one RR */
if (dns_answer_size(t->answer) <= 1)
return;
r = dns_answer_reserve_or_clone(&t->answer, 0);
if (r < 0) /* If this fails, just don't randomize, this is non-essential stuff after all */
return (void) log_debug_errno(r, "Failed to clone answer record, not randomizing RR order of answer: %m");
dns_answer_randomize(t->answer);
}
static int dns_transaction_prepare(DnsTransaction *t, usec_t ts) {
int r;
assert(t);
/* Returns 0 if dns_transaction_complete() has been called. In that case the transaction and query
* candidate objects may have been invalidated and must not be accessed. Returns 1 if the transaction
* has been prepared. */
dns_transaction_stop_timeout(t);
if (t->n_attempts == 1 && t->seen_timeout)
t->scope->manager->n_timeouts_total++;
if (!dns_scope_network_good(t->scope)) {
dns_transaction_complete(t, DNS_TRANSACTION_NETWORK_DOWN);
return 0;
}
if (t->n_attempts >= dns_transaction_attempts_max(t->scope->protocol, t->query_flags)) {
DnsTransactionState result;
if (t->scope->protocol == DNS_PROTOCOL_LLMNR)
/* If we didn't find anything on LLMNR, it's not an error, but a failure to resolve
* the name. */
result = DNS_TRANSACTION_NOT_FOUND;
else
result = DNS_TRANSACTION_ATTEMPTS_MAX_REACHED;
dns_transaction_complete(t, result);
return 0;
}
if (t->scope->protocol == DNS_PROTOCOL_LLMNR && t->tried_stream) {
/* If we already tried via a stream, then we don't
* retry on LLMNR. See RFC 4795, Section 2.7. */
dns_transaction_complete(t, DNS_TRANSACTION_ATTEMPTS_MAX_REACHED);
return 0;
}
t->n_attempts++;
t->start_usec = ts;
dns_transaction_reset_answer(t);
dns_transaction_flush_dnssec_transactions(t);
/* Check the trust anchor. Do so only on classic DNS, since DNSSEC does not apply otherwise. */
if (t->scope->protocol == DNS_PROTOCOL_DNS &&
!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_TRUST_ANCHOR)) {
r = dns_trust_anchor_lookup_positive(&t->scope->manager->trust_anchor, dns_transaction_key(t), &t->answer);
if (r < 0)
return r;
if (r > 0) {
t->answer_rcode = DNS_RCODE_SUCCESS;
t->answer_source = DNS_TRANSACTION_TRUST_ANCHOR;
SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL, true);
dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
return 0;
}
if (dns_name_is_root(dns_resource_key_name(dns_transaction_key(t))) &&
dns_transaction_key(t)->type == DNS_TYPE_DS) {
/* Hmm, this is a request for the root DS? A DS RR doesn't exist in the root zone,
* and if our trust anchor didn't know it either, this means we cannot do any DNSSEC
* logic anymore. */
if (t->scope->dnssec_mode == DNSSEC_ALLOW_DOWNGRADE) {
/* We are in downgrade mode. In this case, synthesize an unsigned empty
* response, so that the any lookup depending on this one can continue
* assuming there was no DS, and hence the root zone was unsigned. */
t->answer_rcode = DNS_RCODE_SUCCESS;
t->answer_source = DNS_TRANSACTION_TRUST_ANCHOR;
SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED, false);
SET_FLAG(t->answer_query_flags, SD_RESOLVED_CONFIDENTIAL, true);
dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
} else
/* If we are not in downgrade mode, then fail the lookup, because we cannot
* reasonably answer it. There might be DS RRs, but we don't know them, and
* the DNS server won't tell them to us (and even if it would, we couldn't
* validate and trust them. */
dns_transaction_complete(t, DNS_TRANSACTION_NO_TRUST_ANCHOR);
return 0;
}
}
/* Check the zone. */
if (!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_ZONE)) {
r = dns_zone_lookup(&t->scope->zone, dns_transaction_key(t), dns_scope_ifindex(t->scope), &t->answer, NULL, NULL);
if (r < 0)
return r;
if (r > 0) {
t->answer_rcode = DNS_RCODE_SUCCESS;
t->answer_source = DNS_TRANSACTION_ZONE;
SET_FLAG(t->answer_query_flags, SD_RESOLVED_AUTHENTICATED|SD_RESOLVED_CONFIDENTIAL, true);
dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
return 0;
}
}
/* Check the cache. */
if (!FLAGS_SET(t->query_flags, SD_RESOLVED_NO_CACHE)) {
/* Before trying the cache, let's make sure we figured out a server to use. Should this cause
* a change of server this might flush the cache. */
(void) dns_scope_get_dns_server(t->scope);
/* Let's then prune all outdated entries */
dns_cache_prune(&t->scope->cache);
/* For the initial attempt or when no stale data is requested, disable serve stale
* and answer the question from the cache (honors ttl property).
* On the second attempt, if StaleRetentionSec is greater than zero,
* try to answer the question using stale data (honors until property).
*
* Serving stale data is a fallback for unicast DNS, where a retry means the configured
* server did not respond. The link-local protocols have no such server: a retry there
* means no peer answered, and for mDNS RFC 6762 treats TTL expiry as a presence signal.
* Hence never serve stale data on those scopes. */
uint64_t query_flags = t->query_flags;
if (t->n_attempts == 1 ||
t->scope->protocol != DNS_PROTOCOL_DNS ||
t->scope->manager->stale_retention_usec == 0)
query_flags |= SD_RESOLVED_NO_STALE;
r = dns_cache_lookup(
&t->scope->cache,
dns_transaction_key(t),
query_flags,
&t->answer_rcode,
&t->answer,
&t->received,
&t->answer_query_flags,
&t->answer_dnssec_result);
if (r < 0)
return r;
if (r > 0) {
dns_transaction_randomize_answer(t);
if (t->bypass && t->scope->protocol == DNS_PROTOCOL_DNS && !t->received)
/* When bypass mode is on, do not use cached data unless it came with a full
* packet. */
dns_transaction_reset_answer(t);
else {
if (t->n_attempts > 1 && !FLAGS_SET(query_flags, SD_RESOLVED_NO_STALE)) {
if (t->answer_rcode == DNS_RCODE_SUCCESS) {
if (t->seen_timeout)
t->scope->manager->n_timeouts_served_stale_total++;
else
t->scope->manager->n_failure_responses_served_stale_total++;
}
char key_str[DNS_RESOURCE_KEY_STRING_MAX];
log_debug("Serve Stale response rcode=%s for %s",
FORMAT_DNS_RCODE(t->answer_rcode),
dns_resource_key_to_string(dns_transaction_key(t), key_str, sizeof key_str));
}
t->answer_source = DNS_TRANSACTION_CACHE;
if (t->answer_rcode == DNS_RCODE_SUCCESS)
dns_transaction_complete(t, DNS_TRANSACTION_SUCCESS);
else {
if (t->received)
(void) dns_packet_ede_rcode(t->received, &t->answer_ede_rcode, &t->answer_ede_msg);
dns_transaction_complete(t, DNS_TRANSACTION_RCODE_FAILURE);
}
return 0;
}
}
}
if (FLAGS_SET(t->query_flags, SD_RESOLVED_NO_NETWORK)) {
dns_transaction_complete(t, DNS_TRANSACTION_NO_SOURCE);
return 0;
}
return 1;
}
static int dns_packet_append_zone(DnsPacket *p, DnsTransaction *t, DnsResourceKey *k, unsigned *nscount) {
_cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
bool tentative;
int r;
assert(p);
assert(t);
assert(k);
if (k->type != DNS_TYPE_ANY)
return 0;
r = dns_zone_lookup(&t->scope->zone, k, t->scope->link->ifindex, &answer, NULL, &tentative);
if (r < 0)
return r;
return dns_packet_append_answer(p, answer, nscount);
}
static int mdns_make_dummy_packet(DnsTransaction *t, DnsPacket **ret_packet, Set **ret_keys) {
_cleanup_(dns_packet_unrefp) DnsPacket *p = NULL;
_cleanup_set_free_ Set *keys = NULL;
bool add_known_answers = false;
unsigned qdcount;
usec_t ts;
int r;
assert(t);
assert(t->scope);
assert(t->scope->protocol == DNS_PROTOCOL_MDNS);
assert(ret_packet);
assert(ret_keys);
r = dns_packet_new_query(&p, t->scope->protocol, 0, false);
if (r < 0)
return r;
r = dns_packet_append_key(p, dns_transaction_key(t), 0, NULL);
if (r < 0)
return r;
qdcount = 1;
if (dns_key_is_shared(dns_transaction_key(t)))
add_known_answers = true;
r = dns_packet_append_zone(p, t, dns_transaction_key(t), NULL);
if (r < 0)
return r;
/* Save appended keys */
r = set_ensure_put(&keys, &dns_resource_key_hash_ops, dns_transaction_key(t));
if (r < 0)
return r;
assert_se(sd_event_now(t->scope->manager->event, CLOCK_BOOTTIME, &ts) >= 0);
LIST_FOREACH(transactions_by_scope, other, t->scope->transactions) {
/* Skip ourselves */
if (other == t)
continue;
if (other->state != DNS_TRANSACTION_PENDING)
continue;
if (other->next_attempt_after > ts)
continue;
if (!set_contains(keys, dns_transaction_key(other))) {
size_t saved_packet_size;
r = dns_packet_append_key(p, dns_transaction_key(other), 0, &saved_packet_size);
/* If we can't stuff more questions into the packet, just give up.
* One of the 'other' transactions will fire later and take care of the rest. */
if (r == -EMSGSIZE)
break;
if (r < 0)
return r;
r = dns_packet_append_zone(p, t, dns_transaction_key(other), NULL);
if (r == -EMSGSIZE) {
dns_packet_truncate(p, saved_packet_size);
break;
}
if (r < 0)
return r;
r = set_ensure_put(&keys, &dns_resource_key_hash_ops, dns_transaction_key(other));
if (r < 0)
return r;
}
r = dns_transaction_prepare(other, ts);
if (r < 0)
return r;
if (r == 0)
/* In this case, not only this transaction, but multiple transactions may be