iroh/address_lookup/
dns.rs

1//! DNS endpoint discovery for iroh
2
3use iroh_base::EndpointId;
4use iroh_dns::dns::DnsResolver;
5pub use iroh_dns::dns::{N0_DNS_ENDPOINT_ORIGIN_PROD, N0_DNS_ENDPOINT_ORIGIN_STAGING};
6use n0_future::boxed::BoxStream;
7use tracing::{Instrument, debug, debug_span, trace};
8
9use crate::{
10    Endpoint,
11    address_lookup::{
12        AddressLookup, AddressLookupBuilder, AddressLookupBuilderError,
13        Error as AddressLookupError, Item as AddressLookupItem,
14    },
15    endpoint::force_staging_infra,
16};
17
18/// Delays after which additional DNS lookup calls are issued.
19///
20/// Each query has its own timeout of 3s. This means that a lookup will finally
21/// abort after 6 seconds.
22pub(crate) const DNS_STAGGERING_MS: &[u64] = &[200, 300, 600, 1000, 2000, 3000];
23
24/// DNS endpoint discovery
25///
26/// When asked to resolve a [`EndpointId`], this service performs a lookup in the Domain Name System (DNS).
27///
28/// It uses the [`Endpoint`]'s DNS resolver to query for `TXT` records under the domain
29/// `_iroh.<z32-endpoint-id>.<origin-domain>`:
30///
31/// * `_iroh`: is the record name
32/// * `<z32-endpoint-id>` is the [`EndpointId`] encoded in [`z-base-32`] format
33/// * `<origin-domain>` is the endpoint origin domain as set in [`DnsAddressLookup::builder`].
34///
35/// Each TXT record returned from the query is expected to contain a string in the format `<name>=<value>`.
36/// If a TXT record contains multiple character strings, they are concatenated first.
37/// The supported attributes are:
38/// * `relay=<url>`: The URL of the home relay server of the endpoint
39///
40/// The DNS resolver defaults to using the nameservers configured on the host system, but can be changed
41/// with [`crate::endpoint::Builder::dns_resolver`].
42///
43/// [`z-base-32`]: https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
44/// [`Endpoint`]: crate::Endpoint
45#[derive(Debug)]
46pub struct DnsAddressLookup {
47    origin_domain: String,
48    dns_resolver: DnsResolver,
49}
50
51/// Builder for [`DnsAddressLookup`].
52///
53/// See [`DnsAddressLookup::builder`].
54#[derive(Debug)]
55pub struct DnsAddressLookupBuilder {
56    origin_domain: String,
57    dns_resolver: Option<DnsResolver>,
58}
59
60impl DnsAddressLookupBuilder {
61    /// Sets the DNS resolver to use.
62    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
63        self.dns_resolver = Some(dns_resolver);
64        self
65    }
66
67    /// Builds a [`DnsAddressLookup`] with the passed [`DnsResolver`].
68    pub fn build(self) -> DnsAddressLookup {
69        DnsAddressLookup {
70            dns_resolver: self.dns_resolver.unwrap_or_default(),
71            origin_domain: self.origin_domain,
72        }
73    }
74}
75
76impl DnsAddressLookup {
77    /// Creates a [`DnsAddressLookupBuilder`] that implements [`AddressLookupBuilder`].
78    pub fn builder(origin_domain: String) -> DnsAddressLookupBuilder {
79        DnsAddressLookupBuilder {
80            origin_domain,
81            dns_resolver: None,
82        }
83    }
84
85    /// Creates a new DNS address lookup using the `iroh.link` domain.
86    ///
87    /// This uses the [`N0_DNS_ENDPOINT_ORIGIN_PROD`] domain.
88    ///
89    /// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
90    /// set to any non empty value the [`N0_DNS_ENDPOINT_ORIGIN_STAGING`] domain
91    /// is used instead.
92    pub fn n0_dns() -> DnsAddressLookupBuilder {
93        if force_staging_infra() {
94            Self::builder(N0_DNS_ENDPOINT_ORIGIN_STAGING.to_string())
95        } else {
96            Self::builder(N0_DNS_ENDPOINT_ORIGIN_PROD.to_string())
97        }
98    }
99}
100
101impl AddressLookupBuilder for DnsAddressLookupBuilder {
102    fn into_address_lookup(
103        mut self,
104        endpoint: &Endpoint,
105    ) -> Result<impl AddressLookup, AddressLookupBuilderError> {
106        if self.dns_resolver.is_none() {
107            self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
108        }
109        Ok(self.build())
110    }
111}
112
113impl AddressLookup for DnsAddressLookup {
114    fn resolve(
115        &self,
116        endpoint_id: EndpointId,
117    ) -> Option<BoxStream<Result<AddressLookupItem, AddressLookupError>>> {
118        let resolver = self.dns_resolver.clone();
119        let origin_domain = self.origin_domain.clone();
120        let span =
121            debug_span!("DnsAddressLookup", lookup_id=%endpoint_id.fmt_short(), %origin_domain);
122        let fut = async move {
123            trace!("starting DNS lookup");
124            let endpoint_info = resolver
125                .lookup_endpoint_by_id_staggered(&endpoint_id, &origin_domain, DNS_STAGGERING_MS)
126                .await
127                .inspect_err(|err| debug!("DNS lookup failed: {err:#}"))
128                .map_err(|e| AddressLookupError::from_err_any("dns", e))?;
129            debug!(info=?endpoint_info, "DNS lookup success");
130            Ok(AddressLookupItem::new(endpoint_info, "dns", None))
131        }
132        .instrument(span);
133        let stream = n0_future::stream::once_future(fut);
134        Some(Box::pin(stream))
135    }
136}