iroh_dns_server/
dns.rs

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