iroh_dns_server/
config.rs

1//! Configuration for the server
2
3use std::{
4    env,
5    net::{IpAddr, Ipv4Addr, SocketAddr},
6    path::{Path, PathBuf},
7    time::Duration,
8};
9
10use n0_snafu::{Result, ResultExt};
11use serde::{Deserialize, Serialize};
12use tracing::info;
13
14use crate::{
15    dns::DnsConfig,
16    http::{CertMode, HttpConfig, HttpsConfig, RateLimitConfig},
17    store::ZoneStoreOptions,
18};
19
20const DEFAULT_METRICS_ADDR: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 9117);
21
22/// Server configuration
23///
24/// The config is usually loaded from a file with [`Self::load`].
25///
26/// The struct also implements [`Default`] which creates a config suitable for local development
27/// and testing.
28#[derive(Debug, Serialize, Deserialize)]
29pub struct Config {
30    /// Config for the HTTP server
31    ///
32    /// If set to `None` no HTTP server will be started.
33    pub http: Option<HttpConfig>,
34    /// Config for the HTTPS server
35    ///
36    /// If set to `None` no HTTPS server will be started.
37    pub https: Option<HttpsConfig>,
38    /// Config for the DNS server.
39    pub dns: DnsConfig,
40    /// Config for the metrics server.
41    ///
42    /// The metrics server is started by default. To disable the metrics server, set to
43    /// `Some(MetricsConfig::disabled())`.
44    pub metrics: Option<MetricsConfig>,
45
46    /// Config for the mainline lookup.
47    pub mainline: Option<MainlineConfig>,
48
49    /// Config for the zone store.
50    pub zone_store: Option<StoreConfig>,
51
52    /// Config for pkarr rate limit
53    #[serde(default)]
54    pub pkarr_put_rate_limit: RateLimitConfig,
55}
56
57/// The config for the store.
58#[derive(Debug, Serialize, Deserialize, Clone)]
59pub struct StoreConfig {
60    /// Maximum number of packets to process in a single write transaction.
61    max_batch_size: usize,
62
63    /// Maximum time to keep a write transaction open.
64    #[serde(with = "humantime_serde")]
65    max_batch_time: Duration,
66
67    /// Time to keep packets in the store before eviction.
68    #[serde(with = "humantime_serde")]
69    eviction: Duration,
70
71    /// Pause between eviction checks.
72    #[serde(with = "humantime_serde")]
73    eviction_interval: Duration,
74}
75
76impl Default for StoreConfig {
77    fn default() -> Self {
78        ZoneStoreOptions::default().into()
79    }
80}
81
82impl From<ZoneStoreOptions> for StoreConfig {
83    fn from(value: ZoneStoreOptions) -> Self {
84        Self {
85            max_batch_size: value.max_batch_size,
86            max_batch_time: value.max_batch_time,
87            eviction: value.eviction,
88            eviction_interval: value.eviction_interval,
89        }
90    }
91}
92
93impl From<StoreConfig> for ZoneStoreOptions {
94    fn from(value: StoreConfig) -> Self {
95        Self {
96            max_batch_size: value.max_batch_size,
97            max_batch_time: value.max_batch_time,
98            eviction: value.eviction,
99            eviction_interval: value.eviction_interval,
100        }
101    }
102}
103
104/// The config for the metrics server.
105#[derive(Debug, Serialize, Deserialize)]
106pub struct MetricsConfig {
107    /// Set to true to disable the metrics server.
108    pub disabled: bool,
109    /// Optionally set a custom address to bind to.
110    pub bind_addr: Option<SocketAddr>,
111}
112
113impl MetricsConfig {
114    /// Disable the metrics server.
115    pub fn disabled() -> Self {
116        Self {
117            disabled: true,
118            bind_addr: None,
119        }
120    }
121}
122
123/// The config for the metrics server.
124#[derive(Debug, Serialize, Deserialize)]
125pub struct MainlineConfig {
126    /// Set to true to enable the mainline lookup.
127    pub enabled: bool,
128    /// Set custom bootstrap nodes.
129    ///
130    /// Addresses can either be `domain:port` or `ipv4:port`.
131    ///
132    /// If empty this will use the default bittorrent mainline bootstrap nodes as defined by pkarr.
133    pub bootstrap: Option<Vec<String>>,
134}
135
136/// Configure the bootstrap servers for mainline DHT resolution.
137#[derive(Debug, Serialize, Deserialize, Default)]
138pub enum BootstrapOption {
139    /// Use the default bootstrap servers.
140    #[default]
141    Default,
142    /// Use custom bootstrap servers.
143    Custom(Vec<String>),
144}
145
146#[allow(clippy::derivable_impls)]
147impl Default for MainlineConfig {
148    fn default() -> Self {
149        Self {
150            enabled: false,
151            bootstrap: None,
152        }
153    }
154}
155
156impl Config {
157    /// Load the config from a file.
158    pub async fn load(path: impl AsRef<Path>) -> Result<Config> {
159        info!(
160            "loading config file from {}",
161            path.as_ref().to_string_lossy()
162        );
163        let s = tokio::fs::read_to_string(path.as_ref())
164            .await
165            .with_context(|| format!("failed to read {}", path.as_ref().to_string_lossy()))?;
166        let config: Config = toml::from_str(&s).e()?;
167        Ok(config)
168    }
169
170    /// Get the data directory.
171    pub fn data_dir() -> Result<PathBuf> {
172        let dir = if let Some(val) = env::var_os("IROH_DNS_DATA_DIR") {
173            PathBuf::from(val)
174        } else {
175            let path = dirs_next::data_dir()
176                .context("operating environment provides no directory for application data")?;
177
178            path.join("iroh-dns")
179        };
180        Ok(dir)
181    }
182
183    /// Get the path to the store database file.
184    pub fn signed_packet_store_path() -> Result<PathBuf> {
185        Ok(Self::data_dir()?.join("signed-packets-1.db"))
186    }
187
188    /// Get the address where the metrics server should be bound, if set.
189    pub(crate) fn metrics_addr(&self) -> Option<SocketAddr> {
190        match &self.metrics {
191            None => Some(DEFAULT_METRICS_ADDR),
192            Some(conf) => match conf.disabled {
193                true => None,
194                false => Some(conf.bind_addr.unwrap_or(DEFAULT_METRICS_ADDR)),
195            },
196        }
197    }
198
199    pub(crate) fn mainline_enabled(&self) -> Option<BootstrapOption> {
200        match self.mainline.as_ref() {
201            None => None,
202            Some(MainlineConfig { enabled: false, .. }) => None,
203            Some(MainlineConfig {
204                bootstrap: Some(bootstrap),
205                ..
206            }) => Some(BootstrapOption::Custom(bootstrap.clone())),
207            Some(MainlineConfig {
208                bootstrap: None, ..
209            }) => Some(BootstrapOption::Default),
210        }
211    }
212}
213
214impl Default for Config {
215    fn default() -> Self {
216        Self {
217            http: Some(HttpConfig {
218                port: 8080,
219                bind_addr: None,
220            }),
221            https: Some(HttpsConfig {
222                port: 8443,
223                bind_addr: None,
224                domains: vec!["localhost".to_string()],
225                cert_mode: CertMode::SelfSigned,
226                letsencrypt_contact: None,
227                letsencrypt_prod: None,
228            }),
229            dns: DnsConfig {
230                port: 5300,
231                bind_addr: None,
232                origins: vec!["irohdns.example.".to_string(), ".".to_string()],
233
234                default_soa: "irohdns.example hostmaster.irohdns.example 0 10800 3600 604800 3600"
235                    .to_string(),
236                default_ttl: 900,
237
238                rr_a: Some(Ipv4Addr::LOCALHOST),
239                rr_aaaa: None,
240                rr_ns: Some("ns1.irohdns.example.".to_string()),
241            },
242            zone_store: None,
243            metrics: None,
244            mainline: None,
245            pkarr_put_rate_limit: RateLimitConfig::default(),
246        }
247    }
248}