Skip to main content

rings_node/dns_relay/
config.rs

1//! The node's `services` section: what it serves at `<did>.<zone>` through DNS relays.
2//!
3//! ```yaml
4//! services:
5//!   ports:
6//!     - port: 25
7//!       target: 127.0.0.1:2525
8//!       proxy_protocol: v2
9//!     - port: 22
10//!       target: 127.0.0.1:22
11//!   txt:
12//!     - name: _acme-challenge
13//!       values: ["<token>"]
14//! ```
15//!
16//! Each port maps to the local address the node dials for a connection to that port of its
17//! relayed address. A port with `proxy_protocol: v2` has the relay send a PROXY protocol v2
18//! header naming the client before the client's bytes, so a service that reads one (Postfix,
19//! HAProxy, the mailbox example) sees the client's address instead of its own node's; the
20//! default, `off`, sends nothing. An empty section (no port, no record) publishes a withdrawal.
21
22use std::collections::BTreeMap;
23use std::net::SocketAddr;
24use std::time::Duration;
25
26use rings_dns_relay::ProxyProtocol;
27use serde::Deserialize;
28use serde::Serialize;
29
30use super::descriptor::ServedTxt;
31use super::registration::ServiceOffer;
32use crate::error::Error;
33use crate::error::Result;
34use crate::registration::validate_schedule;
35use crate::registration::TimingKeys;
36
37/// Default heartbeat interval of the service descriptor, in seconds.
38const DEFAULT_SERVICES_HEARTBEAT_INTERVAL_SECS: u64 = 30;
39/// Default time-to-live of each service descriptor, in seconds.
40const DEFAULT_SERVICES_TTL_SECS: u64 = 90;
41
42/// One served port and the local address behind it.
43#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
44#[serde(deny_unknown_fields)]
45pub struct ServedPortConfig {
46    /// The port at the node's relayed address.
47    pub port: u16,
48    /// The local address the node dials for a connection to it.
49    pub target: SocketAddr,
50    /// Whether the service at `target` reads a PROXY protocol header first.
51    #[serde(default)]
52    pub proxy_protocol: ProxyProtocol,
53}
54
55/// TXT records published at one name under the node's.
56#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
57#[serde(deny_unknown_fields)]
58pub struct ServedTxtConfig {
59    /// The name under the node's name; empty for the node's own.
60    #[serde(default)]
61    pub name: String,
62    /// The records' texts.
63    pub values: Vec<String>,
64}
65
66/// The node's `services` section.
67#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
68#[serde(deny_unknown_fields)]
69pub struct ServicesConfig {
70    /// The served ports.
71    #[serde(default)]
72    pub ports: Vec<ServedPortConfig>,
73    /// The published TXT records.
74    #[serde(default)]
75    pub txt: Vec<ServedTxtConfig>,
76    /// Service descriptor heartbeat interval, in seconds.
77    #[serde(default = "default_services_heartbeat_interval_secs")]
78    pub heartbeat_interval_secs: u64,
79    /// Service descriptor time-to-live, in seconds.
80    #[serde(default = "default_services_ttl_secs")]
81    pub ttl_secs: u64,
82}
83
84impl ServicesConfig {
85    /// The validated offer this section publishes.
86    ///
87    /// Post: no port repeats, every bound of an announcement holds, and the heartbeat refreshes
88    /// the descriptor before it expires.
89    pub fn offer(&self) -> Result<ServiceOffer> {
90        let heartbeat_interval = Duration::from_secs(self.heartbeat_interval_secs);
91        let ttl = Duration::from_secs(self.ttl_secs);
92        let keys = TimingKeys {
93            heartbeat_interval: "services.heartbeat_interval_secs",
94            ttl: "services.ttl_secs",
95            enabled_by: None,
96        };
97        validate_schedule(&keys, heartbeat_interval, ttl)?;
98        let mut ports = BTreeMap::new();
99        for served in &self.ports {
100            if ports.insert(served.port, served.proxy_protocol).is_some() {
101                return Err(Error::InvalidConfig(format!(
102                    "services: port {} is served twice",
103                    served.port
104                )));
105            }
106        }
107        let txt = self
108            .txt
109            .iter()
110            .map(|served| ServedTxt {
111                name: served.name.clone(),
112                values: served.values.clone(),
113            })
114            .collect();
115        ServiceOffer::new(ports, txt, heartbeat_interval, ttl)
116            .map_err(|error| Error::InvalidConfig(format!("services: {error}")))
117    }
118
119    /// The local address behind each served port.
120    pub fn targets(&self) -> impl Iterator<Item = (u16, SocketAddr)> + '_ {
121        self.ports.iter().map(|served| (served.port, served.target))
122    }
123}
124
125/// [`DEFAULT_SERVICES_HEARTBEAT_INTERVAL_SECS`].
126const fn default_services_heartbeat_interval_secs() -> u64 {
127    DEFAULT_SERVICES_HEARTBEAT_INTERVAL_SECS
128}
129
130/// [`DEFAULT_SERVICES_TTL_SECS`].
131const fn default_services_ttl_secs() -> u64 {
132    DEFAULT_SERVICES_TTL_SECS
133}