Skip to content

DNS (pace/dns.hpp)

简体中文 · Reference

Overview

Enable the dns config (dns = true) for the native asynchronous stub resolver. It consults numeric addresses and the hosts file for address lookups, then asks the configured recursive servers. Network I/O, retries and deadlines run on the reactor. Reading system configuration and the hosts file is synchronous.

Synopsis

#include <pace/dns.hpp>

pace::task<void> lookup(pace::io_context& io)
{
    pace::dns::resolver resolver(io);
    auto addresses = co_await resolver.resolve("example.com.");
    auto bindings = co_await resolver.query("example.com.", pace::dns::record_type::https);
}

resolve

Use dns::resolve(hostname, family, options) for a single lookup on the running context. An overload takes an explicit context as its first argument. The task owns its inputs. The default family is family::any, which queries IPv4 and IPv6 concurrently for the same search candidate. Once one family succeeds, the resolver waits up to 50 ms for the other, shortened to half the remaining lookup budget. If the grace period expires, a cacheable sibling query continues in the background. A successful dns::result has a canonical_name and at least one deduplicated numeric address. To connect, use tcp::connect(hostname, port, client_options). It starts both DNS queries, gives IPv6 up to 50 ms to answer when IPv4 arrives first, then alternates available families and staggers pending TCP attempts by 250 ms. The first successful socket is returned after the losing attempts unwind.

resolver

An explicit resolver accepts concurrent resolve and query calls on its owning context. Call cancel() to cancel all active calls, or cancel an individual task through its inherited token. Destruction also cancels active calls. A detached cache refresh can finish after its resolver is destroyed. The context must outlive the tasks. Use context() to get the owner.

query

resolver.query(name, record_type) returns an answer with its canonical name and a vector of matching IN records. Each record includes its owner, type, TTL in seconds and typed data. On a cache hit, the TTL is bounded by the remaining lifetime of the chain and the reader's cache cap.

Record type Accessor Value in record::data
A, AAAA as_address() Numeric address string
CNAME, PTR as_name() Target name string
TXT as_txt() Vector of binary strings, preserving the segment boundaries
MX as_mx() mail_exchange with preference and exchange
SRV as_srv() service_location with priority, weight, port and target
HTTPS, SVCB as_service_binding() service_binding with priority, target and ordered key/value parameters in wire format

The accessors borrow the value from the record and return nullptr for another record type. Decoded names use decimal escapes such as \046 for dots inside a label. Input also accepts a backslash followed by a non-digit, so www\.test.example has two labels. With case randomization enabled, the resolver verifies the wire spelling and restores the original question case in the answer. On service_binding, alpn() returns the advertised protocol IDs and ipv4hint() and ipv6hint() return numeric address strings. These lists are empty when the parameter is absent. port() returns an optional port, and ech() returns an optional view of the binary ECHConfigList including its length prefix. The view borrows from the record. In ServiceMode, unknown keys remain available in parameters. A malformed parameter in a requested ServiceMode answer causes a malformed-response error. AliasMode ignores the parameter list. The decoder accepts compressed SRV targets and requires uncompressed SVCB and HTTPS targets. RFC 9460, RFC 9848

The resolver follows CNAME chains for address and typed queries. Asking for CNAME itself returns the alias record. Names ending in the label localhost resolve locally to 127.0.0.1 or ::1 for address queries. Names ending in the label onion return NXDOMAIN locally. These rules also apply to CNAME targets. A trailing dot makes a name absolute. Use an address's reverse DNS owner name for PTR queries.

options

Member Behavior
servers Empty uses system configuration. A comma-separated list of numeric endpoints, e.g. 127.0.0.1:5353,[::1]:5353, overrides it and selects exact-name lookups
timeout Total lookup budget including retries, 5 s by default, in (0, 24 h]
tries Unsigned attempts per server, 1–10. Defaults to 2
use_system_attempts With system servers and tries == 2, inherit system attempts when true (default). Set false to explicitly use two attempts
randomize_case Randomizes ASCII letter case in questions and requires a case-exact echo. Default false
max_ttl Positive and negative cache lifetime cap, default 1 h. Zero bypasses the cache
tcp_idle_timeout Idle lifetime cap for TCP and DoT connections, default 10 s, in (0, 24 h]
tcp_only Use TCP directly for plaintext DNS. The default is UDP with TCP fallback
shared_cache Optional explicit dns::cache constructed with an io_context or runtime
upstream Optional encrypted transport, with explicit numeric bootstrap servers

On Unix the resolver reads nameserver, search/domain and the ndots, timeout, attempts, rotate and no-rotate options from /etc/resolv.conf. Other options are ignored. macOS overlays global server and search settings from SystemConfiguration when available. Windows deduplicates active adapters' DNS servers by address and interface scope and skips the three legacy site-local placeholders. It checks the global search list, primary DNS suffix and connection suffixes in that order. Address lookups check the supplied name in the platform hosts file before expanding search domains. A root suffix (.) places the bare name at that position in the search list. TCP and HTTP/3 race addresses from the first candidate that resolves.

The default transport sends EDNS0 queries with a random ID and source port. It verifies the responding endpoint and echoed question. If a plaintext server returns FORMERR without an OPT record, the resolver retries once without EDNS within the same attempt deadline. A truncated UDP reply is retried over TCP. Concurrent TCP fallbacks to the same server share a connection and can receive replies out of order. The resolver closes an idle connection after tcp_idle_timeout. It also replaces a pipeline after two consecutive sent queries time out or 64 sent queries have been abandoned with their replies still outstanding. Both one-shot and persistent resolvers use the runtime cache (context-local for a standalone reactor). Entries are scoped to the upstream configuration. Positive entries expire at the shortest TTL in the answer chain. Negative entries use the smaller of the enclosing SOA's TTL and MINIMUM. NXDOMAIN covers all record types for the missing name. NODATA covers only the requested type. Concurrent misses for the same question, upstream and retry settings share a request across workers, including with a zero TTL cap. Each subscriber keeps its own deadline. When the last subscriber cancels, the upstream query is canceled unless a dual-stack grace period has already left the fetch running to refresh the cache.

DNS over TLS

Enable dns = true and native_tls = true; the package then includes the encrypted transports. Set options.servers to the upstream's numeric address or comma-separated addresses. Specify the TLS authentication name without a trailing dot, for example resolver.example. The default DoT port is 853. Custom DoT ports must be distinct from the plaintext port and port 53. See RFC 7858.

  • Strict (default). Set options.upstream = dns::dns_over_tls("resolver.example", tls_config). Every connection must authenticate the configured TLS name. The native engine uses system trust by default. Use tls::config::trust for private CA roots or the native TLS pin or verification callback for a custom trust policy. TLS authentication or connection failure can exhaust the lookup's retries and fails the lookup.
  • Opportunistic (explicit opt-in). Pass dns::dot_profile::opportunistic as the third argument. With a peer name and verification enabled, the resolver attempts authenticated TLS and retries without verification if certificate authentication fails. Pass an empty name for TLS without authentication or SNI. If TLS cannot be established, the resolver can send plaintext DNS to the same numeric address on port 53, or on the separate port passed as the fourth argument. Plaintext uses the usual UDP/TCP policy. TLS connection setup gets half the upstream attempt budget so plaintext has time to complete. A DNS error or malformed response on an established TLS connection is handled as a DNS failure. Opportunistic lookups can expose queries and accept forged responses. Choose the strict profile when the network must authenticate and encrypt DNS. See RFC 8310.

Each persistent dns::resolver keeps up to one idle DoT connection per upstream endpoint. Concurrent exchanges can open separate connections. DoT queries carry a zero-length EDNS0 Keepalive request and are padded to a multiple of 128 bytes before adding the two-byte TCP length prefix. A server's advertised timeout can shorten the local idle cap, and a zero timeout closes the connection after the reply. An absent Keepalive response uses tcp_idle_timeout. The resolver reconnects if the peer closed an idle connection. See RFC 7828 and RFC 8467.

error_category

DNS failures throw std::system_error in dns::error_category() (named pace.dns). Common numeric values are 1 for no data, 3 for SERVFAIL, 4 for NXDOMAIN, 6 for REFUSED and 10 for a malformed response. Cancellation and deadline expiry use std::errc::operation_canceled and std::errc::timed_out. Invalid options and names throw std::invalid_argument. Running on the wrong context throws std::logic_error.

See the DNS and TLS tutorial and TCP reference.