iroh_live_node/
endpoint.rs1use 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#[stack_error(derive, add_meta)]
27pub enum EndpointError {
28 #[error("IROH_SECRET does not hold a secret key")]
30 SecretKey { source: iroh::KeyParsingError },
31 #[error("failed to bind the endpoint")]
33 Bind { source: iroh::endpoint::BindError },
34}
35
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40pub enum Mdns {
41 #[default]
43 Announce,
44 Lookup,
46 Off,
48}
49
50#[derive(Debug, Clone, Default)]
52#[non_exhaustive]
53pub struct EndpointConfig {
54 pub secret_key: Option<SecretKey>,
56 pub mdns: Mdns,
58}
59
60impl EndpointConfig {
61 #[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 #[must_use]
70 pub fn with_mdns(mut self, mdns: Mdns) -> Self {
71 self.mdns = mdns;
72 self
73 }
74
75 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 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 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#[derive(Debug)]
160struct MdnsLookupBuilder {
161 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#[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
210fn 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
235pub 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 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 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 #[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}