Skip to content

DNS

Ask questions about names, and answer them.

dns is a module — import dns — with two halves. Asking is lookup, addresses, reverse and the Resolver a ResolverSpec builds. Answering is server, and the Listener, Query and Reply under it.

A name that does not exist is an ANSWER

This is the one thing to understand before using the asking half.

lookup succeeds when the nameserver replied — including when it replied “no such name”. The Answer then holds no records, and rcode() says which of the two nothings it is:

What came back Meaning Recovery
rcode() == Some(dns.ResponseCode.NameError) NXDOMAIN: no name of this spelling exists a different name
rcode() == Some(dns.ResponseCode.NoError), count() == 0 NODATA: the name exists, with no record of this kind a different kind, or none
Err(…) nobody answered: the network, the server, or the question try again later

Collapsing NXDOMAIN into the third row would put “use a different name” and “try again later” on one channel, and they are opposite recoveries.

import dns

fn where_is(name string) string {
    a := match dns.addresses(name, 3000) {
        Ok(a) => a
        Err(Timeout { duration_ms }) => return "the resolver did not answer"
        Err(e) => return "lookup failed"
    }
    if a.is_empty() {
        if a.rcode() == Some(dns.ResponseCode.NameError) {
            return "no such name"
        }
        return "the name exists and has no address"
    }
    return match a.first_address() {
        Some(ip) => "${ip}"
        None => ""
    }
}

fn main() void {
    println(where_is("example.com."))
}

Reading an answer

The records are not copied into the guest. Each field crosses when it is asked for, so a program that wants one address out of a twelve-record answer pays for one address — the same bargain json.Reader makes.

count() says how many records came back, and at(i) is the dns.Record at i, or None past the last. A record’s kind() and ttl() are every record’s fields; owner(), address(), target(), mailbox() and tag() are text; a TXT or CAA record’s data is bytes a remote zone filled, so data() answers them as bytes and text() as a string?, None unless they are UTF-8; preference(), weight(), port() and the five SOA numbers are Option[int], and None means this record cannot be asked that rather than that something failed. rcode() is a dns.ResponseCode, None on a closed answer.

Record kinds are IANA’s own numbers — dns.A, dns.AAAA, dns.MX and the rest are named, and a kind this module does not name is still askable, because the number goes straight through.

dns.ADDRESS is a pseudo-kind: every address the name has, v4 and v6 together, through the resolver’s own address lookup — which applies the configured family preference and consults /etc/hosts, neither of which a bare A question does.

Describing a resolver

dns.resolver() is the system’s, built from /etc/resolv.conf. dns.spec() describes another: named servers, DNS-over-TLS or DNS-over-HTTPS, a timeout, a cache size, a search domain, an address-family preference.

import dns

fn private_resolver() Result[dns.Resolver, dns.Error] {
    s := match dns.spec() { Ok(s) => s Err(e) => return Err(e) }
    match s.server("10.0.0.53:53") { Ok(k) => {} Err(e) => return Err(e) }
    match s.timeout(2000) { Ok(k) => {} Err(e) => return Err(e) }
    match s.family(dns.Family.V4) { Ok(k) => {} Err(e) => return Err(e) }
    return s.build()
}

fn main() void {
    match private_resolver() {
        Ok(r) => println("built")
        Err(e) => println("could not build a resolver")
    }
}

Naming a server replaces the system’s rather than adding to it. build() spends the description.

Answering questions

dns.server(addr) describes a server; listen() binds it and starts reading. The unit is the query, not the connection: a datagram has no connection, and a TCP connection carrying five pipelined queries is five independent answers.

import dns
import net

fn serve(l dns.Listener) int {
    for {
        q := match l.receive() { Ok(q) => q Err(e) => return -1 }
        name := q.name()
        r := match q.reply() { Ok(r) => r Err(e) => return -2 }
        match r.authoritative(true) { Ok(k) => {} Err(e) => return -3 }
        match r.a(name, 300, net.IpAddr.v4(10, 1, 2, 3)) { Ok(k) => {} Err(e) => return -4 }
        match r.send() { Ok(k) => {} Err(e) => return -5 }
    }
    return 0
}

fn main() void {
    match dns.server("127.0.0.1:5354") {
        Ok(srv) => {
            match srv.listen() {
                Ok(l) => {
                    stopped := serve(l)
                    println("the server stopped: ${stopped}")
                }
                Err(e) => println("bind failed")
            }
        }
        Err(e) => println("bad address")
    }
}

reply takes the query, so read what you need from it first: the handle is the reply’s from then on, and a read of q after it is refused.

What arrives is already checked. A message with the response bit set is never answered — that is what turns a DNS server into a reflector — a malformed one gets FORMERR, an EDNS version this runtime does not implement gets BADVERS, an opcode it does not implement gets NOTIMP, and anything carrying other than exactly one question is refused. None of those reach a program.

Dropping a query unanswered is silence on UDP

Read that twice before writing a handler. An unanswerable datagram must not be amplified into a reply, so a Query dropped without reply() and send() produces nothing at all — and to anyone debugging with dig that looks exactly like a hang. Over TCP the same drop answers SERVFAIL, because a stream has a reader waiting on it.

The sections, and the bailiwick rule

Every record method takes a trailing section, an Option[dns.Section] whose None means dns.Section.Answers — except soa, whose None means dns.Section.Authority because that is where all but one of its uses are. Answering an explicit SOA question means passing Some(dns.Section.Answers) outright. dns.Section.Authority is where an SOA goes on a negative answer — its minimum is how long a resolver may cache the nothing, and without it every client asks again immediately — and where a delegation’s NS records go. dns.Section.Additional is for glue.

A record whose owner name is not the question’s, under it, or above it is refused, and refused at add rather than at send, so the caller finds out before anything is on the wire. A program that could answer a question about evil.example with an address for bank.example is cache-poisoning bait. The cost, stated: glue for a nameserver in another zone is refused too, and a resolver chases that name itself.

Bounds

Setting Default What happens without it
answer_bytes(n) 1232 a fragmented answer middleboxes drop
max_pending(n) 1024 the backlog moves into the kernel’s socket buffer, where nothing can count it
idle(ms) 10000 a client that connects and says nothing holds a task until the process ends

max_pending is the whole concurrency window: past it a datagram query is dropped, which is correct DNS behaviour — a client retries — and completely invisible. Listener.dropped() exists so it is at least askable about.

An answer too large for a datagram sets TC and the resolver comes back over TCP, which is what over_tcp(true) is for. tls(cert_path, key_path) is DNS-over-TLS (RFC 7858); a server configured for it binds TCP alone, because encrypted DNS has no cleartext datagram form.

Errors

dns.Error names InvalidName, Timeout { duration_ms }, Refused, ServerFailure, NotImplemented, Malformed, Unverified, Unreachable, AddressInUse, PermissionDenied, InvalidHandle, ServerStopped and Other.

There is no NoSuchName, deliberately — see the top of this page.

AddressInUse and PermissionDenied carry tcp’s own numbers, because a port already in use and a port this process may not have mean the same thing everywhere in this runtime. DNS lives at 53, so PermissionDenied is the one a server meets first.

Lifetime

Answer, ResolverSpec, Server, Listener, Query and Reply all implement Drop. Resolver does not: a resolver is startup configuration with the store’s lifetime, and nothing releases one.

Effects

lookup, reverse, build, listen, receive and send carry Suspend. Everything else — every field of an answer or a query, every setter, flush, and every close — is synchronous: the record is already parsed and sitting in a table, so nothing can wait.

Type to search…

↑↓ navigate↵ selectEsc close