Skip to main content

rings_dns_relay/
relay.rs

1//! The relay: its DNS authority and its ingress, opened from one configuration and run together.
2//!
3//! ```text
4//!   open : Config → (Directory, Forward) → Result DnsRelay      validates, reads the state
5//!   run  : DnsRelay → stop → Result ()                           binds, serves until stop
6//! ```
7//!
8//! `open` changes nothing outside the state directory, and `run` binds every socket before it
9//! serves any, so a misconfigured relay fails before it answers anything.
10
11use std::collections::BTreeSet;
12use std::future::Future;
13use std::net::SocketAddr;
14use std::num::NonZeroU16;
15use std::sync::Arc;
16use std::time::Duration;
17
18use hickory_proto::rr::Name;
19use hickory_proto::ProtoError;
20use hickory_server::net::NetError;
21use hickory_server::Server;
22use thiserror::Error;
23use tokio::net::TcpListener;
24use tokio::net::UdpSocket;
25
26use crate::authority::AnswerTtl;
27use crate::capability::Directory;
28use crate::capability::Forward;
29use crate::config::DnsRelayConfig;
30use crate::config::ZoneConfig;
31use crate::ingress::AdmissionLimits;
32use crate::ingress::Ingress;
33use crate::ingress::IngressError;
34use crate::memory::MemoryWindows;
35use crate::recall::Recall;
36use crate::registry::duration_ms;
37use crate::registry::AddressRegistry;
38use crate::server::DnsAuthority;
39use crate::socket::bind_udp;
40use crate::socket::listen_tcp;
41use crate::state::StateError;
42use crate::zone::Zone;
43use crate::zone::ZoneError;
44use crate::zone::Zones;
45
46/// How long a TCP DNS client may stay silent before the relay closes its connection.
47const DNS_TCP_TIMEOUT: Duration = Duration::from_secs(5);
48/// How many responses may queue on one TCP DNS connection.
49const DNS_TCP_RESPONSE_BUFFER: usize = 32;
50
51/// Why a relay cannot open or run.
52#[derive(Debug, Error)]
53pub enum DnsRelayError {
54    /// A domain name in the configuration does not parse.
55    #[error("invalid domain name {name:?}: {source}")]
56    Name {
57        /// The name as written.
58        name: String,
59        /// Why it does not parse.
60        source: ProtoError,
61    },
62    /// A zone names no nameserver.
63    #[error("zone {0} names no nameserver")]
64    NoNameserver(String),
65    /// The zones cannot be served together.
66    #[error(transparent)]
67    Zone(#[from] ZoneError),
68    /// No ingress port is configured, or port 0 is.
69    #[error("the ingress needs at least one port, and port 0 cannot be served")]
70    Ports,
71    /// No DNS listener is configured.
72    #[error("DNS needs at least one listening address")]
73    DnsListen,
74    /// A bound that must admit something is 0.
75    #[error("{0} must be at least 1")]
76    ZeroBound(&'static str),
77    /// The state directory cannot be read or written.
78    #[error(transparent)]
79    State(#[from] StateError),
80    /// A DNS socket cannot be bound.
81    #[error("DNS cannot listen on {address}: {source}")]
82    DnsBind {
83        /// The address.
84        address: SocketAddr,
85        /// The failure.
86        source: std::io::Error,
87    },
88    /// The ingress cannot be bound.
89    #[error(transparent)]
90    Ingress(#[from] IngressError),
91    /// The DNS server failed while shutting down.
92    #[error("DNS server: {0}")]
93    Dns(#[from] NetError),
94}
95
96/// A relay opened from its configuration, ready to run.
97pub struct DnsRelay<D, F>
98where
99    D: Directory,
100    F: Forward<Owner = D::Owner>,
101{
102    authority: DnsAuthority<Recall<D>>,
103    dns_listen: Vec<SocketAddr>,
104    ingress: Ingress<Recall<D>, F>,
105}
106
107impl<D, F> DnsRelay<D, F>
108where
109    D: Directory,
110    F: Forward<Owner = D::Owner>,
111{
112    /// Validate `config` and open the relay's state, to read owners from `directory`, through
113    /// the relay's memory of them, and carry connections with `forward`.
114    pub async fn open(
115        config: &DnsRelayConfig,
116        directory: Arc<D>,
117        forward: Arc<F>,
118    ) -> Result<Self, DnsRelayError> {
119        let zones = Arc::new(Zones::new(
120            config
121                .zones
122                .iter()
123                .map(zone_of)
124                .collect::<Result<Vec<_>, _>>()?,
125        )?);
126        let ports = ingress_ports(&config.ports)?;
127        if config.dns_listen.is_empty() {
128            return Err(DnsRelayError::DnsListen);
129        }
130        let max_owners = at_least_one(config.max_owners, "max_owners")?;
131        let max_lookups = at_least_one(config.max_lookups, "max_lookups")?;
132        let registry = Arc::new(
133            AddressRegistry::open(
134                config.prefix,
135                &config.state_dir,
136                Duration::from_secs(config.book_retention_secs),
137                max_owners,
138            )
139            .await?,
140        );
141        let windows = MemoryWindows {
142            fresh_ms: duration_ms(Duration::from_secs(config.fresh_secs)),
143            grace_ms: duration_ms(Duration::from_secs(config.grace_secs)),
144        };
145        let recall = Arc::new(
146            Recall::open(
147                directory,
148                &config.state_dir,
149                windows,
150                max_owners,
151                max_lookups,
152            )
153            .await?,
154        );
155        let ttl = AnswerTtl {
156            positive: config.ttl_secs,
157            negative: config.negative_ttl_secs,
158        };
159        let limits = AdmissionLimits {
160            total: config.max_connections,
161            per_owner: config.max_connections_per_owner,
162        };
163        Ok(Self {
164            authority: DnsAuthority::new(zones, ttl, Arc::clone(&registry), Arc::clone(&recall)),
165            dns_listen: config.dns_listen.clone(),
166            ingress: Ingress::new(
167                config.ingress_listen,
168                ports,
169                registry,
170                recall,
171                forward,
172                limits,
173            ),
174        })
175    }
176
177    /// Bind every socket, then serve DNS and the ingress until `stop` completes.
178    ///
179    /// Every socket is bound before any is served, and served before `stop` is first polled: a
180    /// relay that cannot bind one returns its error having answered nothing.
181    pub async fn run(self, stop: impl Future<Output = ()>) -> Result<(), DnsRelayError> {
182        let dns = self
183            .dns_listen
184            .iter()
185            .map(|address| bind_dns(*address))
186            .collect::<Result<Vec<_>, _>>()?;
187        let listeners = self.ingress.bind()?;
188        let mut server = Server::new(self.authority);
189        for (udp, tcp) in dns {
190            server.register_socket(udp);
191            server.register_listener(tcp, DNS_TCP_TIMEOUT, DNS_TCP_RESPONSE_BUFFER);
192        }
193        let mut ingress = self.ingress.serve(listeners);
194        stop.await;
195        ingress.abort_all();
196        server.shutdown_gracefully().await?;
197        Ok(())
198    }
199}
200
201/// DNS's UDP socket and TCP listener on `address`; on an IPv6 address both are IPv6 only, so
202/// the default `[::]:53` and `0.0.0.0:53` bind together.
203fn bind_dns(address: SocketAddr) -> Result<(UdpSocket, TcpListener), DnsRelayError> {
204    let bind_error = |source| DnsRelayError::DnsBind { address, source };
205    Ok((
206        bind_udp(address).map_err(bind_error)?,
207        listen_tcp(address).map_err(bind_error)?,
208    ))
209}
210
211/// The ingress ports `ports` names: at least one, none of them 0.
212fn ingress_ports(ports: &[u16]) -> Result<BTreeSet<NonZeroU16>, DnsRelayError> {
213    let ports = ports
214        .iter()
215        .map(|port| NonZeroU16::new(*port).ok_or(DnsRelayError::Ports))
216        .collect::<Result<BTreeSet<_>, _>>()?;
217    if ports.is_empty() {
218        return Err(DnsRelayError::Ports);
219    }
220    Ok(ports)
221}
222
223/// `value`, the bound named `name`, when it admits something.
224fn at_least_one(value: usize, name: &'static str) -> Result<usize, DnsRelayError> {
225    if value == 0 {
226        return Err(DnsRelayError::ZeroBound(name));
227    }
228    Ok(value)
229}
230
231/// The zone `config` describes: its first nameserver is the primary.
232fn zone_of(config: &ZoneConfig) -> Result<Zone, DnsRelayError> {
233    let mut nameservers = config
234        .nameservers
235        .iter()
236        .map(|nameserver| fqdn(nameserver))
237        .collect::<Result<Vec<_>, _>>()?
238        .into_iter();
239    let primary = nameservers
240        .next()
241        .ok_or_else(|| DnsRelayError::NoNameserver(config.origin.clone()))?;
242    Ok(Zone::new(
243        fqdn(&config.origin)?,
244        primary,
245        nameservers.collect(),
246        fqdn(&config.contact)?,
247    ))
248}
249
250/// `name` as a fully qualified domain name: a written name is absolute whether or not it ends
251/// with a dot.
252fn fqdn(name: &str) -> Result<Name, DnsRelayError> {
253    let mut parsed = Name::from_ascii(name).map_err(|source| DnsRelayError::Name {
254        name: name.to_owned(),
255        source,
256    })?;
257    parsed.set_fqdn(true);
258    Ok(parsed)
259}