Skip to main content

iroh_live_node/
endpoint.rs

1//! Binding an endpoint: [`MoqPreset`] plus a secret key and mDNS.
2
3use std::{
4    io::Write,
5    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
6    path::Path,
7};
8
9use iroh::{
10    Endpoint, EndpointId, SecretKey,
11    address_lookup::{
12        AddressLookup, AddressLookupBuilder, AddressLookupBuilderError,
13        Error as AddressLookupError, Item,
14    },
15    endpoint::Builder,
16    endpoint_info::EndpointData,
17};
18use iroh_mdns_sd::MdnsAddressLookup;
19use n0_error::{e, stack_error};
20use n0_future::boxed::BoxStream;
21use tracing::{debug, info, warn};
22
23use crate::MoqPreset;
24
25/// An error from [`EndpointConfig::from_env`] or [`EndpointConfig::bind`].
26#[stack_error(derive, add_meta)]
27pub enum EndpointError {
28    /// `IROH_SECRET` does not hold a secret key.
29    #[error("IROH_SECRET does not hold a secret key")]
30    SecretKey { source: iroh::KeyParsingError },
31    /// The endpoint's sockets could not be bound.
32    #[error("failed to bind the endpoint")]
33    Bind { source: iroh::endpoint::BindError },
34}
35
36/// How an endpoint uses mDNS on the local network.
37///
38/// mDNS lets an endpoint id resolve on a network without internet access.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40pub enum Mdns {
41    /// Publishes this endpoint's addresses and resolves others'.
42    #[default]
43    Announce,
44    /// Resolves others without publishing this endpoint.
45    Lookup,
46    /// Uses no mDNS at all.
47    Off,
48}
49
50/// An endpoint with [`MoqPreset`], a key and mDNS.
51#[derive(Debug, Clone, Default)]
52#[non_exhaustive]
53pub struct EndpointConfig {
54    /// The endpoint's identity. `None` generates an ephemeral one.
55    pub secret_key: Option<SecretKey>,
56    /// How the endpoint uses mDNS.
57    pub mdns: Mdns,
58}
59
60impl EndpointConfig {
61    /// Returns this config with `secret_key` as the endpoint's identity.
62    #[must_use]
63    pub fn with_secret_key(mut self, secret_key: SecretKey) -> Self {
64        self.secret_key = Some(secret_key);
65        self
66    }
67
68    /// Returns this config with `mdns` as how the endpoint uses mDNS.
69    #[must_use]
70    pub fn with_mdns(mut self, mdns: Mdns) -> Self {
71        self.mdns = mdns;
72        self
73    }
74
75    /// Returns the default config with the secret key in `IROH_SECRET`, if set.
76    ///
77    /// Set `IROH_SECRET` to keep one endpoint id, and so the same tickets,
78    /// across restarts.
79    ///
80    /// # Errors
81    ///
82    /// Fails with [`EndpointError::SecretKey`] if `IROH_SECRET` is set to
83    /// something that is not a secret key.
84    pub fn from_env() -> Result<Self, EndpointError> {
85        let secret_key = std::env::var_os("IROH_SECRET")
86            .map(|key| key.to_string_lossy().parse())
87            .transpose()
88            .map_err(|source| e!(EndpointError::SecretKey { source }))?;
89        Ok(Self {
90            secret_key,
91            ..Self::default()
92        })
93    }
94
95    /// Applies this config to `builder` and returns it.
96    ///
97    /// This sets [`MoqPreset`], the key and mDNS, for a caller that builds
98    /// its own endpoint. The preset sets the iroh relay mode, the address lookups
99    /// and the QUIC transport config with BBR3, so make your own settings
100    /// after this call, not before. For another congestion controller, set
101    /// `transport_config(Congestion::Cubic.transport_config())` afterwards
102    /// (see [`Congestion`](crate::Congestion)).
103    ///
104    /// The mDNS lookup starts when the endpoint binds. If it cannot start, as
105    /// in a sandbox or on a phone without a multicast lock, the endpoint logs a
106    /// warning and goes without it.
107    ///
108    /// ```no_run
109    /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
110    /// use iroh::{RelayMode, endpoint::Builder};
111    /// use iroh_live_node::EndpointConfig;
112    ///
113    /// let endpoint = EndpointConfig::from_env()?
114    ///     .apply(Builder::empty())
115    ///     .relay_mode(RelayMode::Disabled)
116    ///     .bind()
117    ///     .await?;
118    /// # Ok(())
119    /// # }
120    /// ```
121    pub fn apply(self, builder: Builder) -> Builder {
122        let mut builder = builder.preset(MoqPreset);
123        if let Some(key) = self.secret_key {
124            builder = builder.secret_key(key);
125        }
126        let announce = match self.mdns {
127            Mdns::Announce => true,
128            Mdns::Lookup => false,
129            Mdns::Off => return builder,
130        };
131        builder.address_lookup(MdnsLookupBuilder { announce })
132    }
133
134    /// Binds an endpoint with [`MoqPreset`] and this config.
135    ///
136    /// The endpoint accepts no ALPN until a router mounts handlers on it. The
137    /// caller owns it: close it, or shut down the router built on it, which
138    /// closes it.
139    ///
140    /// # Errors
141    ///
142    /// Fails with [`EndpointError::Bind`] if the endpoint's sockets cannot be
143    /// bound.
144    pub async fn bind(self) -> Result<Endpoint, EndpointError> {
145        let endpoint = self
146            .apply(Builder::empty())
147            .bind()
148            .await
149            .map_err(|source| e!(EndpointError::Bind { source }))?;
150        info!(id = %endpoint.id(), "endpoint bound");
151        Ok(endpoint)
152    }
153}
154
155/// Starts the mDNS address lookup when the endpoint binds.
156///
157/// A failure to start mDNS does not fail the bind: the endpoint gets a
158/// [`MdnsLookup`] without a lookup inside and logs a warning instead.
159#[derive(Debug)]
160struct MdnsLookupBuilder {
161    /// Whether to publish this endpoint's addresses as well.
162    announce: bool,
163}
164
165impl AddressLookupBuilder for MdnsLookupBuilder {
166    fn into_address_lookup(
167        self,
168        endpoint: &Endpoint,
169    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
170        let started = MdnsAddressLookup::builder()
171            .advertise(self.announce)
172            .build(endpoint.id());
173        let lookup = match started {
174            Ok(lookup) => {
175                debug!(announce = self.announce, "mDNS address lookup ready");
176                Some(lookup)
177            }
178            Err(err) => {
179                warn!(
180                    error = %err,
181                    "could not start the mDNS address lookup. Peers on this network are \
182                     found only through pkarr and DNS, which need internet access."
183                );
184                None
185            }
186        };
187        Ok(MdnsLookup(lookup))
188    }
189}
190
191/// The mDNS address lookup, or nothing if mDNS could not start.
192#[derive(Debug)]
193struct MdnsLookup(Option<MdnsAddressLookup>);
194
195impl AddressLookup for MdnsLookup {
196    fn publish(&self, data: &EndpointData) {
197        if let Some(lookup) = &self.0 {
198            lookup.publish(&with_loopback(data));
199        }
200    }
201
202    fn resolve(
203        &self,
204        endpoint_id: EndpointId,
205    ) -> Option<BoxStream<Result<Item, AddressLookupError>>> {
206        self.0.as_ref()?.resolve(endpoint_id)
207    }
208}
209
210/// Returns `data` with a loopback address added for each port it lists.
211///
212/// mdns-sd announces an address only on the interface whose subnet holds it,
213/// and iroh lists no loopback addresses, so without these the loopback
214/// interface carries no records. Endpoints on one host then find each other
215/// only over the LAN interfaces, which macOS Local Network Privacy closes to
216/// processes it has not granted access, such as a launchd agent or a test
217/// binary. Loopback stays open to them, and each loopback address reaches the
218/// socket iroh bound on the unspecified address with that port.
219fn with_loopback(data: &EndpointData) -> EndpointData {
220    let loopback: Vec<SocketAddr> = data
221        .ip_addrs()
222        .map(|addr| {
223            let ip: IpAddr = match addr {
224                SocketAddr::V4(_) => Ipv4Addr::LOCALHOST.into(),
225                SocketAddr::V6(_) => Ipv6Addr::LOCALHOST.into(),
226            };
227            SocketAddr::new(ip, addr.port())
228        })
229        .collect();
230    let mut data = data.clone();
231    data.add_ip_addrs(loopback);
232    data
233}
234
235/// Loads the secret key stored at `path`, or generates one and stores it there.
236///
237/// The file holds the key's 32 bytes and is created readable by this user
238/// only.
239///
240/// # Errors
241///
242/// Fails if the file cannot be read or written, or holds something other than
243/// a key.
244pub fn load_or_create_secret_key(path: &Path) -> std::io::Result<SecretKey> {
245    match std::fs::read(path) {
246        Ok(stored) => {
247            let bytes = <[u8; 32]>::try_from(stored.as_slice()).map_err(|_| {
248                std::io::Error::new(
249                    std::io::ErrorKind::InvalidData,
250                    format!("{} does not hold a secret key", path.display()),
251                )
252            })?;
253            Ok(SecretKey::from_bytes(&bytes))
254        }
255        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
256            let key = SecretKey::generate();
257            let mut options = std::fs::OpenOptions::new();
258            options.write(true).create_new(true);
259            #[cfg(unix)]
260            std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
261            options.open(path)?.write_all(&key.to_bytes())?;
262            info!(path = %path.display(), id = %key.public(), "stored a new secret key");
263            Ok(key)
264        }
265        Err(err) => Err(err),
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    /// Returns a path in the temp dir that nothing else uses.
274    fn scratch() -> std::path::PathBuf {
275        std::env::temp_dir().join(format!("iroh-live-key-{}", SecretKey::generate().public()))
276    }
277
278    #[test]
279    fn a_stored_key_reads_back() {
280        let path = scratch();
281        let created = load_or_create_secret_key(&path).expect("creates the key");
282        let loaded = load_or_create_secret_key(&path).expect("loads the key");
283        std::fs::remove_file(&path).expect("removes the scratch file");
284        assert_eq!(created.to_bytes(), loaded.to_bytes());
285    }
286
287    #[test]
288    fn a_file_that_is_not_a_key_is_refused() {
289        let path = scratch();
290        std::fs::write(&path, b"nowhere near a key").expect("writes the scratch file");
291        let result = load_or_create_secret_key(&path);
292        std::fs::remove_file(&path).expect("removes the scratch file");
293        assert!(result.is_err());
294    }
295
296    /// Binds an endpoint whose only address lookup is mDNS, without an iroh relay.
297    async fn bind_mdns_only(announce: bool, alpn: &[u8]) -> Endpoint {
298        EndpointConfig::default()
299            .with_mdns(Mdns::Off)
300            .apply(Builder::empty())
301            .clear_address_lookup()
302            .address_lookup(MdnsLookupBuilder { announce })
303            .relay_mode(iroh::RelayMode::Disabled)
304            .alpns(vec![alpn.to_vec()])
305            .bind()
306            .await
307            .expect("binds the endpoint")
308    }
309
310    /// A lookup-only endpoint dials an announcing one by its id alone, so the
311    /// addresses can only have come from mDNS.
312    ///
313    /// The two endpoints share a host, so they also find each other over
314    /// loopback where LAN multicast is blocked, as for a test binary under
315    /// macOS Local Network Privacy.
316    #[tokio::test]
317    async fn an_announced_endpoint_resolves_over_mdns() {
318        const ALPN: &[u8] = b"iroh-live/test/mdns";
319        let server = bind_mdns_only(true, ALPN).await;
320        let client = bind_mdns_only(false, ALPN).await;
321
322        let accept = async {
323            let incoming = server.accept().await.expect("the server endpoint closed");
324            incoming.await.expect("accepts the connection").remote_id()
325        };
326        let connect = async {
327            tokio::time::timeout(
328                std::time::Duration::from_secs(20),
329                client.connect(server.id(), ALPN),
330            )
331            .await
332            .expect("resolves the server over mDNS in time")
333            .expect("connects to the server")
334        };
335        let (remote, conn) = tokio::join!(accept, connect);
336        assert_eq!(remote, client.id());
337        assert_eq!(conn.remote_id(), server.id());
338
339        conn.close(0u32.into(), b"done");
340        client.close().await;
341        server.close().await;
342    }
343}