iroh_dns_server/
dns.rs

1//! Implementation of a DNS name server for iroh endpoint announces
2
3use std::{
4    collections::BTreeMap,
5    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
6    sync::Arc,
7    time::Duration,
8};
9
10use async_trait::async_trait;
11use bytes::Bytes;
12use hickory_server::{
13    net::{NetError, runtime::TokioTime, xfer::Protocol},
14    proto::{
15        self,
16        op::ResponseCode,
17        rr::{
18            LowerName, Name, RData, Record, RecordSet, RecordType, RrKey,
19            rdata::{self},
20        },
21    },
22    server::{Request, RequestHandler, ResponseHandler, ResponseInfo},
23    store::in_memory::InMemoryZoneHandler,
24    zone_handler::{AxfrPolicy, Catalog, MessageResponse, ZoneType},
25};
26use n0_error::{Result, StdResultExt, anyerr};
27use serde::{Deserialize, Serialize};
28use tokio::{
29    net::{TcpListener, UdpSocket},
30    sync::broadcast,
31};
32use tracing::{debug, info};
33
34use self::node_zone_handler::NodeZoneHandler;
35use crate::{metrics::Metrics, store::ZoneStore};
36
37mod node_zone_handler;
38
39const DEFAULT_NS_TTL: u32 = 60 * 60 * 12; // 12h
40const DEFAULT_SOA_TTL: u32 = 60 * 60 * 24 * 14; // 14d
41const DEFAULT_A_TTL: u32 = 60 * 60; // 1h
42
43/// Configuration for the DNS listener.
44#[derive(Clone, Debug, Serialize, Deserialize)]
45#[non_exhaustive]
46pub struct DnsConfig {
47    /// Port to bind the DNS listener to, for both UDP and TCP.
48    pub port: u16,
49    /// Address to bind the DNS listener to (defaults to `::`, i.e. IPv6 wildcard which also covers IPv4).
50    pub bind_addr: Option<IpAddr>,
51    /// SOA record data served for authoritative zones, in zone-file format.
52    pub default_soa: String,
53    /// Default time-to-live, in seconds, for returned DNS records.
54    pub default_ttl: u32,
55    /// Origins under which the server publishes pkarr-signed zones.
56    ///
57    /// For each origin, the server answers queries for any published
58    /// `<endpointid>.<origin>` name.
59    pub origins: Vec<String>,
60
61    /// Optional `A` record to serve at each origin apex.
62    pub rr_a: Option<Ipv4Addr>,
63    /// Optional `AAAA` record to serve at each origin apex.
64    pub rr_aaaa: Option<Ipv6Addr>,
65    /// Optional `NS` record to serve at each origin apex.
66    pub rr_ns: Option<String>,
67}
68
69impl DnsConfig {
70    /// Creates a new [`DnsConfig`] with the given required fields.
71    ///
72    /// The optional `bind_addr` and apex resource records (`rr_a`, `rr_aaaa`, `rr_ns`)
73    /// default to `None`. Assign them after construction to override.
74    pub fn new(port: u16, default_soa: String, default_ttl: u32, origins: Vec<String>) -> Self {
75        Self {
76            port,
77            bind_addr: None,
78            default_soa,
79            default_ttl,
80            origins,
81            rr_a: None,
82            rr_aaaa: None,
83            rr_ns: None,
84        }
85    }
86}
87
88/// A DNS server that serves pkarr signed packets.
89#[derive(derive_more::Debug)]
90pub(crate) struct DnsServer {
91    local_addr: SocketAddr,
92    #[debug("hickory_server::Server<DnsHandler>")]
93    server: hickory_server::Server<DnsHandler>,
94}
95
96impl DnsServer {
97    /// Spawn the server.
98    pub(crate) async fn spawn(config: DnsConfig, dns_handler: DnsHandler) -> Result<Self> {
99        const TCP_TIMEOUT: Duration = Duration::from_millis(1000);
100        let mut server = hickory_server::Server::new(dns_handler);
101
102        let bind_addr = SocketAddr::new(
103            config.bind_addr.unwrap_or(Ipv6Addr::UNSPECIFIED.into()),
104            config.port,
105        );
106
107        let socket = UdpSocket::bind(bind_addr).await.anyerr()?;
108
109        let socket_addr = socket.local_addr().anyerr()?;
110
111        const TCP_RESPONSE_BUFFER: usize = 64 * 1024;
112        server.register_socket(socket);
113        server.register_listener(
114            TcpListener::bind(bind_addr).await.anyerr()?,
115            TCP_TIMEOUT,
116            TCP_RESPONSE_BUFFER,
117        );
118        info!("DNS server listening on {}", bind_addr);
119
120        Ok(Self {
121            server,
122            local_addr: socket_addr,
123        })
124    }
125
126    /// Get the local address of the UDP/TCP socket.
127    pub(crate) fn local_addr(&self) -> SocketAddr {
128        self.local_addr
129    }
130
131    /// Shutdown the server an wait for all tasks to complete.
132    pub(crate) async fn shutdown(mut self) -> Result<()> {
133        self.server.shutdown_gracefully().await.anyerr()?;
134        Ok(())
135    }
136
137    /// Wait for all tasks to complete.
138    ///
139    /// Runs forever unless tasks fail.
140    pub(crate) async fn run_until_done(mut self) -> Result<()> {
141        self.server.block_until_done().await.anyerr()?;
142        Ok(())
143    }
144}
145
146/// State for serving DNS
147#[derive(Clone, derive_more::Debug)]
148pub(crate) struct DnsHandler {
149    #[debug("Catalog")]
150    catalog: Arc<Catalog>,
151    metrics: Arc<Metrics>,
152}
153
154impl DnsHandler {
155    /// Create a DNS server given some settings, a connection to the DB for DID-by-username lookups
156    /// and the server DID to serve under `_did.<origin>`.
157    pub(crate) fn new(
158        zone_store: ZoneStore,
159        config: &DnsConfig,
160        metrics: Arc<Metrics>,
161    ) -> Result<Self> {
162        let origins = config
163            .origins
164            .iter()
165            .map(Name::from_utf8)
166            .collect::<Result<Vec<_>, _>>()
167            .anyerr()?;
168
169        let (static_authority, serial) = create_static_authority(&origins, config)?;
170        let authority = Arc::new(NodeZoneHandler::new(
171            zone_store,
172            static_authority,
173            origins,
174            serial,
175        )?);
176
177        let mut catalog = Catalog::new();
178        for origin in authority.origins() {
179            catalog.upsert(LowerName::from(origin), vec![authority.clone()]);
180        }
181
182        Ok(Self {
183            catalog: Arc::new(catalog),
184            metrics,
185        })
186    }
187
188    /// Handle a DNS request
189    pub(crate) async fn answer_request(&self, request: Request) -> Result<Bytes> {
190        let (tx, mut rx) = broadcast::channel(1);
191        let response_handle = Handle(tx);
192        self.handle_request::<_, TokioTime>(&request, response_handle)
193            .await;
194        rx.recv().await.anyerr()
195    }
196}
197
198#[async_trait::async_trait]
199impl RequestHandler for DnsHandler {
200    async fn handle_request<R: ResponseHandler, T: hickory_server::net::runtime::Time>(
201        &self,
202        request: &Request,
203        response_handle: R,
204    ) -> ResponseInfo {
205        self.metrics.dns_requests.inc();
206        match request.protocol() {
207            Protocol::Udp => {
208                self.metrics.dns_requests_udp.inc();
209            }
210            Protocol::Https => {
211                self.metrics.dns_requests_https.inc();
212            }
213            _ => {}
214        }
215        debug!(protocol=%request.protocol(), queries=?request.queries, "incoming DNS request");
216
217        let res = self
218            .catalog
219            .handle_request::<_, T>(request, response_handle)
220            .await;
221        match res.response_code {
222            ResponseCode::NoError => match res.counts().answers {
223                0 => self.metrics.dns_lookup_notfound.inc(),
224                _ => self.metrics.dns_lookup_success.inc(),
225            },
226            ResponseCode::NXDomain => self.metrics.dns_lookup_notfound.inc(),
227            _ => self.metrics.dns_lookup_error.inc(),
228        };
229        res
230    }
231}
232
233/// A handle to the channel over which the response to a DNS request will be sent
234#[derive(Debug, Clone)]
235pub(crate) struct Handle(pub broadcast::Sender<Bytes>);
236
237#[async_trait]
238impl ResponseHandler for Handle {
239    async fn send_response<'a>(
240        &mut self,
241        response: MessageResponse<
242            '_,
243            'a,
244            impl Iterator<Item = &'a proto::rr::Record> + Send + 'a,
245            impl Iterator<Item = &'a proto::rr::Record> + Send + 'a,
246            impl Iterator<Item = &'a proto::rr::Record> + Send + 'a,
247            impl Iterator<Item = &'a proto::rr::Record> + Send + 'a,
248        >,
249    ) -> Result<ResponseInfo, NetError> {
250        let mut bytes = Vec::with_capacity(512);
251        let info = {
252            let mut encoder = proto::serialize::binary::BinEncoder::new(&mut bytes);
253            response.destructive_emit(&mut encoder)?
254        };
255        self.0.send(Bytes::from(bytes)).unwrap();
256        Ok(info)
257    }
258}
259
260fn create_static_authority(
261    origins: &[Name],
262    config: &DnsConfig,
263) -> Result<(InMemoryZoneHandler, u32)> {
264    let soa = match RData::try_from_str(RecordType::SOA, &config.default_soa).anyerr()? {
265        RData::SOA(soa) => soa,
266        _ => return Err(anyerr!("Couldn't parse SOA: {}", config.default_soa)),
267    };
268    let serial = soa.serial;
269    let mut records = BTreeMap::new();
270    for name in origins {
271        push_record(
272            &mut records,
273            serial,
274            Record::from_rdata(name.clone(), DEFAULT_SOA_TTL, RData::SOA(soa.clone())),
275        );
276        if let Some(addr) = config.rr_a {
277            push_record(
278                &mut records,
279                serial,
280                Record::from_rdata(name.clone(), DEFAULT_A_TTL, RData::A(addr.into())),
281            );
282        }
283        if let Some(addr) = config.rr_aaaa {
284            push_record(
285                &mut records,
286                serial,
287                Record::from_rdata(name.clone(), DEFAULT_A_TTL, RData::AAAA(addr.into())),
288            );
289        }
290        if let Some(ns) = &config.rr_ns {
291            let ns = Name::parse(ns, Some(&Name::root())).anyerr()?;
292            push_record(
293                &mut records,
294                serial,
295                Record::from_rdata(name.clone(), DEFAULT_NS_TTL, RData::NS(rdata::NS(ns))),
296            );
297        }
298    }
299
300    let static_authority =
301        InMemoryZoneHandler::new(Name::root(), records, ZoneType::Primary, AxfrPolicy::Deny)
302            .map_err(|e| anyerr!("new authority: {e}"))?;
303
304    Ok((static_authority, serial))
305}
306
307fn push_record(records: &mut BTreeMap<RrKey, RecordSet>, serial: u32, record: Record) {
308    let key = RrKey::new(record.name.clone().into(), record.record_type());
309    let mut record_set = RecordSet::new(record.name.clone(), record.record_type(), serial);
310    record_set.insert(record, serial);
311    records.insert(key, record_set);
312}