Bound iroh path retries to prevent multi-connection OOM
A long-running rc.33 daemon reached OOM with roughly 22 GiB resident and 24 GiB swapped. Live inspection found 40 GiB and 10/20 GiB anonymous container mappings; the active worker stack and tracing metadata identified iroh's scheduled path-open retry loop. In iroh 1.2.0 every failed connection requeues the same path, while each retry visits every connection again. Separate control and data connections multiply the queue geometrically. Vendor the published iroh 1.2.0 source and select it with a workspace Cargo patch. Deduplicate retry admission and cap distinct pending paths at 64, evicting the oldest before inserting a new candidate. Keep the current and next retry batches bounded without combining control/data connections or changing wire protocols, identity derivation, authentication or state. Document source provenance, the live evidence and removal conditions. Upstream PR 4551 merged on October 6, but inspection of the official 1.3.0 crate still shows the unconditional enqueue, so that upgrade alone is not a fix. No version bump, release tag or installed-service change. The default workspace suite includes the exact vendored admission module. Three regressions failed with the original enqueue and pass with the fix: repeated failures across connections, duplicate admission at capacity, and 10,000 distinct candidates with bounded length/capacity and FIFO eviction. Transport integration tests continue using real endpoints and encryption. Checks on Linux in nix develop: - cargo fmt --all -- --check - cargo clippy --locked --workspace --all-targets -- -D warnings - cargo test --locked --workspace --all-targets, with only the inherited TSUNAGI_CONTROL_SOCKET removed from the test environment - git diff --cached --check Initial full-suite runs failed six DNS readiness checks because the inherited system socket path overrode their temporary state directories. Clearing that environment variable resolves those failures without changing application code. Root/network-dependent ignored tests and other operating systems were not run.
This commit is contained in:
1 parent
4e235cbac6
commit
2b0c938487
86 files changed
+35810
-3
No files matched your search
Vendored
+1401
File diff suppressed because it is too large.
Load diff
+136
@@ -0,0 +1,136 @@
|
||||
//! DNS endpoint discovery for iroh
|
||||
|
||||
use iroh_base::EndpointId;
|
||||
use iroh_dns::dns::DnsResolver;
|
||||
pub use iroh_dns::dns::{N0_DNS_ENDPOINT_ORIGIN_PROD, N0_DNS_ENDPOINT_ORIGIN_STAGING};
|
||||
use n0_future::boxed::BoxStream;
|
||||
use tracing::{Instrument, debug, debug_span, trace};
|
||||
|
||||
use crate::{
|
||||
Endpoint,
|
||||
address_lookup::{
|
||||
AddressLookup, AddressLookupBuilder, AddressLookupBuilderError,
|
||||
Error as AddressLookupError, Item as AddressLookupItem,
|
||||
},
|
||||
endpoint::force_staging_infra,
|
||||
};
|
||||
|
||||
/// Delays after which additional DNS lookup calls are issued.
|
||||
///
|
||||
/// Each query has its own timeout of 3s. This means that a lookup will finally
|
||||
/// abort after 6 seconds.
|
||||
pub(crate) const DNS_STAGGERING_MS: &[u64] = &[200, 300, 600, 1000, 2000, 3000];
|
||||
|
||||
/// DNS endpoint discovery
|
||||
///
|
||||
/// When asked to resolve a [`EndpointId`], this service performs a lookup in the Domain Name System (DNS).
|
||||
///
|
||||
/// It uses the [`Endpoint`]'s DNS resolver to query for `TXT` records under the domain
|
||||
/// `_iroh.<z32-endpoint-id>.<origin-domain>`:
|
||||
///
|
||||
/// * `_iroh`: is the record name
|
||||
/// * `<z32-endpoint-id>` is the [`EndpointId`] encoded in [`z-base-32`] format
|
||||
/// * `<origin-domain>` is the endpoint origin domain as set in [`DnsAddressLookup::builder`].
|
||||
///
|
||||
/// Each TXT record returned from the query is expected to contain a string in the format `<name>=<value>`.
|
||||
/// If a TXT record contains multiple character strings, they are concatenated first.
|
||||
/// The supported attributes are:
|
||||
/// * `relay=<url>`: The URL of the home relay server of the endpoint
|
||||
///
|
||||
/// The DNS resolver defaults to using the nameservers configured on the host system, but can be changed
|
||||
/// with [`crate::endpoint::Builder::dns_resolver`].
|
||||
///
|
||||
/// [`z-base-32`]: https://philzimmermann.com/docs/human-oriented-base-32-encoding.txt
|
||||
/// [`Endpoint`]: crate::Endpoint
|
||||
#[derive(Debug)]
|
||||
pub struct DnsAddressLookup {
|
||||
origin_domain: String,
|
||||
dns_resolver: DnsResolver,
|
||||
}
|
||||
|
||||
/// Builder for [`DnsAddressLookup`].
|
||||
///
|
||||
/// See [`DnsAddressLookup::builder`].
|
||||
#[derive(Debug)]
|
||||
pub struct DnsAddressLookupBuilder {
|
||||
origin_domain: String,
|
||||
dns_resolver: Option<DnsResolver>,
|
||||
}
|
||||
|
||||
impl DnsAddressLookupBuilder {
|
||||
/// Sets the DNS resolver to use.
|
||||
pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
|
||||
self.dns_resolver = Some(dns_resolver);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds a [`DnsAddressLookup`] with the passed [`DnsResolver`].
|
||||
pub fn build(self) -> DnsAddressLookup {
|
||||
DnsAddressLookup {
|
||||
dns_resolver: self.dns_resolver.unwrap_or_default(),
|
||||
origin_domain: self.origin_domain,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsAddressLookup {
|
||||
/// Creates a [`DnsAddressLookupBuilder`] that implements [`AddressLookupBuilder`].
|
||||
pub fn builder(origin_domain: String) -> DnsAddressLookupBuilder {
|
||||
DnsAddressLookupBuilder {
|
||||
origin_domain,
|
||||
dns_resolver: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new DNS address lookup using the `iroh.link` domain.
|
||||
///
|
||||
/// This uses the [`N0_DNS_ENDPOINT_ORIGIN_PROD`] domain.
|
||||
///
|
||||
/// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
|
||||
/// set to any non empty value the [`N0_DNS_ENDPOINT_ORIGIN_STAGING`] domain
|
||||
/// is used instead.
|
||||
pub fn n0_dns() -> DnsAddressLookupBuilder {
|
||||
if force_staging_infra() {
|
||||
Self::builder(N0_DNS_ENDPOINT_ORIGIN_STAGING.to_string())
|
||||
} else {
|
||||
Self::builder(N0_DNS_ENDPOINT_ORIGIN_PROD.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookupBuilder for DnsAddressLookupBuilder {
|
||||
fn into_address_lookup(
|
||||
mut self,
|
||||
endpoint: &Endpoint,
|
||||
) -> Result<impl AddressLookup, AddressLookupBuilderError> {
|
||||
if self.dns_resolver.is_none() {
|
||||
self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
|
||||
}
|
||||
Ok(self.build())
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookup for DnsAddressLookup {
|
||||
fn resolve(
|
||||
&self,
|
||||
endpoint_id: EndpointId,
|
||||
) -> Option<BoxStream<Result<AddressLookupItem, AddressLookupError>>> {
|
||||
let resolver = self.dns_resolver.clone();
|
||||
let origin_domain = self.origin_domain.clone();
|
||||
let span =
|
||||
debug_span!("DnsAddressLookup", lookup_id=%endpoint_id.fmt_short(), %origin_domain);
|
||||
let fut = async move {
|
||||
trace!("starting DNS lookup");
|
||||
let endpoint_info = resolver
|
||||
.lookup_endpoint_by_id_staggered(&endpoint_id, &origin_domain, DNS_STAGGERING_MS)
|
||||
.await
|
||||
.inspect_err(|err| debug!("DNS lookup failed: {err:#}"))
|
||||
.map_err(|e| AddressLookupError::from_err_any("dns", e))?;
|
||||
debug!(info=?endpoint_info, "DNS lookup success");
|
||||
Ok(AddressLookupItem::new(endpoint_info, "dns", None))
|
||||
}
|
||||
.instrument(span);
|
||||
let stream = n0_future::stream::once_future(fut);
|
||||
Some(Box::pin(stream))
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
//! An in-memory address lookup system to manually add endpoint addressing information.
|
||||
//!
|
||||
//! Often an application might get endpoint addressing information out-of-band in an
|
||||
//! application-specific way. [`EndpointTicket`]'s are one common way used to achieve this.
|
||||
//! This addressing information is often only usable for a limited time so needs to
|
||||
//! be able to be removed again once you know it is no longer useful.
|
||||
//!
|
||||
//! This is where the [`MemoryLookup`] is useful: it allows applications to add and
|
||||
//! retract endpoint addressing information that is otherwise out-of-band to iroh.
|
||||
//!
|
||||
//! [`EndpointTicket`]: https://docs.rs/iroh-tickets/latest/iroh_tickets/endpoint/struct.EndpointTicket.html
|
||||
|
||||
use std::{
|
||||
collections::{BTreeMap, btree_map::Entry},
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
use iroh_base::EndpointId;
|
||||
use n0_future::{
|
||||
boxed::BoxStream,
|
||||
stream::{self, StreamExt},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
|
||||
|
||||
/// An in-memory address lookup system to manually add endpoint addressing information.
|
||||
///
|
||||
/// Often an application might get endpoint addressing information out-of-band in an
|
||||
/// application-specific way. [`EndpointTicket`]'s are one common way used to achieve this.
|
||||
/// This addressing information is often only usable for a limited time so needs to
|
||||
/// be able to be removed again once you know it is no longer useful.
|
||||
///
|
||||
/// This is where the [`MemoryLookup`] is useful: it allows applications to add and
|
||||
/// retract endpoint addressing information that is otherwise out-of-band to iroh.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
|
||||
/// # {
|
||||
/// use iroh::{
|
||||
/// Endpoint, EndpointAddr, TransportAddr, address_lookup::memory::MemoryLookup,
|
||||
/// endpoint::presets,
|
||||
/// };
|
||||
/// use iroh_base::SecretKey;
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// // Create the Address Lookup and endpoint.
|
||||
/// let address_lookup = MemoryLookup::new();
|
||||
///
|
||||
/// let _ep = Endpoint::builder(presets::N0)
|
||||
/// .address_lookup(address_lookup.clone())
|
||||
/// .bind()
|
||||
/// .await?;
|
||||
///
|
||||
/// // Sometime later add a RelayUrl for our endpoint.
|
||||
/// let id = SecretKey::generate().public();
|
||||
/// // You can pass either `EndpointInfo` or `EndpointAddr` to `add_endpoint_info`.
|
||||
/// address_lookup.add_endpoint_info(EndpointAddr {
|
||||
/// id,
|
||||
/// addrs: [TransportAddr::Relay("https://example.com".parse()?)]
|
||||
/// .into_iter()
|
||||
/// .collect(),
|
||||
/// });
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`EndpointTicket`]: https://docs.rs/iroh-tickets/latest/iroh_tickets/endpoint/struct.EndpointTicket.html
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MemoryLookup {
|
||||
endpoints: Arc<RwLock<BTreeMap<EndpointId, StoredEndpointInfo>>>,
|
||||
provenance: &'static str,
|
||||
}
|
||||
|
||||
impl Default for MemoryLookup {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
endpoints: Default::default(),
|
||||
provenance: Self::PROVENANCE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StoredEndpointInfo {
|
||||
data: EndpointData,
|
||||
last_updated: SystemTime,
|
||||
}
|
||||
|
||||
impl MemoryLookup {
|
||||
/// The provenance string for this Address Lookup implementation.
|
||||
///
|
||||
/// This is mostly used for debugging information and allows understanding the origin of
|
||||
/// addressing information used by an iroh [`Endpoint`].
|
||||
///
|
||||
/// [`Endpoint`]: crate::Endpoint
|
||||
pub const PROVENANCE: &'static str = "memory_lookup";
|
||||
|
||||
/// Creates a new empty Memory Lookup instance.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Creates a new Memory Lookup instance with the provided `provenance`.
|
||||
///
|
||||
/// The provenance is part of [`address_lookup::Item`]s returned from [`Self::resolve`].
|
||||
/// It is mostly used for debugging information and allows understanding the origin of
|
||||
/// addressing information used by an iroh [`Endpoint`].
|
||||
///
|
||||
/// [`Endpoint`]: crate::Endpoint
|
||||
/// [`address_lookup::Item`]: crate::address_lookup::Item
|
||||
pub fn with_provenance(provenance: &'static str) -> Self {
|
||||
Self {
|
||||
endpoints: Default::default(),
|
||||
provenance,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a Memory Lookup instance from endpoint addresses.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
|
||||
/// # {
|
||||
/// use std::{net::SocketAddr, str::FromStr};
|
||||
///
|
||||
/// use iroh::{Endpoint, EndpointAddr, address_lookup::memory::MemoryLookup, endpoint::presets};
|
||||
///
|
||||
/// # fn get_addrs() -> Vec<EndpointAddr> {
|
||||
/// # Vec::new()
|
||||
/// # }
|
||||
/// # #[tokio::main]
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// // get addrs from somewhere
|
||||
/// let addrs = get_addrs();
|
||||
///
|
||||
/// // create a MemoryLookup from the list of addrs.
|
||||
/// let address_lookup = MemoryLookup::from_endpoint_info(addrs);
|
||||
/// // create an endpoint with the memory lookup address_lookup
|
||||
/// let endpoint = Endpoint::builder(presets::N0)
|
||||
/// .address_lookup(address_lookup)
|
||||
/// .bind()
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn from_endpoint_info(infos: impl IntoIterator<Item = impl Into<EndpointInfo>>) -> Self {
|
||||
let res = Self::default();
|
||||
for info in infos {
|
||||
res.add_endpoint_info(info);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
/// Sets endpoint addressing information for the given endpoint ID.
|
||||
///
|
||||
/// This will completely overwrite any existing info for the endpoint.
|
||||
///
|
||||
/// Returns the [`EndpointData`] of the previous entry, or `None` if there was no previous
|
||||
/// entry for this endpoint ID.
|
||||
pub fn set_endpoint_info(
|
||||
&self,
|
||||
endpoint_info: impl Into<EndpointInfo>,
|
||||
) -> Option<EndpointData> {
|
||||
let last_updated = SystemTime::now();
|
||||
let EndpointInfo { endpoint_id, data } = endpoint_info.into();
|
||||
let mut guard = self.endpoints.write().expect("poisoned");
|
||||
let previous = guard.insert(endpoint_id, StoredEndpointInfo { data, last_updated });
|
||||
previous.map(|x| x.data)
|
||||
}
|
||||
|
||||
/// Augments endpoint addressing information for the given endpoint ID.
|
||||
///
|
||||
/// The provided addressing information is combined with the existing info in the memory
|
||||
/// lookup. Any new direct addresses are added to those already present while the
|
||||
/// relay URL is overwritten.
|
||||
pub fn add_endpoint_info(&self, endpoint_info: impl Into<EndpointInfo>) {
|
||||
let last_updated = SystemTime::now();
|
||||
let EndpointInfo { endpoint_id, data } = endpoint_info.into();
|
||||
let mut guard = self.endpoints.write().expect("poisoned");
|
||||
match guard.entry(endpoint_id) {
|
||||
Entry::Occupied(mut entry) => {
|
||||
let existing = entry.get_mut();
|
||||
existing.data.add_addrs(data.addrs().cloned());
|
||||
existing.data.set_user_data(data.user_data().cloned());
|
||||
existing.last_updated = last_updated;
|
||||
}
|
||||
Entry::Vacant(entry) => {
|
||||
entry.insert(StoredEndpointInfo { data, last_updated });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns endpoint addressing information for the given endpoint ID.
|
||||
pub fn get_endpoint_info(&self, endpoint_id: EndpointId) -> Option<EndpointInfo> {
|
||||
let guard = self.endpoints.read().expect("poisoned");
|
||||
let info = guard.get(&endpoint_id)?;
|
||||
Some(EndpointInfo::from_parts(endpoint_id, info.data.clone()))
|
||||
}
|
||||
|
||||
/// Removes all endpoint addressing information for the given endpoint ID.
|
||||
///
|
||||
/// Any removed information is returned.
|
||||
pub fn remove_endpoint_info(&self, endpoint_id: EndpointId) -> Option<EndpointInfo> {
|
||||
let mut guard = self.endpoints.write().expect("poisoned");
|
||||
let info = guard.remove(&endpoint_id)?;
|
||||
Some(EndpointInfo::from_parts(endpoint_id, info.data))
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookup for MemoryLookup {
|
||||
fn publish(&self, _data: &EndpointData) {}
|
||||
|
||||
fn resolve(&self, endpoint_id: EndpointId) -> Option<BoxStream<Result<super::Item, Error>>> {
|
||||
let guard = self.endpoints.read().expect("poisoned");
|
||||
let info = guard.get(&endpoint_id);
|
||||
match info {
|
||||
Some(endpoint_info) => {
|
||||
let last_updated = endpoint_info
|
||||
.last_updated
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.expect("time drift")
|
||||
.as_micros() as u64;
|
||||
let item = Item::new(
|
||||
EndpointInfo::from_parts(endpoint_id, endpoint_info.data.clone()),
|
||||
self.provenance,
|
||||
Some(last_updated),
|
||||
);
|
||||
Some(stream::iter(Some(Ok(item))).boxed())
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use iroh_base::{EndpointAddr, SecretKey, TransportAddr};
|
||||
use n0_error::{Result, StackResultExt};
|
||||
|
||||
use super::*;
|
||||
use crate::{Endpoint, endpoint::presets};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_basic() -> Result {
|
||||
let address_lookup = MemoryLookup::new();
|
||||
|
||||
let _ep = Endpoint::builder(presets::Minimal)
|
||||
.address_lookup(address_lookup.clone())
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
let key = SecretKey::from_bytes(&[0u8; 32]);
|
||||
let addr = EndpointAddr::from_parts(
|
||||
key.public(),
|
||||
[TransportAddr::Relay("https://example.com".parse()?)],
|
||||
);
|
||||
let user_data = Some("foobar".parse().unwrap());
|
||||
let endpoint_info = EndpointInfo::from(addr.clone()).with_user_data(user_data.clone());
|
||||
address_lookup.add_endpoint_info(endpoint_info.clone());
|
||||
|
||||
let back = address_lookup
|
||||
.get_endpoint_info(key.public())
|
||||
.context("no addr")?;
|
||||
|
||||
assert_eq!(back, endpoint_info);
|
||||
assert_eq!(back.user_data(), user_data.as_ref());
|
||||
assert_eq!(back.into_endpoint_addr(), addr);
|
||||
|
||||
let removed = address_lookup
|
||||
.remove_endpoint_info(key.public())
|
||||
.context("nothing removed")?;
|
||||
assert_eq!(removed, endpoint_info);
|
||||
let res = address_lookup.get_endpoint_info(key.public());
|
||||
assert!(res.is_none());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_provenance() -> Result {
|
||||
let address_lookup = MemoryLookup::with_provenance("foo");
|
||||
let key = SecretKey::from_bytes(&[0u8; 32]);
|
||||
let addr = EndpointAddr::from_parts(
|
||||
key.public(),
|
||||
[TransportAddr::Relay("https://example.com".parse()?)],
|
||||
);
|
||||
address_lookup.add_endpoint_info(addr);
|
||||
let mut stream = address_lookup.resolve(key.public()).unwrap();
|
||||
let item = stream.next().await.unwrap()?;
|
||||
assert_eq!(item.provenance(), "foo");
|
||||
assert_eq!(
|
||||
item.relay_urls().next(),
|
||||
Some(&("https://example.com".parse()?))
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+683
@@ -0,0 +1,683 @@
|
||||
//! An address lookup service which publishes and resolves endpoint information using a [pkarr] relay.
|
||||
//!
|
||||
//! Public-Key Addressable Resource Records, [pkarr], is a system which allows publishing
|
||||
//! [DNS Resource Records] owned by a particular [`SecretKey`] under a name derived from its
|
||||
//! corresponding [`PublicKey`], also known as the [`EndpointId`]. Additionally this pkarr
|
||||
//! Resource Record is signed using the same [`SecretKey`], ensuring authenticity of the
|
||||
//! record.
|
||||
//!
|
||||
//! Pkarr normally stores these records on the [Mainline DHT], but also provides two bridges
|
||||
//! that do not require clients to directly interact with the DHT:
|
||||
//!
|
||||
//! - Resolvers are servers which expose the pkarr Resource Record under a domain name,
|
||||
//! e.g. `o3dks..6uyy.dns.iroh.link`. This allows looking up the pkarr Resource Records
|
||||
//! using normal DNS clients. These resolvers would normally perform lookups on the
|
||||
//! Mainline DHT augmented with a local cache to improve performance.
|
||||
//!
|
||||
//! - Relays are servers which allow both publishing and looking up of the pkarr Resource
|
||||
//! Records using HTTP PUT and GET requests. They will usually perform the publishing to
|
||||
//! the Mainline DHT on behalf on the client as well as cache lookups performed on the DHT
|
||||
//! to improve performance.
|
||||
//!
|
||||
//! [`PkarrPublisher`] filters published addresses: only relay addresses are published by default.
|
||||
//! To change this behavior, use [`PkarrPublisherBuilder::addr_filter`] and set it to e.g. [`AddrFilter::unfiltered`].
|
||||
//! This can be useful to enable publishing IP addresses if the iroh endpoint is reachable via public
|
||||
//! IP addresses.
|
||||
//!
|
||||
//! For address lookup in iroh the pkarr Resource Records contain the addressing information,
|
||||
//! providing endpoints which retrieve the pkarr Resource Record with enough detail
|
||||
//! to contact the iroh endpoint.
|
||||
//!
|
||||
//! There are several Address Lookup's built on top of pkarr, which can be composed
|
||||
//! to the application's needs:
|
||||
//!
|
||||
//! - [`PkarrPublisher`], which publishes to a pkarr relay server using HTTP.
|
||||
//!
|
||||
//! - [`PkarrResolver`], which resolves from a pkarr relay server using HTTP.
|
||||
//!
|
||||
//! - [`address_lookup::DnsAddressLookup`], which resolves from a DNS server.
|
||||
//!
|
||||
//! Mainline-DHT-based pkarr publishing/lookup lives in the
|
||||
//! [`iroh-mainline-address-lookup`] crate.
|
||||
//!
|
||||
//! [`iroh-mainline-address-lookup`]: https://docs.rs/iroh-mainline-address-lookup
|
||||
//! [pkarr]: https://pkarr.org
|
||||
//! [DNS Resource Records]: https://en.wikipedia.org/wiki/Domain_Name_System#Resource_records
|
||||
//! [Mainline DHT]: https://en.wikipedia.org/wiki/Mainline_DHT
|
||||
//! [`SecretKey`]: crate::SecretKey
|
||||
//! [`PublicKey`]: crate::PublicKey
|
||||
//! [`EndpointId`]: crate::EndpointId
|
||||
//! [`address_lookup::DnsAddressLookup`]: crate::address_lookup::DnsAddressLookup
|
||||
//! [`N0` preset]: crate::endpoint::presets::N0
|
||||
//! [`AddrFilter`]: crate::address_lookup::AddrFilter
|
||||
//! [`AddrFilter::relay_only`]: crate::address_lookup::AddrFilter::relay_only
|
||||
//! [`AddrFilter::unfiltered`]: crate::address_lookup::AddrFilter::unfiltered
|
||||
//! [`PkarrPublisherBuilder::addr_filter`]: PkarrPublisherBuilder::addr_filter
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use iroh_base::{EndpointId, RelayUrl, SecretKey};
|
||||
use iroh_dns::{
|
||||
EncodingError,
|
||||
endpoint_info::{AddrFilter, EndpointInfo},
|
||||
pkarr::{SignedPacket, SignedPacketVerifyError},
|
||||
};
|
||||
use n0_error::{AnyError, anyerr, e, stack_error};
|
||||
use n0_future::{
|
||||
boxed::BoxStream,
|
||||
task::{self, AbortOnDropHandle},
|
||||
time::{self, Duration, Instant},
|
||||
};
|
||||
use n0_watcher::{Disconnected, Watchable, Watcher as _};
|
||||
use tracing::{Instrument, debug, info_span, trace, warn};
|
||||
use url::Url;
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
use crate::dns::DnsResolver;
|
||||
use crate::{
|
||||
Endpoint,
|
||||
address_lookup::{
|
||||
AddressLookup, AddressLookupBuilder, AddressLookupBuilderError, EndpointData,
|
||||
Error as AddressLookupError, Item as AddressLookupItem,
|
||||
},
|
||||
endpoint::force_staging_infra,
|
||||
util::reqwest_client_builder,
|
||||
};
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub enum PkarrError {
|
||||
#[error("Invalid public key")]
|
||||
PublicKey {
|
||||
#[error(std_err)]
|
||||
source: iroh_base::KeyParsingError,
|
||||
},
|
||||
#[error("Packet failed to verify")]
|
||||
Verify {
|
||||
#[error(std_err)]
|
||||
source: SignedPacketVerifyError,
|
||||
},
|
||||
#[error("Invalid relay URL")]
|
||||
InvalidRelayUrl { url: RelayUrl },
|
||||
#[error("Error sending http request")]
|
||||
HttpSend { source: AnyError },
|
||||
#[error("Error resolving http request")]
|
||||
HttpRequest { status: http::StatusCode },
|
||||
#[error("Http payload error")]
|
||||
HttpPayload { source: AnyError },
|
||||
#[error("EncodingError")]
|
||||
Encoding { source: EncodingError },
|
||||
}
|
||||
|
||||
impl From<PkarrError> for AddressLookupError {
|
||||
fn from(err: PkarrError) -> Self {
|
||||
AddressLookupError::from_err_any("pkarr", err)
|
||||
}
|
||||
}
|
||||
|
||||
/// The production pkarr relay run by [number 0].
|
||||
///
|
||||
/// This server is both a pkarr relay server as well as a DNS resolver, see the [module
|
||||
/// documentation]. However it does not interact with the Mainline DHT, so is a more
|
||||
/// central service. It is a reliable service to use for address lookup.
|
||||
///
|
||||
/// [number 0]: https://n0.computer
|
||||
/// [module documentation]: crate::address_lookup::pkarr
|
||||
pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr";
|
||||
/// The testing pkarr relay run by [number 0].
|
||||
///
|
||||
/// This server operates similarly to [`N0_DNS_PKARR_RELAY_PROD`] but is not as reliable.
|
||||
/// It is meant for more experimental use and testing purposes.
|
||||
///
|
||||
/// [number 0]: https://n0.computer
|
||||
pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr";
|
||||
|
||||
/// Default TTL for the records in the pkarr signed packet.
|
||||
///
|
||||
/// The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the
|
||||
/// `iroh-dns-server`, e.g. as running on [`N0_DNS_PKARR_RELAY_PROD`], as the home server
|
||||
/// keeps the records for the domain. When using the pkarr relay no DNS is involved and the
|
||||
/// setting is ignored.
|
||||
// TODO(flub): huh?
|
||||
pub const DEFAULT_PKARR_TTL: u32 = 30;
|
||||
|
||||
/// Interval in which to republish the endpoint info even if unchanged: 5 minutes.
|
||||
pub const DEFAULT_REPUBLISH_INTERVAL: Duration = Duration::from_secs(60 * 5);
|
||||
|
||||
/// Builder for [`PkarrPublisher`].
|
||||
///
|
||||
/// See [`PkarrPublisher::builder`].
|
||||
#[derive(Debug)]
|
||||
pub struct PkarrPublisherBuilder {
|
||||
pkarr_relay: Url,
|
||||
ttl: u32,
|
||||
republish_interval: Duration,
|
||||
filter: AddrFilter,
|
||||
#[cfg(not(wasm_browser))]
|
||||
dns_resolver: Option<DnsResolver>,
|
||||
}
|
||||
|
||||
impl PkarrPublisherBuilder {
|
||||
/// See [`PkarrPublisher::builder`].
|
||||
fn new(pkarr_relay: Url) -> Self {
|
||||
Self {
|
||||
pkarr_relay,
|
||||
ttl: DEFAULT_PKARR_TTL,
|
||||
republish_interval: DEFAULT_REPUBLISH_INTERVAL,
|
||||
filter: AddrFilter::relay_only(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
dns_resolver: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// See [`PkarrPublisher::n0_dns`].
|
||||
fn n0_dns() -> Self {
|
||||
let pkarr_relay = match force_staging_infra() {
|
||||
true => N0_DNS_PKARR_RELAY_STAGING,
|
||||
false => N0_DNS_PKARR_RELAY_PROD,
|
||||
};
|
||||
|
||||
let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
|
||||
Self::new(pkarr_relay)
|
||||
}
|
||||
|
||||
/// Sets the TTL (time-to-live) for published packets.
|
||||
///
|
||||
/// Default is [`DEFAULT_PKARR_TTL`].
|
||||
pub fn ttl(mut self, ttl: u32) -> Self {
|
||||
self.ttl = ttl;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the interval after which packets are republished even if our endpoint info did not change.
|
||||
///
|
||||
/// Default is [`DEFAULT_REPUBLISH_INTERVAL`].
|
||||
pub fn republish_interval(mut self, republish_interval: Duration) -> Self {
|
||||
self.republish_interval = republish_interval;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the DNS resolver to use for resolving the pkarr relay URL.
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
|
||||
self.dns_resolver = Some(dns_resolver);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the address filter to control which addresses are published to the pkarr server.
|
||||
///
|
||||
/// By default [`AddrFilter::relay_only`] is used. This avoids leaking IP addresses to the
|
||||
/// public pkarr server.
|
||||
///
|
||||
/// However, enabling IP address publishing can be useful, e.g. when iroh runs on a machine
|
||||
/// connected to the internet via public IP addresses without a firewall.
|
||||
/// In such cases, publishing them can make dialing such endpoints via DNS or Pkarr lookup
|
||||
/// faster, potentially skipping a relay connection altogether.
|
||||
pub fn addr_filter(mut self, filter: AddrFilter) -> Self {
|
||||
self.filter = filter;
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the [`PkarrPublisher`] with the passed secret key for signing packets.
|
||||
///
|
||||
/// This publisher will be able to publish [pkarr](https://pkarr.org) records for [`SecretKey`].
|
||||
pub fn build(self, secret_key: SecretKey, tls_config: rustls::ClientConfig) -> PkarrPublisher {
|
||||
PkarrPublisher::new(
|
||||
secret_key,
|
||||
self.pkarr_relay,
|
||||
self.ttl,
|
||||
self.republish_interval,
|
||||
#[cfg(not(wasm_browser))]
|
||||
self.dns_resolver.unwrap_or_default(),
|
||||
tls_config,
|
||||
self.filter,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookupBuilder for PkarrPublisherBuilder {
|
||||
fn into_address_lookup(
|
||||
mut self,
|
||||
endpoint: &Endpoint,
|
||||
) -> Result<impl AddressLookup, AddressLookupBuilderError> {
|
||||
#[cfg(not(wasm_browser))]
|
||||
if self.dns_resolver.is_none() {
|
||||
self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
|
||||
}
|
||||
let tls_config = endpoint.tls_config().clone();
|
||||
Ok(self.build(endpoint.secret_key().clone(), tls_config))
|
||||
}
|
||||
}
|
||||
|
||||
/// Publisher of address lookup information to a [pkarr] relay.
|
||||
///
|
||||
/// This publisher uses HTTP to publish address lookup information to a pkarr relay
|
||||
/// server, see the [module docs] for details.
|
||||
///
|
||||
/// This implements the [`AddressLookup`] trait to be used as an address lookup service. Note
|
||||
/// that it only publishes address lookup information, for the corresponding resolver use
|
||||
/// the [`PkarrResolver`] together with [`AddressLookupServices`].
|
||||
///
|
||||
/// By default this publisher only publishes the [`RelayUrl`], to avoid leaking IP addresses to
|
||||
/// the public pkarr server. Which addresses are published is controlled by the [`AddrFilter`]
|
||||
/// set via [`PkarrPublisherBuilder::addr_filter`].
|
||||
///
|
||||
/// [pkarr]: https://pkarr.org
|
||||
/// [module docs]: crate::address_lookup::pkarr
|
||||
/// [`RelayUrl`]: crate::RelayUrl
|
||||
/// [`AddressLookupServices`]: super::AddressLookupServices
|
||||
#[derive(derive_more::Debug, Clone)]
|
||||
pub struct PkarrPublisher {
|
||||
endpoint_id: EndpointId,
|
||||
watchable: Watchable<Option<EndpointInfo>>,
|
||||
addr_filter: AddrFilter,
|
||||
_drop_guard: Arc<AbortOnDropHandle<()>>,
|
||||
}
|
||||
|
||||
impl PkarrPublisher {
|
||||
/// Returns a [`PkarrPublisherBuilder`] that publishes endpoint info to a [pkarr] relay at `pkarr_relay`.
|
||||
///
|
||||
/// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the
|
||||
/// time-to-live value for the published packets, and it will republish Address Lookup information
|
||||
/// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged.
|
||||
///
|
||||
/// [`PkarrPublisherBuilder`] implements [`AddressLookupBuilder`], so it can be passed to [`address_lookup`].
|
||||
/// It will then use the endpoint's secret key to sign published packets.
|
||||
///
|
||||
/// [`address_lookup`]: crate::endpoint::Builder::address_lookup
|
||||
/// [pkarr]: https://pkarr.org
|
||||
pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder {
|
||||
PkarrPublisherBuilder::new(pkarr_relay)
|
||||
}
|
||||
|
||||
/// Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals.
|
||||
///
|
||||
/// This allows creating the publisher with custom time-to-live values of the
|
||||
/// [`SignedPacket`]s as well as a custom republish interval.
|
||||
fn new(
|
||||
secret_key: SecretKey,
|
||||
pkarr_relay: Url,
|
||||
ttl: u32,
|
||||
republish_interval: Duration,
|
||||
#[cfg(not(wasm_browser))] dns_resolver: DnsResolver,
|
||||
tls_config: rustls::ClientConfig,
|
||||
addr_filter: AddrFilter,
|
||||
) -> Self {
|
||||
debug!("creating pkarr publisher that publishes to {pkarr_relay}");
|
||||
let endpoint_id = secret_key.public();
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
let pkarr_client = PkarrRelayClient::new(pkarr_relay);
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
let pkarr_client = PkarrRelayClient::new(pkarr_relay, tls_config, dns_resolver);
|
||||
|
||||
let watchable = Watchable::default();
|
||||
let service = PublisherService {
|
||||
ttl,
|
||||
watcher: watchable.watch(),
|
||||
secret_key,
|
||||
pkarr_client,
|
||||
republish_interval,
|
||||
};
|
||||
let join_handle = task::spawn(service.run().instrument(info_span!("pkarr_publish")));
|
||||
Self {
|
||||
watchable,
|
||||
endpoint_id,
|
||||
addr_filter,
|
||||
_drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a pkarr publisher which uses the [number 0] pkarr relay server.
|
||||
///
|
||||
/// This uses the pkarr relay server operated by [number 0], at
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`].
|
||||
///
|
||||
/// When running with the environment variable
|
||||
/// `IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
|
||||
/// server is used instead.
|
||||
///
|
||||
/// [number 0]: https://n0.computer
|
||||
pub fn n0_dns() -> PkarrPublisherBuilder {
|
||||
PkarrPublisherBuilder::n0_dns()
|
||||
}
|
||||
|
||||
/// Publishes the addressing information about this endpoint to a pkarr relay.
|
||||
///
|
||||
/// This is a nonblocking function, the actual update is performed in the background.
|
||||
pub fn update_endpoint_data(&self, data: &EndpointData) {
|
||||
let data = data.apply_filter(&self.addr_filter).into_owned();
|
||||
let info = EndpointInfo::from_parts(self.endpoint_id, data);
|
||||
self.watchable.set(Some(info)).ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookup for PkarrPublisher {
|
||||
fn publish(&self, data: &EndpointData) {
|
||||
self.update_endpoint_data(data);
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish endpoint info to a pkarr relay.
|
||||
#[derive(derive_more::Debug, Clone)]
|
||||
struct PublisherService {
|
||||
#[debug("SecretKey")]
|
||||
secret_key: SecretKey,
|
||||
#[debug("PkarrClient")]
|
||||
pkarr_client: PkarrRelayClient,
|
||||
watcher: n0_watcher::Direct<Option<EndpointInfo>>,
|
||||
ttl: u32,
|
||||
republish_interval: Duration,
|
||||
}
|
||||
|
||||
impl PublisherService {
|
||||
async fn run(mut self) {
|
||||
let mut failed_attempts = 0;
|
||||
let republish = time::sleep(Duration::MAX);
|
||||
tokio::pin!(republish);
|
||||
loop {
|
||||
if !self.watcher.is_connected() {
|
||||
break;
|
||||
}
|
||||
if let Some(info) = self.watcher.get() {
|
||||
match self.publish_current(info).await {
|
||||
Err(err) => {
|
||||
failed_attempts += 1;
|
||||
// Retry after increasing timeout
|
||||
let retry_after = Duration::from_secs(failed_attempts);
|
||||
republish.as_mut().reset(Instant::now() + retry_after);
|
||||
warn!(
|
||||
err = %format!("{err:#}"),
|
||||
url = %self.pkarr_client.pkarr_relay_url ,
|
||||
?retry_after,
|
||||
%failed_attempts,
|
||||
"Failed to publish to pkarr",
|
||||
);
|
||||
}
|
||||
Ok(()) => {
|
||||
failed_attempts = 0;
|
||||
// Republish after fixed interval
|
||||
republish
|
||||
.as_mut()
|
||||
.reset(Instant::now() + self.republish_interval);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Wait until either the retry/republish timeout is reached, or the endpoint info changed.
|
||||
tokio::select! {
|
||||
res = self.watcher.updated() => match res {
|
||||
Ok(_) => debug!("Publish endpoint info to pkarr (info changed)"),
|
||||
Err(Disconnected { .. }) => break,
|
||||
},
|
||||
_ = &mut republish => debug!("Publish endpoint info to pkarr (interval elapsed)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_current(&self, info: EndpointInfo) -> Result<(), PkarrError> {
|
||||
debug!(
|
||||
data = ?info.data,
|
||||
pkarr_relay = %self.pkarr_client.pkarr_relay_url,
|
||||
"Publishing endpoint info to pkarr"
|
||||
);
|
||||
let signed_packet = info
|
||||
.to_pkarr_signed_packet(&self.secret_key, self.ttl)
|
||||
.map_err(|err| e!(PkarrError::Encoding, err))?;
|
||||
self.pkarr_client.publish(&signed_packet).await?;
|
||||
trace!(
|
||||
data = ?info.data,
|
||||
pkarr_relay = %self.pkarr_client.pkarr_relay_url,
|
||||
"Published endpoint info to pkarr"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder for [`PkarrResolver`].
|
||||
///
|
||||
/// See [`PkarrResolver::builder`].
|
||||
#[derive(Debug)]
|
||||
pub struct PkarrResolverBuilder {
|
||||
pkarr_relay: Url,
|
||||
#[cfg(not(wasm_browser))]
|
||||
dns_resolver: Option<DnsResolver>,
|
||||
}
|
||||
|
||||
impl PkarrResolverBuilder {
|
||||
/// Sets the DNS resolver to use for resolving the pkarr relay URL.
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
|
||||
self.dns_resolver = Some(dns_resolver);
|
||||
self
|
||||
}
|
||||
|
||||
/// Creates a [`PkarrResolver`] from this builder.
|
||||
pub fn build(self, tls_config: rustls::ClientConfig) -> PkarrResolver {
|
||||
#[cfg(wasm_browser)]
|
||||
let pkarr_client = PkarrRelayClient::new(self.pkarr_relay);
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
let pkarr_client = PkarrRelayClient::new(
|
||||
self.pkarr_relay,
|
||||
tls_config,
|
||||
self.dns_resolver.unwrap_or_default(),
|
||||
);
|
||||
|
||||
PkarrResolver { pkarr_client }
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookupBuilder for PkarrResolverBuilder {
|
||||
fn into_address_lookup(
|
||||
mut self,
|
||||
endpoint: &Endpoint,
|
||||
) -> Result<impl AddressLookup, AddressLookupBuilderError> {
|
||||
#[cfg(not(wasm_browser))]
|
||||
if self.dns_resolver.is_none() {
|
||||
self.dns_resolver = Some(endpoint.dns_resolver()?.clone());
|
||||
}
|
||||
let tls_config = endpoint.tls_config().clone();
|
||||
Ok(self.build(tls_config))
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolver of address lookup information from a [pkarr] relay.
|
||||
///
|
||||
/// The resolver uses HTTP to query address lookup information from a pkarr relay server,
|
||||
/// see the [module docs] for details.
|
||||
///
|
||||
/// This implements the [`AddressLookup`] trait to be used as an address lookup service. Note
|
||||
/// that it only resolves address lookup information, for the corresponding publisher use
|
||||
/// the [`PkarrPublisher`] together with [`AddressLookupServices`].
|
||||
///
|
||||
/// [pkarr]: https://pkarr.org
|
||||
/// [module docs]: crate::address_lookup::pkarr
|
||||
/// [`AddressLookupServices`]: super::AddressLookupServices
|
||||
#[derive(derive_more::Debug, Clone)]
|
||||
pub struct PkarrResolver {
|
||||
pkarr_client: PkarrRelayClient,
|
||||
}
|
||||
|
||||
impl PkarrResolver {
|
||||
/// Creates a new resolver builder using the pkarr relay server at the URL.
|
||||
///
|
||||
/// The builder implements [`AddressLookupBuilder`].
|
||||
pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder {
|
||||
PkarrResolverBuilder {
|
||||
pkarr_relay,
|
||||
#[cfg(not(wasm_browser))]
|
||||
dns_resolver: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a pkarr resolver builder which uses the [number 0] pkarr relay server.
|
||||
///
|
||||
/// This uses the pkarr relay server operated by [number 0] at
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`].
|
||||
///
|
||||
/// When running with the environment variable `IROH_FORCE_STAGING_RELAYS`
|
||||
/// set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`]
|
||||
/// server is used instead.
|
||||
///
|
||||
/// [number 0]: https://n0.computer
|
||||
pub fn n0_dns() -> PkarrResolverBuilder {
|
||||
let pkarr_relay = match force_staging_infra() {
|
||||
true => N0_DNS_PKARR_RELAY_STAGING,
|
||||
false => N0_DNS_PKARR_RELAY_PROD,
|
||||
};
|
||||
|
||||
let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid");
|
||||
Self::builder(pkarr_relay)
|
||||
}
|
||||
}
|
||||
|
||||
impl AddressLookup for PkarrResolver {
|
||||
fn resolve(
|
||||
&self,
|
||||
endpoint_id: EndpointId,
|
||||
) -> Option<BoxStream<Result<AddressLookupItem, AddressLookupError>>> {
|
||||
let pkarr_client = self.pkarr_client.clone();
|
||||
let fut = async move {
|
||||
let signed_packet = pkarr_client.resolve(endpoint_id).await?;
|
||||
let info = EndpointInfo::from_pkarr_signed_packet(&signed_packet)
|
||||
.map_err(|err| AddressLookupError::from_err_any("pkarr", err))?;
|
||||
let item = AddressLookupItem::new(info, "pkarr", None);
|
||||
Ok(item)
|
||||
};
|
||||
let stream = n0_future::stream::once_future(fut);
|
||||
Some(Box::pin(stream))
|
||||
}
|
||||
}
|
||||
|
||||
/// A [pkarr](https://pkarr.org) client to publish [`SignedPacket`]s to a pkarr relay.
|
||||
///
|
||||
/// [pkarr]: https://pkarr.org
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PkarrRelayClient {
|
||||
http_client: reqwest::Client,
|
||||
pkarr_relay_url: Url,
|
||||
}
|
||||
|
||||
/// A builder for the [`PkarrRelayClient`]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PkarrRelayClientBuilder {
|
||||
pkarr_relay_url: Url,
|
||||
#[cfg(not(wasm_browser))]
|
||||
dns_resolver: DnsResolver,
|
||||
#[cfg(not(wasm_browser))]
|
||||
tls_config: rustls::ClientConfig,
|
||||
}
|
||||
|
||||
impl PkarrRelayClientBuilder {
|
||||
/// Build a [`PkarrRelayClient`].
|
||||
pub fn build(self) -> PkarrRelayClient {
|
||||
#[cfg(not(wasm_browser))]
|
||||
let builder = reqwest_client_builder(self.tls_config, self.dns_resolver);
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
let builder = reqwest_client_builder();
|
||||
|
||||
let http_client = builder.build().expect("failed to create reqwest client");
|
||||
PkarrRelayClient {
|
||||
http_client,
|
||||
pkarr_relay_url: self.pkarr_relay_url,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PkarrRelayClient {
|
||||
/// Creates a [`PkarrRelayClient`].
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub fn new(
|
||||
pkarr_relay_url: Url,
|
||||
tls_config: rustls::ClientConfig,
|
||||
dns_resolver: DnsResolver,
|
||||
) -> Self {
|
||||
let http_client = reqwest_client_builder(tls_config, dns_resolver)
|
||||
.build()
|
||||
.expect("failed to create reqwest client");
|
||||
Self {
|
||||
http_client,
|
||||
pkarr_relay_url,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [`PkarrRelayClient`].
|
||||
#[cfg(wasm_browser)]
|
||||
pub fn new(pkarr_relay_url: Url) -> Self {
|
||||
let http_client = reqwest_client_builder()
|
||||
.build()
|
||||
.expect("failed to create reqwest client");
|
||||
Self {
|
||||
http_client,
|
||||
pkarr_relay_url,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a [`SignedPacket`] for the given [`EndpointId`].
|
||||
pub async fn resolve(
|
||||
&self,
|
||||
endpoint_id: EndpointId,
|
||||
) -> Result<SignedPacket, AddressLookupError> {
|
||||
let mut url = self.pkarr_relay_url.clone();
|
||||
url.path_segments_mut()
|
||||
.map_err(|_| {
|
||||
e!(PkarrError::InvalidRelayUrl {
|
||||
url: self.pkarr_relay_url.clone().into()
|
||||
})
|
||||
})?
|
||||
.push(&endpoint_id.to_z32());
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| e!(PkarrError::HttpSend, anyerr!(err)))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(e!(PkarrError::HttpRequest {
|
||||
status: response.status()
|
||||
})
|
||||
.into());
|
||||
}
|
||||
|
||||
let payload = response
|
||||
.bytes()
|
||||
.await
|
||||
.map_err(|err| e!(PkarrError::HttpPayload, anyerr!(err)))?;
|
||||
let packet = SignedPacket::from_relay_payload(&endpoint_id, &payload)
|
||||
.map_err(|err| e!(PkarrError::Verify, err))?;
|
||||
Ok(packet)
|
||||
}
|
||||
|
||||
/// Publishes a [`SignedPacket`].
|
||||
pub async fn publish(&self, signed_packet: &SignedPacket) -> Result<(), PkarrError> {
|
||||
let mut url = self.pkarr_relay_url.clone();
|
||||
url.path_segments_mut()
|
||||
.map_err(|_| {
|
||||
e!(PkarrError::InvalidRelayUrl {
|
||||
url: self.pkarr_relay_url.clone().into()
|
||||
})
|
||||
})?
|
||||
.push(&signed_packet.public_key().to_z32());
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.put(url)
|
||||
.body(signed_packet.to_relay_payload())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| e!(PkarrError::HttpSend, anyerr!(err)))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(e!(PkarrError::HttpRequest {
|
||||
status: response.status()
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+156
@@ -0,0 +1,156 @@
|
||||
//! Default values used in [`iroh`][`crate`]
|
||||
|
||||
/// The default QUIC port used by the Relay server to accept QUIC connections
|
||||
/// for QUIC address discovery
|
||||
///
|
||||
/// The port is "QUIC" typed on a phone keypad.
|
||||
pub use iroh_relay::defaults::DEFAULT_RELAY_QUIC_PORT;
|
||||
use url::Url;
|
||||
|
||||
/// The default HTTP port used by the Relay server.
|
||||
pub const DEFAULT_HTTP_PORT: u16 = 80;
|
||||
|
||||
/// The default HTTPS port used by the Relay server.
|
||||
pub const DEFAULT_HTTPS_PORT: u16 = 443;
|
||||
|
||||
/// The default metrics port used by the Relay server.
|
||||
pub const DEFAULT_METRICS_PORT: u16 = 9090;
|
||||
|
||||
/// Production configuration.
|
||||
pub mod prod {
|
||||
use iroh_relay::{RelayConfig, RelayMap};
|
||||
|
||||
use super::*;
|
||||
use crate::RelayUrl;
|
||||
|
||||
/// Hostname of the default NA east relay.
|
||||
pub const NA_EAST_RELAY_HOSTNAME: &str = "use1-1.relay.n0.iroh.link.";
|
||||
/// Hostname of the default NA west relay.
|
||||
pub const NA_WEST_RELAY_HOSTNAME: &str = "usw1-1.relay.n0.iroh.link.";
|
||||
/// Hostname of the default EU relay.
|
||||
pub const EU_RELAY_HOSTNAME: &str = "euc1-1.relay.n0.iroh.link.";
|
||||
/// Hostname of the default Asia-Pacific relay.
|
||||
pub const AP_RELAY_HOSTNAME: &str = "aps1-1.relay.n0.iroh.link.";
|
||||
|
||||
/// Get the default [`RelayMap`].
|
||||
pub fn default_relay_map() -> RelayMap {
|
||||
RelayMap::from_iter([
|
||||
default_na_east_relay(),
|
||||
default_na_west_relay(),
|
||||
default_eu_relay(),
|
||||
default_ap_relay(),
|
||||
])
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for NA east.
|
||||
pub fn default_na_east_relay() -> RelayConfig {
|
||||
// The default NA east relay server run by number0.
|
||||
let url: Url = format!("https://{NA_EAST_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for NA west.
|
||||
pub fn default_na_west_relay() -> RelayConfig {
|
||||
// The default NA west relay server run by number0.
|
||||
let url: Url = format!("https://{NA_WEST_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for EU.
|
||||
pub fn default_eu_relay() -> RelayConfig {
|
||||
// The default EU relay server run by number0.
|
||||
let url: Url = format!("https://{EU_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default_url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for Asia-Pacific.
|
||||
pub fn default_ap_relay() -> RelayConfig {
|
||||
// The default Asia-Pacific relay server run by number0.
|
||||
let url: Url = format!("https://{AP_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default_url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
}
|
||||
|
||||
/// Staging configuration.
|
||||
///
|
||||
/// Used by tests and might have incompatible changes deployed
|
||||
///
|
||||
/// Note: we have staging servers in EU and NA, but no corresponding staging server for AP at this time.
|
||||
pub mod staging {
|
||||
use iroh_relay::{RelayConfig, RelayMap};
|
||||
|
||||
use super::*;
|
||||
use crate::RelayUrl;
|
||||
|
||||
/// Hostname of the default NA relay.
|
||||
pub const NA_EAST_RELAY_HOSTNAME: &str = "use1-1.staging-relay.n0.iroh.link.";
|
||||
/// Hostname of the default EU relay.
|
||||
pub const EU_RELAY_HOSTNAME: &str = "euc1-1.staging-relay.n0.iroh.link.";
|
||||
|
||||
/// Get the default [`RelayMap`].
|
||||
pub fn default_relay_map() -> RelayMap {
|
||||
RelayMap::from_iter([default_na_east_relay(), default_eu_relay()])
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for NA east.
|
||||
pub fn default_na_east_relay() -> RelayConfig {
|
||||
// The default NA east relay server run by number0.
|
||||
let url: Url = format!("https://{NA_EAST_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
|
||||
/// Get the default [`RelayConfig`] for EU.
|
||||
pub fn default_eu_relay() -> RelayConfig {
|
||||
// The default EU relay server run by number0.
|
||||
let url: Url = format!("https://{EU_RELAY_HOSTNAME}")
|
||||
.parse()
|
||||
.expect("default_url");
|
||||
RelayConfig::from(RelayUrl::from(url))
|
||||
}
|
||||
}
|
||||
|
||||
/// Contains all timeouts that we use in `iroh`.
|
||||
pub(crate) mod timeouts {
|
||||
use n0_future::time::Duration;
|
||||
|
||||
// Timeouts for net_report
|
||||
|
||||
/// Maximum duration to wait for a net_report.
|
||||
pub(crate) const NET_REPORT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use n0_tracing_test::traced_test;
|
||||
|
||||
use super::staging::NA_EAST_RELAY_HOSTNAME;
|
||||
use crate::dns::DnsResolver;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const STAGGERING_DELAYS: &[u64] = &[200, 300];
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_dns_lookup_ipv4_ipv6() {
|
||||
let resolver = DnsResolver::new();
|
||||
let res: Vec<_> = resolver
|
||||
.lookup_ipv4_ipv6_staggered(NA_EAST_RELAY_HOSTNAME, TIMEOUT, STAGGERING_DELAYS)
|
||||
.await
|
||||
.unwrap()
|
||||
.collect();
|
||||
assert!(!res.is_empty());
|
||||
dbg!(res);
|
||||
}
|
||||
}
|
||||
Vendored
+4224
File diff suppressed because it is too large.
Load diff
Vendored
+252
@@ -0,0 +1,252 @@
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
|
||||
};
|
||||
|
||||
use n0_error::stack_error;
|
||||
|
||||
/// Options when configuring binding an IP socket.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BindOpts {
|
||||
/// Sets the network prefix length of the subnet for this interface.
|
||||
///
|
||||
/// The prefix length is used in the routing table that is built to decide where
|
||||
/// datagrams without a specific source address are sent. If these number of leading
|
||||
/// bits in the destination IP address match the same number of leading bits in this
|
||||
/// bound socket address, then it matches the subnet and the datagram will be sent
|
||||
/// here. Otherwise the next bound sockets will be checked for a subnet match. Sockets
|
||||
/// are ordered from longest prefix to shortest prefix.
|
||||
///
|
||||
/// If no bound address has a matching subnet, the bind marked with
|
||||
/// [`Self::is_default_route`] will be used.
|
||||
///
|
||||
/// Note that most datagrams belonging to a traffic flow are in response to an incoming
|
||||
/// datagram. Those are usually sent on the same bound socket as they were received and
|
||||
/// will not consult the routing table derived from these bound sockets to select the
|
||||
/// socket on which they will be sent.
|
||||
prefix_len: u8,
|
||||
/// If set, binding this interface is required and any errors will abort the
|
||||
/// initialization of the endpoint.
|
||||
///
|
||||
/// Defaults to `true`.
|
||||
is_required: bool,
|
||||
/// Whether this socket should be used as default route.
|
||||
///
|
||||
/// The default route is used for outgoing datagrams not belonging to an existing
|
||||
/// traffic flow, which does not fit in any subnet of the bound sockets. It is assumed
|
||||
/// this subnet has a gateway router to route such packets.
|
||||
///
|
||||
/// See [`Self::prefix_len`] for details of how such routing works.
|
||||
is_default_route: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for BindOpts {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
prefix_len: 0,
|
||||
is_required: true,
|
||||
is_default_route: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BindOpts {
|
||||
/// Sets the network prefix length of the subnet this interface is in.
|
||||
///
|
||||
///
|
||||
/// The subnets of bound sockets are used to route outgoing datagrams not belonging to
|
||||
/// an existing traffic flow to the socket they should be sent on. Subnets are ordered
|
||||
/// from longest prefix length to shortest prefix length and the first subnet which
|
||||
/// contains the destination IP address will be chosen. If no subnet matches but there
|
||||
/// is a bound socket marked with [`Self::set_is_default_route`] then this socket will
|
||||
/// be used. In this case it is assumed the attached subnet has a gateway router to
|
||||
/// forward the datagram.
|
||||
///
|
||||
/// Defaults to `0`, which means *all* IP addresses will belong to the subnet of this
|
||||
/// socket's address. If multiple sockets of the same address family (IPv4 or IPv6) are
|
||||
/// bound with such a `/0` prefix the socket which will be chosen is undefined.
|
||||
///
|
||||
/// For IPv4 sockets the maximum prefix is `32`. For IPv6 the maximum prefix is `128`.
|
||||
pub fn set_prefix_len(mut self, prefix_len: u8) -> Self {
|
||||
self.prefix_len = prefix_len;
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the `prefix_len`, see [`Self::set_prefix_len`].
|
||||
pub fn prefix_len(&self) -> u8 {
|
||||
self.prefix_len
|
||||
}
|
||||
|
||||
/// Sets whether bind errors are fatal for this socket.
|
||||
///
|
||||
/// If `false` and this socket fails to bind, the error will be silently ignored and the
|
||||
/// endpoint will still be created.
|
||||
///
|
||||
/// Defaults to `true`.
|
||||
pub fn set_is_required(mut self, is_required: bool) -> Self {
|
||||
self.is_required = is_required;
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the value set by [`Self::set_is_required`].
|
||||
pub fn is_required(&self) -> bool {
|
||||
self.is_required
|
||||
}
|
||||
|
||||
/// Sets whether this is a default route.
|
||||
///
|
||||
/// The default route is used for outgoing datagrams not belonging to an existing
|
||||
/// traffic flow, which does not fit in any subnet of the bound sockets. It is assumed
|
||||
/// this subnet has a gateway router to route such packets.
|
||||
///
|
||||
/// See [`Self::set_prefix_len`] for details on how this routing works.
|
||||
///
|
||||
/// If not set explicitly, then [`Self::is_default_route`] will return `true`
|
||||
/// if the prefix length is set to `0` (the default) and `false` otherwise.
|
||||
pub fn set_is_default_route(mut self, is_default_route: bool) -> Self {
|
||||
self.is_default_route = Some(is_default_route);
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns whether this is a default route.
|
||||
///
|
||||
/// If [`Self::set_is_default_route`] has been called then that value is returned.
|
||||
/// Otherwise, returns `true` if the [`prefix_len`][`Self::prefix_len`] is `0` and
|
||||
/// `false` otherwise.
|
||||
pub fn is_default_route(&self) -> bool {
|
||||
match self.is_default_route {
|
||||
Some(is_default) => is_default,
|
||||
None => self.prefix_len() == 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A simpler version of [`ToSocketAddrs`], that does not do any DNS resolution.
|
||||
///
|
||||
/// [`ToSocketAddrs`]: std::net::ToSocketAddrs
|
||||
pub trait ToSocketAddr {
|
||||
/// Error type on failed conversion.
|
||||
type Err: std::error::Error;
|
||||
|
||||
/// Tries to convert this type to a [`SocketAddr`].
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err>;
|
||||
}
|
||||
|
||||
impl ToSocketAddr for SocketAddr {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
Ok(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for SocketAddrV4 {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
Ok(SocketAddr::V4(*self))
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for SocketAddrV6 {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
Ok(SocketAddr::V6(*self))
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for (IpAddr, u16) {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
let (ip, port) = *self;
|
||||
match ip {
|
||||
IpAddr::V4(ref a) => (*a, port).to_socket_addr(),
|
||||
IpAddr::V6(ref a) => (*a, port).to_socket_addr(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for (Ipv4Addr, u16) {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
let (ip, port) = *self;
|
||||
SocketAddrV4::new(ip, port).to_socket_addr()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for (Ipv6Addr, u16) {
|
||||
type Err = Infallible;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
let (ip, port) = *self;
|
||||
SocketAddrV6::new(ip, port, 0, 0).to_socket_addr()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for (&str, u16) {
|
||||
type Err = std::net::AddrParseError;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
let (host, port) = *self;
|
||||
|
||||
let addr = host.parse::<IpAddr>()?;
|
||||
let addr = SocketAddr::new(addr, port);
|
||||
Ok(addr)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for (String, u16) {
|
||||
type Err = std::net::AddrParseError;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
(&*self.0, self.1).to_socket_addr()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for str {
|
||||
type Err = std::net::AddrParseError;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
let addr = self.parse()?;
|
||||
Ok(addr)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ToSocketAddr + ?Sized> ToSocketAddr for &T {
|
||||
type Err = T::Err;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
(**self).to_socket_addr()
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddr for String {
|
||||
type Err = std::net::AddrParseError;
|
||||
|
||||
fn to_socket_addr(&self) -> Result<SocketAddr, Self::Err> {
|
||||
(**self).to_socket_addr()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[stack_error(derive, add_meta, from_sources)]
|
||||
#[non_exhaustive]
|
||||
pub enum InvalidSocketAddr {
|
||||
#[error(transparent)]
|
||||
AddrParse {
|
||||
#[error(std_err)]
|
||||
source: std::net::AddrParseError,
|
||||
},
|
||||
#[error("Invalid IP prefix length")]
|
||||
InvalidPrefixLength {},
|
||||
#[error(transparent)]
|
||||
Infallible {
|
||||
#[error(std_err)]
|
||||
source: Infallible,
|
||||
},
|
||||
#[error("Only a single default address can be set per IP family")]
|
||||
DuplicateDefaultAddr,
|
||||
}
|
||||
+1652
File diff suppressed because it is too large.
Load diff
Vendored
+171
@@ -0,0 +1,171 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use iroh_base::EndpointAddr;
|
||||
|
||||
use crate::endpoint::{connection::Connection, quic::VarInt};
|
||||
|
||||
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
/// Outcome of [`EndpointHooks::before_connect`]
|
||||
#[derive(Debug)]
|
||||
pub enum BeforeConnectOutcome {
|
||||
/// Accept the connect attempt.
|
||||
Accept,
|
||||
/// Reject the connect attempt.
|
||||
Reject,
|
||||
}
|
||||
|
||||
/// Outcome of [`EndpointHooks::after_handshake`]
|
||||
#[derive(Debug)]
|
||||
pub enum AfterHandshakeOutcome {
|
||||
/// Accept the connection.
|
||||
Accept,
|
||||
/// Reject and close the connection.
|
||||
///
|
||||
/// See [`Connection::close`] for details on `error_code` and `reason`.
|
||||
///
|
||||
/// [`Connection::close`]: crate::endpoint::Connection::close
|
||||
Reject {
|
||||
/// Error code to send with the connection close frame.
|
||||
error_code: VarInt,
|
||||
/// Close reason to send with the connection close frame.
|
||||
reason: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
impl AfterHandshakeOutcome {
|
||||
/// Returns [`Self::Accept`].
|
||||
pub fn accept() -> Self {
|
||||
Self::Accept
|
||||
}
|
||||
|
||||
/// Returns [`Self::Reject`].
|
||||
pub fn reject(&self, error_code: VarInt, reason: &[u8]) -> Self {
|
||||
Self::Reject {
|
||||
error_code,
|
||||
reason: reason.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EndpointHooks intercept the connection establishment process of an [`Endpoint`].
|
||||
///
|
||||
/// Use [`Builder::hooks`] to install hooks onto an endpoint.
|
||||
///
|
||||
/// For each hook, all installed hooks are invoked in the order they were installed on
|
||||
/// the endpoint builder. If a hook returns `Accept`, processing continues with the next
|
||||
/// hook. If a hook returns `Reject`, processing is aborted and further hooks
|
||||
/// are not invoked for this hook point.
|
||||
///
|
||||
/// ## Notes to implementers
|
||||
///
|
||||
/// As hooks are stored on the endpoint, you must make sure to never store an [`Endpoint`]
|
||||
/// on the hook struct itself, as this would create reference counting loop and cause the
|
||||
/// endpoint to never be dropped, leaking memory.
|
||||
///
|
||||
/// [`Endpoint`]: crate::Endpoint
|
||||
/// [`Builder::hooks`]: crate::endpoint::Builder::hooks
|
||||
pub trait EndpointHooks: std::fmt::Debug + Send + Sync {
|
||||
/// Intercept outgoing connections before they are started.
|
||||
///
|
||||
/// This is called whenever a new outgoing connection is initiated via [`Endpoint::connect`]
|
||||
/// or [`Endpoint::connect_with_opts`].
|
||||
///
|
||||
/// If any hook returns [`BeforeConnectOutcome::Reject`], the connection attempt is aborted
|
||||
/// before any packets are sent to the remote.
|
||||
///
|
||||
/// [`Endpoint::connect`]: crate::Endpoint::connect
|
||||
/// [`Endpoint::connect_with_opts`]: crate::Endpoint::connect_with_opts
|
||||
fn before_connect<'a>(
|
||||
&'a self,
|
||||
_remote_addr: &'a EndpointAddr,
|
||||
_alpn: &'a [u8],
|
||||
) -> impl Future<Output = BeforeConnectOutcome> + Send + 'a {
|
||||
async { BeforeConnectOutcome::Accept }
|
||||
}
|
||||
|
||||
/// Intercept both incoming and outgoing connections once the TLS handshake has completed.
|
||||
///
|
||||
/// At this point in time, we know the remote's endpoint id and ALPN. If any hook returns
|
||||
/// [`AfterHandshakeOutcome::Reject`], the connection is closed with the provided error code
|
||||
/// and reason.
|
||||
///
|
||||
/// The hook receives the [`Connection`] by reference so that implementations can read any
|
||||
/// information they need synchronously. Do not clone the [`Connection`] out of the hook:
|
||||
/// holding a strong [`Connection`] handle keeps the connection alive and disables
|
||||
/// close-on-drop, which the primary use sites of the connection might rely on. If you need to
|
||||
/// keep a reference for later (for example to wait for the connection to close, or to
|
||||
/// look up the connection in a map), call [`Connection::weak_handle`] and store the
|
||||
/// resulting [`WeakConnectionHandle`] instead.
|
||||
///
|
||||
/// [`WeakConnectionHandle`]: crate::endpoint::WeakConnectionHandle
|
||||
fn after_handshake<'a>(
|
||||
&'a self,
|
||||
_conn: &'a Connection,
|
||||
) -> impl Future<Output = AfterHandshakeOutcome> + Send + 'a {
|
||||
async { AfterHandshakeOutcome::accept() }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait DynEndpointHooks: std::fmt::Debug + Send + Sync {
|
||||
fn before_connect<'a>(
|
||||
&'a self,
|
||||
remote_addr: &'a EndpointAddr,
|
||||
alpn: &'a [u8],
|
||||
) -> BoxFuture<'a, BeforeConnectOutcome>;
|
||||
fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome>;
|
||||
}
|
||||
|
||||
impl<T: EndpointHooks> DynEndpointHooks for T {
|
||||
fn before_connect<'a>(
|
||||
&'a self,
|
||||
remote_addr: &'a EndpointAddr,
|
||||
alpn: &'a [u8],
|
||||
) -> BoxFuture<'a, BeforeConnectOutcome> {
|
||||
Box::pin(EndpointHooks::before_connect(self, remote_addr, alpn))
|
||||
}
|
||||
|
||||
fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome> {
|
||||
Box::pin(EndpointHooks::after_handshake(self, conn))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct EndpointHooksList {
|
||||
inner: Vec<Box<dyn DynEndpointHooks>>,
|
||||
}
|
||||
|
||||
impl EndpointHooksList {
|
||||
pub(super) fn push(&mut self, hook: impl EndpointHooks + 'static) {
|
||||
let hook: Box<dyn DynEndpointHooks> = Box::new(hook);
|
||||
self.inner.push(hook);
|
||||
}
|
||||
|
||||
pub(super) async fn before_connect(
|
||||
&self,
|
||||
remote_addr: &EndpointAddr,
|
||||
alpn: &[u8],
|
||||
) -> BeforeConnectOutcome {
|
||||
for hook in self.inner.iter() {
|
||||
match hook.before_connect(remote_addr, alpn).await {
|
||||
BeforeConnectOutcome::Accept => continue,
|
||||
reject @ BeforeConnectOutcome::Reject => {
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
}
|
||||
BeforeConnectOutcome::Accept
|
||||
}
|
||||
|
||||
pub(super) async fn after_handshake(&self, conn: &Connection) -> AfterHandshakeOutcome {
|
||||
for hook in self.inner.iter() {
|
||||
match hook.after_handshake(conn).await {
|
||||
AfterHandshakeOutcome::Accept => continue,
|
||||
reject @ AfterHandshakeOutcome::Reject { .. } => {
|
||||
return reject;
|
||||
}
|
||||
}
|
||||
}
|
||||
AfterHandshakeOutcome::Accept
|
||||
}
|
||||
}
|
||||
Vendored
+184
@@ -0,0 +1,184 @@
|
||||
//! Presets allow configuring an endpoint quickly with a chosen set of defaults.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # async fn wrapper() -> n0_error::Result {
|
||||
//! use iroh::{Endpoint, RelayMode, Watcher, endpoint::presets};
|
||||
//!
|
||||
//! let endpoint = Endpoint::builder(presets::N0).bind().await?;
|
||||
//! # let _ = endpoint;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
use crate::endpoint::Builder;
|
||||
|
||||
/// A reusable bundle of endpoint [`Builder`] configuration.
|
||||
pub trait Preset {
|
||||
/// Applies the configuration to the passed in [`Builder`].
|
||||
fn apply(self, builder: Builder) -> Builder;
|
||||
}
|
||||
|
||||
/// An empty preset that doesn't set anything on the builder.
|
||||
///
|
||||
/// This doesn't set mandatory builder options, so using this in
|
||||
/// `Endpoint::bind(presets::Empty)` will always fail.
|
||||
///
|
||||
/// However, it can be useful, if you want control over all mandatory options
|
||||
/// yourself, by using `Endpoint::builder(presets::Empty)`.
|
||||
///
|
||||
/// If you prefer a minimal version that is guaranteed to work, see the
|
||||
/// [`Minimal`] preset.
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct Empty;
|
||||
|
||||
impl Preset for Empty {
|
||||
fn apply(self, builder: Builder) -> Builder {
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset that is almost empty, besides setting mandatory options.
|
||||
///
|
||||
/// At the moment the only mandatory option to set on the endpoint builder is
|
||||
/// [`Builder::crypto_provider`]. This preset makes a choice for that based on
|
||||
/// the current set of enabled features in iroh, which is why it's only available
|
||||
/// with the `tls-ring` or `tls-aws-lc-rs` feature flag.
|
||||
///
|
||||
/// It uses either [ring] or [aws-lc-rs], depending on which feature is enabled
|
||||
/// on iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct Minimal;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for Minimal {
|
||||
fn apply(self, mut builder: Builder) -> Builder {
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "tls-ring")]
|
||||
{
|
||||
builder = builder.crypto_provider(Arc::new(rustls::crypto::ring::default_provider()));
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "tls-aws-lc-rs", not(feature = "tls-ring")))]
|
||||
{
|
||||
builder =
|
||||
builder.crypto_provider(Arc::new(rustls::crypto::aws_lc_rs::default_provider()));
|
||||
}
|
||||
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the endpoint to use the n0 defaults
|
||||
///
|
||||
/// Currently this consists of
|
||||
/// - the DNS Address Lookup service.
|
||||
/// - the default relay servers provided by Number 0.
|
||||
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
|
||||
/// on which feature is enabled in iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// Due to the last point, this preset is only available with the `tls-ring` or
|
||||
/// `tls-aws-lc-rs` feature enabled.
|
||||
/// If you want to set your own crypto provider, we recommend copying the
|
||||
/// implementation of this preset into your own and setting the appropriate crypto
|
||||
/// provider there.
|
||||
///
|
||||
/// The default address lookup service publishes to and resolves from the
|
||||
/// n0.computer dns server `iroh.link`.
|
||||
///
|
||||
/// This is equivalent to adding a [`crate::address_lookup::PkarrPublisher`],
|
||||
/// a [`crate::address_lookup::PkarrResolver`], and (outside browsers) a
|
||||
/// [`crate::address_lookup::DnsAddressLookup`], all configured to use the
|
||||
/// n0.computer dns server.
|
||||
///
|
||||
/// This will by default use [`N0_DNS_PKARR_RELAY_PROD`].
|
||||
/// When in tests, or when the `test-utils` feature is enabled, this will use the
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`].
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`]: crate::address_lookup::N0_DNS_PKARR_RELAY_PROD
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::address_lookup::N0_DNS_PKARR_RELAY_STAGING
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct N0;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for N0 {
|
||||
fn apply(self, mut builder: Builder) -> Builder {
|
||||
use crate::{
|
||||
address_lookup::{PkarrPublisher, PkarrResolver},
|
||||
endpoint::default_relay_mode,
|
||||
};
|
||||
|
||||
builder = Minimal.apply(builder);
|
||||
|
||||
builder = builder.address_lookup(PkarrPublisher::n0_dns());
|
||||
|
||||
// Resolve using HTTPS requests to our DNS server's /pkarr path.
|
||||
builder = builder.address_lookup(PkarrResolver::n0_dns());
|
||||
|
||||
// Additionally resolve using DNS queries outside browsers.
|
||||
#[cfg(not(wasm_browser))]
|
||||
{
|
||||
builder = builder.address_lookup(crate::address_lookup::DnsAddressLookup::n0_dns());
|
||||
}
|
||||
|
||||
builder = builder.relay_mode(default_relay_mode());
|
||||
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the endpoint to use the n0 defaults, but with relay mode disabled.
|
||||
///
|
||||
/// Currently this consists of
|
||||
/// - setting `RelayMode::Disabled`
|
||||
/// - the DNS Address Lookup service, that publishes IP addresses rather than
|
||||
/// relay urls.
|
||||
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
|
||||
/// on which feature is enabled in iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// Due to the last point, this preset is only available with the `tls-ring` or
|
||||
/// `tls-aws-lc-rs` feature enabled.
|
||||
/// If you want to set your own crypto provider, we recommend copying the
|
||||
/// implementation of this preset into your own and setting the appropriate crypto
|
||||
/// provider there.
|
||||
///
|
||||
/// The default address lookup service publishes to and resolves from the
|
||||
/// n0.computer dns server `iroh.link`.
|
||||
///
|
||||
/// This is equivalent to adding a [`crate::address_lookup::PkarrPublisher`],
|
||||
/// a [`crate::address_lookup::PkarrResolver`], and (outside browsers) a
|
||||
/// [`crate::address_lookup::DnsAddressLookup`], all configured to use the
|
||||
/// n0.computer dns server.
|
||||
///
|
||||
/// This will by default use [`N0_DNS_PKARR_RELAY_PROD`].
|
||||
/// When in tests, or when the `test-utils` feature is enabled, this will use the
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`].
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`]: crate::address_lookup::N0_DNS_PKARR_RELAY_PROD
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::address_lookup::N0_DNS_PKARR_RELAY_STAGING
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct N0DisableRelay;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for N0DisableRelay {
|
||||
fn apply(self, builder: Builder) -> Builder {
|
||||
use crate::RelayMode;
|
||||
|
||||
N0.apply(builder).relay_mode(RelayMode::Disabled)
|
||||
}
|
||||
}
|
||||
Vendored
+716
@@ -0,0 +1,716 @@
|
||||
//! Exporting and encapsulating structs from noq
|
||||
//!
|
||||
//! Co-locates all iroh-noq exports.
|
||||
//!
|
||||
//! There are some structs that we use in particular ways, where we would like
|
||||
//! to limit or expand how those structs are used in iroh. By encapsulating them
|
||||
//! we can ensure the functionality needed to make iroh work.
|
||||
|
||||
#[cfg(feature = "qlog")]
|
||||
use std::path::Path;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
/// `noq` types that are used in the public iroh API.
|
||||
// Each type is notated with the iroh type or noq type that uses it.
|
||||
pub use noq::{
|
||||
AcceptBi, // iroh::endpoint::Connection
|
||||
AcceptUni, // iroh::endpoint::Connection
|
||||
AckFrequencyConfig, // iroh::endpoint::quic::QuicTransportConfig
|
||||
Closed, // iroh::endpoint::WeakConnectionHandle
|
||||
ClosedStream, // iroh::protocol::AcceptError, noq::RecvStream, noq::SendStream
|
||||
ConnectionError, // iroh::endpoint::ConnectError
|
||||
ConnectionStats, // iroh::endpoint::Connection
|
||||
Dir, // noq::StreamId
|
||||
IdleTimeout, // iroh::endpoint::quic::QuicTransportConfig
|
||||
MtuDiscoveryConfig, // iroh::endpoint::quic::QuicTransportConfig
|
||||
OpenBi, // iroh::endpoint::Connection
|
||||
OpenUni, // iroh::endpoint::Connection
|
||||
PathStats, // iroh::socket::remote_map::remote_state::PathInfo
|
||||
ReadDatagram, // iroh::endpoint::Connection
|
||||
ReadError, // noq::RecvStream
|
||||
ReadExactError, // noq::RecvStream
|
||||
ReadToEndError, // noq::RecvStream
|
||||
RecvStream, // noq::AcceptBi, noq::AcceptUni, noq::OpenBi, noq::OpenUni
|
||||
ResetError, // noq::RecvStream
|
||||
SendDatagram, // iroh::endpoint::Connection
|
||||
SendDatagramError, // iroh::endpoint::Connection
|
||||
SendStream, // noq::AcceptBi, noq::OpenUni
|
||||
Side, // iroh::endpoint::Connection, noq::StreamId,
|
||||
StoppedError, // noq::SendStream
|
||||
StreamId, // noq::RecvStream
|
||||
UnorderedRecvStream, // noq::RecvStream
|
||||
VarInt, // various
|
||||
VarIntBoundsExceeded, // noq::VarInt, noq::IdleTimeout
|
||||
WriteError, // noq::SendStream
|
||||
};
|
||||
#[cfg(feature = "qlog")]
|
||||
pub use noq::{QlogConfig, QlogFactory, QlogFileFactory};
|
||||
/// `noq_proto` types that are used in the public iroh API.
|
||||
// Each type is notated with the iroh type or noq type that uses it.
|
||||
pub use noq_proto::{
|
||||
ApplicationClose, // noq::ConnectionError
|
||||
Chunk, // noq::RecvStream
|
||||
ConnectError as QuicConnectError, // iroh::endpoint::ConnectWithOptsError
|
||||
ConnectionClose, // noq::ConnectionError
|
||||
DecryptedInitial, // iroh::endpoint::connection::Incoming
|
||||
FrameStats, // noq::ConnectionStats
|
||||
FrameType, // noq_proto::TransportError
|
||||
IncomingAlpns, // iroh::endpoint::DecryptedInitial
|
||||
PathId, // noq_proto::crypto::PacketKey
|
||||
RttEstimator, // noq_proto::congestion::Controller
|
||||
TimeSource, // iroh::endpoint::quic::ServerConfig
|
||||
TokenLog, // noq::ValidationTokenConfig
|
||||
TokenReuseError, // noq::TokenLog
|
||||
TransportError, // noq::ConnectionError
|
||||
TransportErrorCode, // noq_proto::TransportError
|
||||
UdpStats, // noq::ConnectionStats
|
||||
ValidationTokenConfig, // iroh::endpoint::quic::::ServerConfig
|
||||
congestion::{
|
||||
Controller, // iroh::endpoint::Connection
|
||||
ControllerFactory, // iroh::endpoint::quic::QuicTransportConfig
|
||||
ControllerMetrics, // noq_proto::congestion::Controller
|
||||
},
|
||||
crypto::{
|
||||
CryptoError, // noq_proto::crypto::CryptoError, noq_proto::crypto::PacketKey
|
||||
ExportKeyingMaterialError, // iroh::endpoint::Connection
|
||||
HandshakeTokenKey, // iroh::endpoint::quic::ServerConfig
|
||||
HeaderKey, // noq_proto::crypto::Keys
|
||||
Keys, // noq_proto::crypto::Session
|
||||
PacketKey, // noq_proto::crypto::Keys
|
||||
UnsupportedVersion, // noq_proto::ConnectError
|
||||
},
|
||||
transport_parameters::TransportParameters, // noq_proto::crypot::ServerConfig
|
||||
};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::socket::{
|
||||
HEARTBEAT_INTERVAL, MAX_MULTIPATH_PATHS, MAX_QNT_ADDRESSES, PATH_MAX_IDLE_TIMEOUT,
|
||||
};
|
||||
|
||||
/// Builder for a [`QuicTransportConfig`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QuicTransportConfigBuilder(noq::TransportConfig);
|
||||
|
||||
/// Parameters governing the core QUIC state machine
|
||||
///
|
||||
/// Default values should be suitable for most internet applications. Applications protocols which
|
||||
/// forbid remotely-initiated streams should set `max_concurrent_bidi_streams` and
|
||||
/// `max_concurrent_uni_streams` to zero.
|
||||
///
|
||||
/// In some cases, performance or resource requirements can be improved by tuning these values to
|
||||
/// suit a particular application and/or network connection. In particular, data window sizes can be
|
||||
/// tuned for a particular expected round trip time, link capacity, and memory availability. Tuning
|
||||
/// for higher bandwidths and latencies increases worst-case memory consumption, but does not impair
|
||||
/// performance at lower bandwidths and latencies. The default configuration is tuned for a 100Mbps
|
||||
/// link with a 100ms round trip time.
|
||||
///
|
||||
/// Use the [`QuicTransportConfigBuilder`] to customize these tunable fields.
|
||||
///
|
||||
/// In iroh, the config has some specific default values that make iroh's holepunching work
|
||||
/// well with QUIC multipath. Adjusting those settings may cause suboptimal usage.
|
||||
///
|
||||
/// Look at the following methods for more details:
|
||||
/// - [`QuicTransportConfigBuilder::default_path_keep_alive_interval`]
|
||||
/// - [`QuicTransportConfigBuilder::default_path_max_idle_timeout`]
|
||||
/// - [`QuicTransportConfigBuilder::max_concurrent_multipath_paths`]
|
||||
/// - [`QuicTransportConfigBuilder::max_remote_nat_traversal_addresses`]
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
/// use std::time::Duration;
|
||||
///
|
||||
/// use iroh::endpoint::QuicTransportConfig;
|
||||
///
|
||||
/// let _cfg = QuicTransportConfig::builder()
|
||||
/// .send_observed_address_reports(true)
|
||||
/// .build();
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QuicTransportConfig(Arc<noq::TransportConfig>);
|
||||
|
||||
impl QuicTransportConfig {
|
||||
/// Returns a default [`QuicTransportConfigBuilder`] that allows customizing
|
||||
/// a [`QuicTransportConfig`].
|
||||
pub fn builder() -> QuicTransportConfigBuilder {
|
||||
QuicTransportConfigBuilder::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for QuicTransportConfig {
|
||||
fn default() -> Self {
|
||||
QuicTransportConfigBuilder::new().build()
|
||||
}
|
||||
}
|
||||
|
||||
impl QuicTransportConfig {
|
||||
pub(crate) fn to_inner_arc(&self) -> Arc<noq::TransportConfig> {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl QuicTransportConfigBuilder {
|
||||
/// Creates a default [`QuicTransportConfigBuilder`].
|
||||
fn new() -> Self {
|
||||
let mut cfg = noq::TransportConfig::default();
|
||||
// Override some transport config settings.
|
||||
cfg.keep_alive_interval(Some(HEARTBEAT_INTERVAL));
|
||||
cfg.default_path_keep_alive_interval(Some(HEARTBEAT_INTERVAL));
|
||||
cfg.default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
|
||||
cfg.max_concurrent_multipath_paths(MAX_MULTIPATH_PATHS);
|
||||
cfg.max_remote_nat_traversal_addresses(MAX_QNT_ADDRESSES);
|
||||
cfg.server_handshake_migration(true);
|
||||
Self(cfg)
|
||||
}
|
||||
|
||||
/// Builds a [`QuicTransportConfig`] from the builder.
|
||||
pub fn build(self) -> QuicTransportConfig {
|
||||
QuicTransportConfig(Arc::new(self.0))
|
||||
}
|
||||
|
||||
/// Maximum number of incoming bidirectional streams that may be open concurrently.
|
||||
///
|
||||
/// Must be nonzero for the peer to open any bidirectional streams.
|
||||
///
|
||||
/// Worst-case memory use is directly proportional to `max_concurrent_bidi_streams *
|
||||
/// stream_receive_window`, with an upper bound proportional to `receive_window`.
|
||||
pub fn max_concurrent_bidi_streams(mut self, value: VarInt) -> Self {
|
||||
self.0.max_concurrent_bidi_streams(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Variant of `max_concurrent_bidi_streams` affecting unidirectional streams.
|
||||
pub fn max_concurrent_uni_streams(mut self, value: VarInt) -> Self {
|
||||
self.0.max_concurrent_uni_streams(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum duration of inactivity to accept before timing out the connection.
|
||||
///
|
||||
/// The true idle timeout is the minimum of this and the peer's own max idle timeout. `None`
|
||||
/// represents an infinite timeout. Defaults to 30 seconds.
|
||||
///
|
||||
/// **WARNING**: If a peer or its network path malfunctions or acts maliciously, an infinite
|
||||
/// idle timeout can result in permanently hung futures!
|
||||
///
|
||||
/// ```
|
||||
/// # use std::{convert::TryInto, time::Duration};
|
||||
/// # use iroh::endpoint::{QuicTransportConfig, VarInt, VarIntBoundsExceeded};
|
||||
/// # fn main() -> Result<(), VarIntBoundsExceeded> {
|
||||
/// let mut builder = QuicTransportConfig::builder()
|
||||
/// // Set the idle timeout as `VarInt`-encoded milliseconds
|
||||
/// .max_idle_timeout(Some(VarInt::from_u32(10_000).into()));
|
||||
///
|
||||
/// // Set the idle timeout as a `Duration`
|
||||
/// builder = builder.max_idle_timeout(Some(Duration::from_secs(10).try_into()?));
|
||||
///
|
||||
/// let _cfg = builder.build();
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn max_idle_timeout(mut self, value: Option<IdleTimeout>) -> Self {
|
||||
self.0.max_idle_timeout(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of bytes the peer may transmit without acknowledgement on any one stream
|
||||
/// before becoming blocked.
|
||||
///
|
||||
/// This should be set to at least the expected connection latency multiplied by the maximum
|
||||
/// desired throughput. Setting this smaller than `receive_window` helps ensure that a single
|
||||
/// stream doesn't monopolize receive buffers, which may otherwise occur if the application
|
||||
/// chooses not to read from a large stream for a time while still requiring data on other
|
||||
/// streams.
|
||||
pub fn stream_receive_window(mut self, value: VarInt) -> Self {
|
||||
self.0.stream_receive_window(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of bytes the peer may transmit across all streams of a connection before
|
||||
/// becoming blocked.
|
||||
///
|
||||
/// This should be set to at least the expected connection latency multiplied by the maximum
|
||||
/// desired throughput. Larger values can be useful to allow maximum throughput within a
|
||||
/// stream while another is blocked.
|
||||
pub fn receive_window(mut self, value: VarInt) -> Self {
|
||||
self.0.receive_window(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of bytes to transmit to a peer without acknowledgment.
|
||||
///
|
||||
/// Provides an upper bound on memory when communicating with peers that issue large amounts of
|
||||
/// flow control credit. Endpoints that wish to handle large numbers of connections robustly
|
||||
/// should take care to set this low enough to guarantee memory exhaustion does not occur if
|
||||
/// every connection uses the entire window.
|
||||
pub fn send_window(mut self, value: u64) -> Self {
|
||||
self.0.send_window(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether to implement fair queuing for send streams having the same priority.
|
||||
///
|
||||
/// When enabled, connections schedule data from outgoing streams having the same priority in a
|
||||
/// round-robin fashion. When disabled, streams are scheduled in the order they are written to.
|
||||
///
|
||||
/// Note that this only affects streams with the same priority. Higher priority streams always
|
||||
/// take precedence over lower priority streams.
|
||||
///
|
||||
/// Disabling fairness can reduce fragmentation and protocol overhead for workloads that use
|
||||
/// many small streams.
|
||||
pub fn send_fairness(mut self, value: bool) -> Self {
|
||||
self.0.send_fairness(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum reordering in packet number space before FACK style loss detection considers a
|
||||
/// packet lost. Should not be less than 3, per RFC5681.
|
||||
pub fn packet_threshold(mut self, value: u32) -> Self {
|
||||
self.0.packet_threshold(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum reordering in time space before time based loss detection considers a packet lost,
|
||||
/// as a factor of RTT.
|
||||
pub fn time_threshold(mut self, value: f32) -> Self {
|
||||
self.0.time_threshold(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// The RTT used before an RTT sample is taken.
|
||||
pub fn initial_rtt(mut self, value: Duration) -> Self {
|
||||
self.0.initial_rtt(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// The initial value to be used as the maximum UDP payload size before running MTU discovery
|
||||
/// (see [`QuicTransportConfigBuilder::mtu_discovery_config`]).
|
||||
///
|
||||
/// Must be at least 1200, which is the default, and known to be safe for typical internet
|
||||
/// applications. Larger values are more efficient, but increase the risk of packet loss due to
|
||||
/// exceeding the network path's IP MTU. If the provided value is higher than what the network
|
||||
/// path actually supports, packet loss will eventually trigger black hole detection and bring
|
||||
/// it down to [`QuicTransportConfigBuilder::min_mtu`].
|
||||
pub fn initial_mtu(mut self, value: u16) -> Self {
|
||||
self.0.initial_mtu(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// The maximum UDP payload size guaranteed to be supported by the network.
|
||||
///
|
||||
/// Must be at least 1200, which is the default, and lower than or equal to
|
||||
/// [`QuicTransportConfigBuilder::initial_mtu`].
|
||||
///
|
||||
/// Real-world MTUs can vary according to ISP, VPN, and properties of intermediate network links
|
||||
/// outside of either endpoint's control. Extreme care should be used when raising this value
|
||||
/// outside of private networks where these factors are fully controlled. If the provided value
|
||||
/// is higher than what the network path actually supports, the result will be unpredictable and
|
||||
/// catastrophic packet loss, without a possibility of repair. Prefer
|
||||
/// [`QuicTransportConfigBuilder::initial_mtu`] together with
|
||||
/// [`QuicTransportConfigBuilder::mtu_discovery_config`] to set a maximum UDP payload size that robustly
|
||||
/// adapts to the network.
|
||||
pub fn min_mtu(mut self, value: u16) -> Self {
|
||||
self.0.min_mtu(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the MTU discovery config (see [`MtuDiscoveryConfig`] for details).
|
||||
///
|
||||
/// Enabled by default.
|
||||
pub fn mtu_discovery_config(mut self, value: Option<MtuDiscoveryConfig>) -> Self {
|
||||
self.0.mtu_discovery_config(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Pad UDP datagrams carrying application data to current maximum UDP payload size.
|
||||
///
|
||||
/// Disabled by default. UDP datagrams containing loss probes are exempt from padding.
|
||||
///
|
||||
/// Enabling this helps mitigate traffic analysis by network observers, but it increases
|
||||
/// bandwidth usage. Without this mitigation precise plain text size of application datagrams as
|
||||
/// well as the total size of stream write bursts can be inferred by observers under certain
|
||||
/// conditions. This analysis requires either an uncongested connection or application datagrams
|
||||
/// too large to be coalesced.
|
||||
pub fn pad_to_mtu(mut self, value: bool) -> Self {
|
||||
self.0.pad_to_mtu(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Specifies the ACK frequency config (see [`AckFrequencyConfig`] for details).
|
||||
///
|
||||
/// The provided configuration will be ignored if the peer does not support the acknowledgement
|
||||
/// frequency QUIC extension.
|
||||
///
|
||||
/// Defaults to `None`, which disables controlling the peer's acknowledgement frequency. Even
|
||||
/// if set to `None`, the local side still supports the acknowledgement frequency QUIC
|
||||
/// extension and may use it in other ways.
|
||||
pub fn ack_frequency_config(mut self, value: Option<AckFrequencyConfig>) -> Self {
|
||||
self.0.ack_frequency_config(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Number of consecutive PTOs after which network is considered to be experiencing persistent congestion.
|
||||
pub fn persistent_congestion_threshold(mut self, value: u32) -> Self {
|
||||
self.0.persistent_congestion_threshold(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Period of inactivity before sending a keep-alive packet.
|
||||
///
|
||||
/// Keep-alive packets prevent an inactive but otherwise healthy connection from timing
|
||||
/// out. They are important to keep NAT bindings alive and firewalls open.
|
||||
///
|
||||
/// The default is 5s, please be careful when modifying this as it may affect connection
|
||||
/// stability. Must be set lower than the idle_timeout of both peers to be effective.
|
||||
pub fn keep_alive_interval(mut self, value: Duration) -> Self {
|
||||
self.0.keep_alive_interval(Some(value));
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum quantity of out-of-order crypto layer data to buffer.
|
||||
pub fn crypto_buffer_size(mut self, value: usize) -> Self {
|
||||
self.0.crypto_buffer_size(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the implementation is permitted to set the spin bit on this connection.
|
||||
///
|
||||
/// This allows passive observers to easily judge the round trip time of a connection, which can
|
||||
/// be useful for network administration but sacrifices a small amount of privacy.
|
||||
pub fn allow_spin(mut self, value: bool) -> Self {
|
||||
self.0.allow_spin(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of incoming application datagram bytes to buffer, or None to disable
|
||||
/// incoming datagrams.
|
||||
///
|
||||
/// The peer is forbidden to send single datagrams larger than this size. If the aggregate size
|
||||
/// of all datagrams that have been received from the peer but not consumed by the application
|
||||
/// exceeds this value, old datagrams are dropped until it is no longer exceeded.
|
||||
pub fn datagram_receive_buffer_size(mut self, value: Option<usize>) -> Self {
|
||||
self.0.datagram_receive_buffer_size(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of outgoing application datagram bytes to buffer.
|
||||
///
|
||||
/// While datagrams are sent ASAP, it is possible for an application to generate data faster
|
||||
/// than the link, or even the underlying hardware, can transmit them. This limits the amount of
|
||||
/// memory that may be consumed in that case. When the send buffer is full and a new datagram is
|
||||
/// sent, older datagrams are dropped until sufficient space is available.
|
||||
pub fn datagram_send_buffer_size(mut self, value: usize) -> Self {
|
||||
self.0.datagram_send_buffer_size(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// How to construct new `congestion::Controller`s.
|
||||
///
|
||||
/// Typically the refcounted configuration of a `congestion::Controller`,
|
||||
/// e.g. a `congestion::NewRenoConfig`.
|
||||
///
|
||||
/// # Example
|
||||
/// ```
|
||||
/// # use iroh::endpoint::QuicTransportConfig; use noq_proto::congestion; use std::sync::Arc;
|
||||
/// let config = QuicTransportConfig::builder()
|
||||
/// .congestion_controller_factory(Arc::new(congestion::NewRenoConfig::default()))
|
||||
/// .build();
|
||||
/// ```
|
||||
pub fn congestion_controller_factory(
|
||||
mut self,
|
||||
factory: Arc<dyn ControllerFactory + Send + Sync + 'static>,
|
||||
) -> Self {
|
||||
self.0.congestion_controller_factory(factory);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether to use "Generic Segmentation Offload" to accelerate transmits, when supported by the
|
||||
/// environment.
|
||||
///
|
||||
/// Defaults to `true`.
|
||||
///
|
||||
/// GSO dramatically reduces CPU consumption when sending large numbers of packets with the same
|
||||
/// headers, such as when transmitting bulk data on a connection. However, it is not supported
|
||||
/// by all network interface drivers or packet inspection tools. `noq-udp` will attempt to
|
||||
/// disable GSO automatically when unavailable, but this can lead to spurious packet loss at
|
||||
/// startup, temporarily degrading performance.
|
||||
pub fn enable_segmentation_offload(mut self, enabled: bool) -> Self {
|
||||
self.0.enable_segmentation_offload(enabled);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether to send observed address reports to peers.
|
||||
///
|
||||
/// This will aid peers in inferring their reachable address, which in most NATd networks
|
||||
/// will not be easily available to them.
|
||||
pub fn send_observed_address_reports(mut self, enabled: bool) -> Self {
|
||||
self.0.send_observed_address_reports(enabled);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether to receive observed address reports from other peers.
|
||||
///
|
||||
/// Peers with the address discovery extension enabled that are willing to provide observed
|
||||
/// address reports will do so if this transport parameter is set. In general, observed address
|
||||
/// reports cannot be trusted. This, however, can aid the current endpoint in inferring its
|
||||
/// reachable address, which in most NATd networks will not be easily available.
|
||||
pub fn receive_observed_address_reports(mut self, enabled: bool) -> Self {
|
||||
self.0.receive_observed_address_reports(enabled);
|
||||
self
|
||||
}
|
||||
|
||||
/// Enables the Multipath Extension for QUIC.
|
||||
///
|
||||
/// Setting this to any nonzero value will enable the Multipath Extension for QUIC,
|
||||
/// <https://datatracker.ietf.org/doc/draft-ietf-quic-multipath/>.
|
||||
///
|
||||
/// The value provided specifies the number maximum number of paths this endpoint may open
|
||||
/// concurrently when multipath is negotiated. For any path to be opened, the remote must
|
||||
/// enable multipath as well.
|
||||
///
|
||||
/// Note: this method will ignore values less than the recommended 13 and will log a warning.
|
||||
pub fn max_concurrent_multipath_paths(mut self, max_concurrent: u32) -> Self {
|
||||
if max_concurrent < MAX_MULTIPATH_PATHS + 1 {
|
||||
warn!(
|
||||
"QuicTransportConfig::max_concurrent_multipath_paths must be at minimum {}, ignoring user supplied value",
|
||||
MAX_MULTIPATH_PATHS + 1
|
||||
);
|
||||
return self;
|
||||
}
|
||||
self.0.max_concurrent_multipath_paths(max_concurrent);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a default per-path maximum idle timeout.
|
||||
///
|
||||
/// If the path is idle for this long the path will be abandoned. Bear in mind this will
|
||||
/// interact with the [`QuicTransportConfigBuilder::max_idle_timeout`], if the last path is
|
||||
/// abandoned the entire connection will be closed.
|
||||
///
|
||||
/// Note: values higher than `PATH_MAX_IDLE_TIMEOUT` (15 seconds) are clamped and a warning is logged.
|
||||
pub fn default_path_max_idle_timeout(mut self, timeout: Duration) -> Self {
|
||||
if timeout > PATH_MAX_IDLE_TIMEOUT {
|
||||
warn!(
|
||||
"QuicTransportConfig::default_path_max_idle must be at most {:?}, clamping",
|
||||
PATH_MAX_IDLE_TIMEOUT
|
||||
);
|
||||
self.0
|
||||
.default_path_max_idle_timeout(Some(PATH_MAX_IDLE_TIMEOUT));
|
||||
return self;
|
||||
}
|
||||
self.0.default_path_max_idle_timeout(Some(timeout));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a default per-path keep alive interval.
|
||||
///
|
||||
/// Note that this does not interact with the connection-wide
|
||||
/// [`QuicTransportConfigBuilder::keep_alive_interval`]. This setting will keep this path active,
|
||||
/// [`QuicTransportConfigBuilder::keep_alive_interval`] will keep the connection active, with no
|
||||
/// control over which path is used for this.
|
||||
///
|
||||
/// Note: this method will ignore values higher than the recommended 5 seconds and will log a warning.
|
||||
pub fn default_path_keep_alive_interval(mut self, interval: Duration) -> Self {
|
||||
if interval > HEARTBEAT_INTERVAL {
|
||||
warn!(
|
||||
"QuicTransportConfig::default_path_keep_alive must be at most {:?}, ignoring user supplied value",
|
||||
HEARTBEAT_INTERVAL
|
||||
);
|
||||
return self;
|
||||
}
|
||||
self.0.default_path_keep_alive_interval(Some(interval));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum number of nat traversal addresses this endpoint allows the remote to
|
||||
/// advertise.
|
||||
///
|
||||
/// Setting this to any nonzero value will enable Iroh's holepunching, loosely based in the Nat
|
||||
/// Traversal Extension for QUIC, see
|
||||
/// <https://www.ietf.org/archive/id/draft-seemann-quic-nat-traversal-02.html>
|
||||
///
|
||||
/// This implementation expects the multipath extension to be enabled as well. If not yet
|
||||
/// enabled via [`Self::max_concurrent_multipath_paths`], a default value of
|
||||
/// 8 will be used.
|
||||
///
|
||||
/// Note: this method will ignore values less than the recommended 8 and will log a warning.
|
||||
pub fn max_remote_nat_traversal_addresses(mut self, max_addresses: u8) -> Self {
|
||||
if max_addresses < MAX_MULTIPATH_PATHS as u8 {
|
||||
warn!(
|
||||
"QuicTransportConfig::max_remote_nat_traversal_addresses must be at least {}, ignoring user supplied value",
|
||||
MAX_MULTIPATH_PATHS
|
||||
);
|
||||
return self;
|
||||
}
|
||||
self.0.max_remote_nat_traversal_addresses(max_addresses);
|
||||
self
|
||||
}
|
||||
|
||||
/// Configures qlog capturing by setting a [`QlogFactory`].
|
||||
///
|
||||
/// This assigns a [`QlogFactory`] that produces qlog capture configurations for
|
||||
/// individual connections.
|
||||
#[cfg(feature = "qlog")]
|
||||
pub fn qlog_factory(mut self, factory: Arc<dyn QlogFactory>) -> Self {
|
||||
self.0.qlog_factory(factory);
|
||||
self
|
||||
}
|
||||
|
||||
/// Configures qlog capturing through the `QLOGDIR` environment variable.
|
||||
///
|
||||
/// This uses [`QlogFileFactory::from_env`] to create a factory to write qlog traces
|
||||
/// into the directory set through the `QLOGDIR` environment variable.
|
||||
///
|
||||
/// If `QLOGDIR` is not set, no traces will be written. If `QLOGDIR` is set to a path
|
||||
/// that does not exist, it will be created.
|
||||
///
|
||||
/// The files will be prefixed with `prefix`.
|
||||
#[cfg(feature = "qlog")]
|
||||
pub fn qlog_from_env(mut self, prefix: &str) -> Self {
|
||||
self.0.qlog_from_env(prefix);
|
||||
self
|
||||
}
|
||||
|
||||
/// Configures qlog capturing into a directory.
|
||||
///
|
||||
/// This uses [`QlogFileFactory`] to create a factory to write qlog traces into
|
||||
/// the specified directory. The files will be prefixed with `prefix`.
|
||||
#[cfg(feature = "qlog")]
|
||||
pub fn qlog_from_path(mut self, path: impl AsRef<Path>, prefix: &str) -> Self {
|
||||
self.0.qlog_from_path(path, prefix);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A builder for a [`ServerConfig`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfigBuilder {
|
||||
inner: noq::ServerConfig,
|
||||
transport: QuicTransportConfig,
|
||||
}
|
||||
|
||||
/// Parameters governing incoming connections
|
||||
///
|
||||
/// Default values should be suitable for most internet applications.
|
||||
///
|
||||
/// Use a [`ServerConfigBuilder`] to adjust the default values.
|
||||
///
|
||||
/// To create a [`ServerConfig`] compatible with your [`Endpoint`] identity, use the [`Endpoint::create_server_config_builder`] method.
|
||||
///
|
||||
/// [`Endpoint`]: crate::Endpoint
|
||||
/// [`Endpoint::create_server_config_builder`]: crate::Endpoint::create_server_config_builder
|
||||
// Note: used in `iroh::endpoint::connection::Incoming::accept_with`
|
||||
// This is new-typed since `noq::ServerConfig` takes a `TransportConfig`, which we new-type as a `QuicTransportConfig`
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfig(Arc<noq::ServerConfig>);
|
||||
|
||||
impl ServerConfig {
|
||||
pub(crate) fn to_inner_arc(&self) -> Arc<noq::ServerConfig> {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerConfigBuilder {
|
||||
/// Build a [`ServerConfig`] from a [`ServerConfigBuilder`].
|
||||
pub fn build(self) -> ServerConfig {
|
||||
ServerConfig(Arc::new(self.inner))
|
||||
}
|
||||
|
||||
pub(crate) fn new(inner: noq::ServerConfig, transport: QuicTransportConfig) -> Self {
|
||||
Self { inner, transport }
|
||||
}
|
||||
|
||||
/// Sets a custom [`QuicTransportConfig`].
|
||||
pub fn set_transport_config(mut self, transport: QuicTransportConfig) -> Self {
|
||||
self.inner.transport_config(transport.to_inner_arc());
|
||||
self.transport = transport;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a custom [`ValidationTokenConfig`].
|
||||
pub fn set_validation_token_config(mut self, validation_token: ValidationTokenConfig) -> Self {
|
||||
self.inner.validation_token_config(validation_token);
|
||||
self
|
||||
}
|
||||
|
||||
/// Private key used to authenticate data included in handshake tokens
|
||||
pub fn set_token_key(mut self, value: Arc<dyn HandshakeTokenKey>) -> Self {
|
||||
self.inner.token_key(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Duration after a retry token was issued for which it's considered valid
|
||||
///
|
||||
/// Defaults to 15 seconds.
|
||||
pub fn set_retry_token_lifetime(mut self, value: Duration) -> Self {
|
||||
self.inner.retry_token_lifetime(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of [`Incoming`] to allow to exist at a time.
|
||||
///
|
||||
/// An [`Incoming`] comes into existence when an incoming connection attempt
|
||||
/// is received and stops existing when the application either accepts it or otherwise disposes
|
||||
/// of it. While this limit is reached, new incoming connection attempts are immediately
|
||||
/// refused. Larger values have greater worst-case memory consumption, but accommodate greater
|
||||
/// application latency in handling incoming connection attempts.
|
||||
///
|
||||
/// The default value is set to 65536. With a typical Ethernet MTU of 1500 bytes, this limits
|
||||
/// memory consumption from this to under 100 MiB--a generous amount that still prevents memory
|
||||
/// exhaustion in most contexts.
|
||||
///
|
||||
/// [`Incoming`]: crate::endpoint::Incoming
|
||||
pub fn set_max_incoming(mut self, max_incoming: usize) -> Self {
|
||||
self.inner.max_incoming(max_incoming);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of received bytes to buffer for each [`Incoming`].
|
||||
///
|
||||
/// An [`Incoming`] comes into existence when an incoming connection attempt
|
||||
/// is received and stops existing when the application either accepts it or otherwise disposes
|
||||
/// of it. This limit governs only packets received within that period, and does not include
|
||||
/// the first packet. Packets received in excess of this limit are dropped, which may cause
|
||||
/// 0-RTT or handshake data to have to be retransmitted.
|
||||
///
|
||||
/// The default value is set to 10 MiB--an amount such that in most situations a client would
|
||||
/// not transmit that much 0-RTT data faster than the server handles the corresponding
|
||||
/// [`Incoming`].
|
||||
///
|
||||
/// [`Incoming`]: crate::endpoint::Incoming
|
||||
pub fn set_incoming_buffer_size(mut self, incoming_buffer_size: u64) -> Self {
|
||||
self.inner.incoming_buffer_size(incoming_buffer_size);
|
||||
self
|
||||
}
|
||||
|
||||
/// Maximum number of received bytes to buffer for all [`Incoming`]
|
||||
/// collectively.
|
||||
///
|
||||
/// An [`Incoming`] comes into existence when an incoming connection attempt
|
||||
/// is received and stops existing when the application either accepts it or otherwise disposes
|
||||
/// of it. This limit governs only packets received within that period, and does not include
|
||||
/// the first packet. Packets received in excess of this limit are dropped, which may cause
|
||||
/// 0-RTT or handshake data to have to be retransmitted.
|
||||
///
|
||||
/// The default value is set to 100 MiB--a generous amount that still prevents memory
|
||||
/// exhaustion in most contexts.
|
||||
///
|
||||
/// [`Incoming`]: crate::endpoint::Incoming
|
||||
pub fn set_incoming_buffer_size_total(mut self, incoming_buffer_size_total: u64) -> Self {
|
||||
self.inner
|
||||
.incoming_buffer_size_total(incoming_buffer_size_total);
|
||||
self
|
||||
}
|
||||
|
||||
/// Object to get current [`SystemTime`].
|
||||
///
|
||||
/// This exists to allow system time to be mocked in tests, or wherever else desired.
|
||||
///
|
||||
/// Defaults to [`noq::StdSystemTime`], which simply calls [`SystemTime::now()`](std::time::SystemTime::now).
|
||||
///
|
||||
/// [`SystemTime`]: std::time::SystemTime
|
||||
pub fn set_time_source(mut self, time_source: Arc<dyn TimeSource>) -> Self {
|
||||
self.inner.time_source(time_source);
|
||||
self
|
||||
}
|
||||
}
|
||||
Vendored
+306
@@ -0,0 +1,306 @@
|
||||
//! Peer-to-peer QUIC connections.
|
||||
//!
|
||||
//! iroh is a library to establish direct connectivity between peers. It exposes an
|
||||
//! interface to [QUIC] connections and streams to the user, while implementing direct
|
||||
//! connectivity using [hole punching] complemented by relay servers under the hood.
|
||||
//!
|
||||
//! An iroh endpoint is created and controlled by the [`Endpoint`], e.g. connecting to
|
||||
//! another endpoint:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! # use n0_error::{StackResultExt, StdResultExt};
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
//! let addr: EndpointAddr = todo!();
|
||||
//! let ep = Endpoint::bind(presets::N0).await?;
|
||||
//! let conn = ep.connect(addr, b"my-alpn").await?;
|
||||
//! let mut send_stream = conn.open_uni().await.std_context("unable to open uni")?;
|
||||
//! send_stream
|
||||
//! .write_all(b"msg")
|
||||
//! .await
|
||||
//! .std_context("unable to write all")?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! The other endpoint can accept incoming connections using the [`Endpoint`] as well:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! # use n0_error::{StackResultExt, StdResultExt};
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
//! let ep = Endpoint::builder(presets::N0)
|
||||
//! .alpns(vec![b"my-alpn".to_vec()])
|
||||
//! .bind()
|
||||
//! .await?;
|
||||
//! let conn = ep
|
||||
//! .accept()
|
||||
//! .await
|
||||
//! .context("accept error")?
|
||||
//! .await
|
||||
//! .std_context("connecting error")?;
|
||||
//! let mut recv_stream = conn.accept_uni().await.std_context("unable to open uni")?;
|
||||
//! let mut buf = [0u8; 3];
|
||||
//! recv_stream
|
||||
//! .read_exact(&mut buf)
|
||||
//! .await
|
||||
//! .std_context("unable to read")?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Of course you can also use [bi-directional streams] or any other features from QUIC.
|
||||
//!
|
||||
//! For more elaborate examples, see [below](#examples) or the examples directory in
|
||||
//! the source repository.
|
||||
//!
|
||||
//!
|
||||
//! # Connection Establishment
|
||||
//!
|
||||
//! An iroh connection between two iroh endpoints is usually established with the help
|
||||
//! of a Relay server. When creating the [`Endpoint`] it connects to the closest Relay
|
||||
//! server and designates this as the *home relay*. When other endpoints want to connect they
|
||||
//! first establish connection via this home relay. As soon as connection between the two
|
||||
//! endpoints is established they will attempt to create a direct connection, using [hole
|
||||
//! punching] if needed. Once the direct connection is established the relay server is no
|
||||
//! longer involved in the connection.
|
||||
//!
|
||||
//! If one of the iroh endpoints can be reached directly, connectivity can also be
|
||||
//! established without involving a Relay server. This is done by using the endpoint's
|
||||
//! listening addresses in the connection establishment instead of the [`RelayUrl`] which
|
||||
//! is used to identify a Relay server. Of course it is also possible to use both a
|
||||
//! [`RelayUrl`] and direct addresses at the same time to connect.
|
||||
//!
|
||||
//!
|
||||
//! # Encryption
|
||||
//!
|
||||
//! The connection is encrypted using TLS, like standard QUIC connections. Unlike standard
|
||||
//! QUIC there is no client, server or server TLS key and certificate chain. Instead each iroh endpoint has a
|
||||
//! unique [`SecretKey`] used to authenticate and encrypt the connection. When an iroh
|
||||
//! endpoint connects, it uses the corresponding [`PublicKey`] to ensure the connection is only
|
||||
//! established with the intended peer.
|
||||
//!
|
||||
//! Since the [`PublicKey`] is also used to identify the iroh endpoint it is also known as
|
||||
//! the [`EndpointId`]. As encryption is an integral part of TLS as used in QUIC this
|
||||
//! [`EndpointId`] is always a required parameter to establish a connection.
|
||||
//!
|
||||
//! When accepting connections the peer's [`EndpointId`] is authenticated. However it is up to
|
||||
//! the application to decide if a particular peer is allowed to connect or not.
|
||||
//!
|
||||
//!
|
||||
//! # Relay Servers
|
||||
//!
|
||||
//! Relay servers exist to ensure all iroh endpoints are always reachable. They accept
|
||||
//! **encrypted** traffic for iroh endpoints which are connected to them, forwarding it to
|
||||
//! the correct destination based on the [`EndpointId`] only. Since endpoints only send encrypted
|
||||
//! traffic, the Relay servers can not decode any traffic for other iroh endpoints and only
|
||||
//! forward it.
|
||||
//!
|
||||
//! The connections to the Relay server are initiated as normal HTTP 1.1 connections using
|
||||
//! TLS. Once connected the transport is upgraded to a plain TCP connection using a custom
|
||||
//! protocol. All further data is then sent using this custom relaying protocol. Usually
|
||||
//! soon after the connection is established via the Relay it will migrate to a direct
|
||||
//! connection. However if this is not possible the connection will keep flowing over the
|
||||
//! relay server as a fallback.
|
||||
//!
|
||||
//! Additionally to providing reliable connectivity between iroh endpoints, Relay servers
|
||||
//! provide some functions to assist in [hole punching]. They have various services to help
|
||||
//! endpoints understand their own network situation. This includes offering a [QAD] server,
|
||||
//! but also a few HTTP extra endpoints as well as responding to ICMP echo requests.
|
||||
//!
|
||||
//! By default the [number 0] relay servers are used, see [`RelayMode::Default`].
|
||||
//!
|
||||
//!
|
||||
//! # Connections and Streams
|
||||
//!
|
||||
//! An iroh endpoint is managed using the [`Endpoint`] and this is used to create or accept
|
||||
//! connections to other endpoints. To establish a connection to an iroh endpoint you need to
|
||||
//! know three pieces of information:
|
||||
//!
|
||||
//! - The [`EndpointId`] of the peer to connect to.
|
||||
//! - Some addressing information:
|
||||
//! - Usually the [`RelayUrl`] identifying the Relay server.
|
||||
//! - Sometimes, or usually additionally, any direct addresses which might be known.
|
||||
//! - The QUIC/TLS Application-Layer Protocol Negotiation, or [ALPN], name to use.
|
||||
//!
|
||||
//! The ALPN is used by both sides to agree on which application-specific protocol will be
|
||||
//! used over the resulting QUIC connection. These can be protocols like `h3` used for
|
||||
//! [HTTP/3][HTTP3], but more commonly will be a custom identifier for the application.
|
||||
//!
|
||||
//! Once connected the API exposes QUIC streams. These are very cheap to create so can be
|
||||
//! created at any time and can be used to create very many short-lived stream as well as
|
||||
//! long-lived streams. There are two stream types to choose from:
|
||||
//!
|
||||
//! - **Uni-directional** which only allows the peer which initiated the stream to send
|
||||
//! data.
|
||||
//!
|
||||
//! - **Bi-directional** which allows both peers to send and receive data. However, the
|
||||
//! initiator of this stream has to send data before the peer will be aware of this
|
||||
//! stream.
|
||||
//!
|
||||
//! Additionally to being extremely light-weight, streams can be interleaved and will not
|
||||
//! block each other. Allowing many streams to co-exist, regardless of how long they last.
|
||||
//!
|
||||
//! <div class="warning">
|
||||
//!
|
||||
//! To keep streams cheap, they are lazily created on the network: only once a sender starts
|
||||
//! sending data on the stream will the receiver become aware of a stream. This means only
|
||||
//! calling [`Connection::open_bi`] is not sufficient for the corresponding call to
|
||||
//! [`Connection::accept_bi`] to return. The sender **must** send data on the stream before
|
||||
//! the receiver's [`Connection::accept_bi`] call will return.
|
||||
//!
|
||||
//! </div>
|
||||
//!
|
||||
//! ## Address Lookup
|
||||
//!
|
||||
//! The need to know the [`RelayUrl`] *or* some direct addresses in addition to the
|
||||
//! [`EndpointId`] to connect to an iroh endpoint can be an obstacle. To address this, the
|
||||
//! [`endpoint::Builder`] allows you to configure an [`address_lookup`] service.
|
||||
//!
|
||||
//! The [`address_lookup::DnsAddressLookup`] service is an address lookup service which will publish the [`RelayUrl`]
|
||||
//! and direct addresses to a service publishing those as DNS records. To connect it looks
|
||||
//! up the [`EndpointId`] in the DNS system to find the addressing details. This enables
|
||||
//! connecting using only the [`EndpointId`] which is often more convenient and resilient.
|
||||
//!
|
||||
//! See [the Address Lookup module] for more details.
|
||||
//!
|
||||
//!
|
||||
//! # Examples
|
||||
//!
|
||||
//! The central struct is the [`Endpoint`], which allows you to connect to other endpoints:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
//!
|
||||
//! async fn connect(addr: EndpointAddr) -> Result<()> {
|
||||
//! // The Endpoint is the central object that manages an iroh node.
|
||||
//! let ep = Endpoint::bind(presets::N0).await?;
|
||||
//!
|
||||
//! // Establish a QUIC connection, open a bi-directional stream, exchange messages.
|
||||
//! let conn = ep.connect(addr, b"hello-world").await?;
|
||||
//! let (mut send_stream, mut recv_stream) = conn.open_bi().await.std_context("open bi")?;
|
||||
//! send_stream.write_all(b"hello").await.std_context("write")?;
|
||||
//! send_stream.finish().std_context("finish")?;
|
||||
//! // `read_to_end` waits until the peer finishes or closes its send side.
|
||||
//! let _msg = recv_stream.read_to_end(10).await.std_context("read")?;
|
||||
//!
|
||||
//! // Gracefully close the connection and endpoint.
|
||||
//! conn.close(1u8.into(), b"done");
|
||||
//! ep.close().await;
|
||||
//! println!("Client closed");
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Every [`Endpoint`] can also accept connections:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
//! use n0_future::StreamExt;
|
||||
//!
|
||||
//! async fn accept() -> Result<()> {
|
||||
//! // To accept connections at least one ALPN must be configured.
|
||||
//! let ep = Endpoint::builder(presets::N0)
|
||||
//! .alpns(vec![b"hello-world".to_vec()])
|
||||
//! .bind()
|
||||
//! .await?;
|
||||
//!
|
||||
//! // Accept a QUIC connection, accept a bi-directional stream, exchange messages.
|
||||
//! let conn = ep
|
||||
//! .accept()
|
||||
//! .await
|
||||
//! .context("no incoming connection")?
|
||||
//! .await
|
||||
//! .context("accept conn")?;
|
||||
//! let (mut send_stream, mut recv_stream) =
|
||||
//! conn.accept_bi().await.std_context("accept stream")?;
|
||||
//! // `read_to_end` terminates once the client calls `finish` on its send stream.
|
||||
//! let _msg = recv_stream.read_to_end(10).await.std_context("read")?;
|
||||
//! send_stream.write_all(b"world").await.std_context("write")?;
|
||||
//! send_stream.finish().std_context("finish")?;
|
||||
//!
|
||||
//! // Wait for the client to close the connection and gracefully close the endpoint.
|
||||
//! conn.closed().await;
|
||||
//! ep.close().await;
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Please see the examples directory for more nuanced examples.
|
||||
//!
|
||||
//!
|
||||
//! [QUIC]: https://quicwg.org
|
||||
//! [bi-directional streams]: crate::endpoint::Connection::open_bi
|
||||
//! [hole punching]: https://en.wikipedia.org/wiki/Hole_punching_(networking)
|
||||
//! [socket addresses]: https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html
|
||||
//! [QAD]: https://www.ietf.org/archive/id/draft-ietf-quic-address-discovery-00.html
|
||||
//! [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
|
||||
//! [HTTP3]: https://en.wikipedia.org/wiki/HTTP/3
|
||||
//! [`SecretKey`]: crate::SecretKey
|
||||
//! [`PublicKey`]: crate::PublicKey
|
||||
//! [`RelayUrl`]: crate::RelayUrl
|
||||
//! [`address_lookup`]: crate::endpoint::Builder::address_lookup
|
||||
//! [`address_lookup::DnsAddressLookup`]: crate::address_lookup::DnsAddressLookup
|
||||
//! [number 0]: https://n0.computer
|
||||
//! [`RelayMode::Default`]: crate::RelayMode::Default
|
||||
//! [the Address Lookup module]: crate::address_lookup
|
||||
//! [`Connection::open_bi`]: crate::endpoint::Connection::open_bi
|
||||
//! [`Connection::accept_bi`]: crate::endpoint::Connection::accept_bi
|
||||
|
||||
#![recursion_limit = "256"]
|
||||
#![deny(missing_docs, rustdoc::broken_intra_doc_links, unreachable_pub)]
|
||||
#![cfg_attr(wasm_browser, allow(unused))]
|
||||
#![cfg_attr(not(test), deny(clippy::unwrap_used))]
|
||||
#![cfg_attr(iroh_docsrs, feature(doc_cfg))]
|
||||
|
||||
mod socket;
|
||||
pub mod tls;
|
||||
|
||||
pub(crate) mod portmapper;
|
||||
pub(crate) mod runtime;
|
||||
pub(crate) mod util;
|
||||
|
||||
pub mod address_lookup;
|
||||
pub mod defaults;
|
||||
pub mod endpoint;
|
||||
pub mod metrics;
|
||||
mod net_report;
|
||||
pub mod protocol;
|
||||
|
||||
pub use endpoint::{Endpoint, RelayMode};
|
||||
pub use iroh_base::{
|
||||
EndpointAddr, EndpointId, KeyParsingError, PublicKey, RelayUrl, RelayUrlParseError, SecretKey,
|
||||
Signature, SignatureError, TransportAddr,
|
||||
};
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub use iroh_dns::dns;
|
||||
pub use iroh_dns::endpoint_info;
|
||||
pub use iroh_relay::{RelayConfig, RelayMap};
|
||||
pub use n0_watcher::Watcher;
|
||||
pub use net_report::{NetReportConfig, TIMEOUT as NET_REPORT_TIMEOUT};
|
||||
|
||||
#[cfg(feature = "unstable-net-report")]
|
||||
pub mod unstable_net_report {
|
||||
//! Exports of net report types reachable via [`crate::endpoint::Endpoint::net_report`].
|
||||
/// This API is unstable and gated behind the `unstable-net-report` feature.
|
||||
/// It is not covered by semantic versioning guarantees and may change in any release
|
||||
/// without a major version bump.
|
||||
pub use crate::net_report::{Probe, RelayLatencies, Report as NetReport};
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
pub mod test_utils;
|
||||
Vendored
+37
@@ -0,0 +1,37 @@
|
||||
//! Co-locating all of the iroh metrics structs
|
||||
use std::sync::Arc;
|
||||
|
||||
use iroh_metrics::MetricsGroupSet;
|
||||
#[cfg(feature = "test-utils")]
|
||||
pub use iroh_relay::server::Metrics as RelayMetrics;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use crate::{net_report::Metrics as NetReportMetrics, socket::Metrics as SocketMetrics};
|
||||
|
||||
/// Metrics collected by an [`crate::endpoint::Endpoint`].
|
||||
///
|
||||
/// See [`crate::endpoint::Endpoint::metrics`] for details.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize, MetricsGroupSet)]
|
||||
#[metrics(name = "endpoint")]
|
||||
#[non_exhaustive]
|
||||
pub struct EndpointMetrics {
|
||||
/// Metrics collected by the endpoint's socket.
|
||||
pub socket: Arc<SocketMetrics>,
|
||||
/// Metrics collected by net reports.
|
||||
pub net_report: Arc<NetReportMetrics>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::EndpointMetrics;
|
||||
#[test]
|
||||
fn test_serde() {
|
||||
let metrics = EndpointMetrics::default();
|
||||
metrics.socket.actor_link_change.inc();
|
||||
metrics.net_report.reports.inc_by(10);
|
||||
let encoded = postcard::to_stdvec(&metrics).unwrap();
|
||||
let decoded: EndpointMetrics = postcard::from_bytes(&encoded).unwrap();
|
||||
assert_eq!(decoded.socket.actor_link_change.get(), 1);
|
||||
assert_eq!(decoded.net_report.reports.get(), 10);
|
||||
}
|
||||
}
|
||||
Vendored
+1255
File diff suppressed because it is too large.
Load diff
+39
@@ -0,0 +1,39 @@
|
||||
//! Default values used in net_report.
|
||||
|
||||
/// Contains all timeouts that we use in `iroh-net-report`.
|
||||
pub(crate) mod timeouts {
|
||||
use n0_future::time::Duration;
|
||||
|
||||
// Timeouts for net_report
|
||||
|
||||
/// The maximum amount of time, in seconds, the net_report will spend gathering a single report.
|
||||
// This is separated from `OVERALL_REPORT_TIMEOUT` to use as a reference
|
||||
// in documentation outside of this crate. `OVERALL_REPORT_TIMEOUT` is a
|
||||
// duration and rustdoc cannot calculate it at runtime, and so cannot be
|
||||
// used directly for documentation purposes.
|
||||
pub const TIMEOUT: u64 = 5;
|
||||
|
||||
/// The maximum amount of time net_report will spend gathering a single report.
|
||||
pub(crate) const OVERALL_REPORT_TIMEOUT: Duration = Duration::from_secs(TIMEOUT);
|
||||
|
||||
/// The total time we wait for all the probes.
|
||||
///
|
||||
/// This includes the QAD and HTTPS probes, which will all
|
||||
/// start at different times based on the ProbePlan.
|
||||
pub(crate) const PROBES_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// How long to await for a captive-portal result.
|
||||
///
|
||||
/// This delay is chosen so it starts after good-working QAD probes
|
||||
/// would have finished, but not too long so the delay is bearable if
|
||||
/// UDP/QAD is blocked.
|
||||
pub(crate) const CAPTIVE_PORTAL_DELAY: Duration = Duration::from_millis(200);
|
||||
|
||||
/// Timeout for captive portal checks
|
||||
///
|
||||
/// Must be lower than [`OVERALL_REPORT_TIMEOUT`] minus
|
||||
/// [`CAPTIVE_PORTAL_DELAY`].
|
||||
pub(crate) const CAPTIVE_PORTAL_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
pub(crate) const DNS_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
use iroh_metrics::{Counter, MetricsGroup};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Enum of metrics for the module
|
||||
#[derive(Debug, Default, MetricsGroup, Serialize, Deserialize)]
|
||||
#[metrics(name = "net_report")]
|
||||
#[non_exhaustive]
|
||||
pub struct Metrics {
|
||||
/// Number of reports executed by net_report, including full reports.
|
||||
pub reports: Counter,
|
||||
/// Number of full reports executed by net_report
|
||||
pub reports_full: Counter,
|
||||
/// Number of port mapping attempts.
|
||||
pub portmap_attempts: Counter,
|
||||
/// Number of times an external address was obtained via port mapping.
|
||||
pub portmap_external_address_updated: Counter,
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
//! Options for creating a report gen client.
|
||||
|
||||
pub(crate) use imp::Options;
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
mod imp {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use url::Url;
|
||||
|
||||
use crate::net_report::{NetReportConfig, QuicConfig, probes::Probe};
|
||||
|
||||
/// Options for running probes
|
||||
///
|
||||
/// By default, will run Https probes.
|
||||
///
|
||||
/// Use [`Options::quic_config`] to enable QUIC address discovery.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Options {
|
||||
/// The configuration needed to launch QUIC address discovery probes.
|
||||
///
|
||||
/// If not provided, will not run QUIC address discovery.
|
||||
pub(crate) quic_config: Option<QuicConfig>,
|
||||
/// TLS config for HTTPS probes.
|
||||
pub(crate) tls_config: rustls::ClientConfig,
|
||||
/// Proxy to send the HTTP(S) based probes through.
|
||||
///
|
||||
/// If not provided, the probes connect directly.
|
||||
pub(crate) proxy_url: Option<Url>,
|
||||
/// User-facing configuration.
|
||||
pub(crate) user_config: NetReportConfig,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
pub(crate) fn new(tls_config: rustls::ClientConfig) -> Self {
|
||||
Self {
|
||||
quic_config: None,
|
||||
tls_config,
|
||||
proxy_url: None,
|
||||
user_config: NetReportConfig::default(),
|
||||
}
|
||||
}
|
||||
/// Enable quic probes
|
||||
pub(crate) fn quic_config(mut self, quic_config: Option<QuicConfig>) -> Self {
|
||||
self.quic_config = quic_config;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the proxy to send the HTTP(S) based probes through.
|
||||
pub(crate) fn proxy_url(mut self, proxy_url: Option<Url>) -> Self {
|
||||
self.proxy_url = proxy_url;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the net report configuration.
|
||||
pub(crate) fn net_report_config(mut self, config: NetReportConfig) -> Self {
|
||||
self.user_config = config;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turn the options into set of valid protocols
|
||||
pub(crate) fn as_protocols(&self) -> BTreeSet<Probe> {
|
||||
let mut protocols = BTreeSet::new();
|
||||
if let Some(ref quic) = self.quic_config {
|
||||
if quic.ipv4 {
|
||||
protocols.insert(Probe::QadIpv4);
|
||||
}
|
||||
if quic.ipv6 {
|
||||
protocols.insert(Probe::QadIpv6);
|
||||
}
|
||||
}
|
||||
if self.user_config.https_probes {
|
||||
protocols.insert(Probe::Https);
|
||||
}
|
||||
protocols
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
mod imp {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::net_report::{NetReportConfig, Probe};
|
||||
|
||||
/// Options for running probes (in browsers).
|
||||
///
|
||||
/// Only HTTPS probes are supported in browsers.
|
||||
/// These are run by default.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Options {
|
||||
/// User-facing configuration.
|
||||
pub(crate) user_config: NetReportConfig,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
user_config: NetReportConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// Set the net report configuration.
|
||||
pub(crate) fn net_report_config(mut self, config: NetReportConfig) -> Self {
|
||||
self.user_config = config;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turn the options into set of valid protocols
|
||||
pub(crate) fn as_protocols(&self) -> BTreeSet<Probe> {
|
||||
let mut protocols = BTreeSet::new();
|
||||
if self.user_config.https_probes {
|
||||
protocols.insert(Probe::Https);
|
||||
}
|
||||
protocols
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+266
@@ -0,0 +1,266 @@
|
||||
//! The relay probes.
|
||||
//!
|
||||
//! All the probes try and establish the latency to the relay servers. Preferably the QAD
|
||||
//! probes work and we also learn about our public IP addresses and ports. But fallback
|
||||
//! probes for HTTPS exist as well.
|
||||
|
||||
use std::{collections::BTreeSet, fmt, sync::Arc};
|
||||
|
||||
use iroh_relay::{RelayConfig, RelayMap};
|
||||
use n0_future::time::Duration;
|
||||
|
||||
use crate::net_report::Report;
|
||||
|
||||
/// The retransmit interval used.
|
||||
const DEFAULT_INITIAL_RETRANSMIT: Duration = Duration::from_millis(100);
|
||||
|
||||
/// The delay before starting HTTPS probes.
|
||||
const HTTPS_OFFSET: Duration = Duration::from_millis(200);
|
||||
|
||||
/// The protocol used to time an endpoint's latency.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, derive_more::Display)]
|
||||
#[repr(u8)]
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
#[non_exhaustive]
|
||||
pub enum Probe {
|
||||
/// HTTPS
|
||||
Https,
|
||||
/// QUIC Address Discovery Ipv4
|
||||
#[cfg(not(wasm_browser))]
|
||||
QadIpv4,
|
||||
/// QUIC Address Discovery Ipv6
|
||||
#[cfg(not(wasm_browser))]
|
||||
QadIpv6,
|
||||
}
|
||||
|
||||
/// A probe set is a sequence of similar [`Probe`]s with delays between them.
|
||||
///
|
||||
/// The probes are to the same Relayer and of the same [`Probe`] but will have different
|
||||
/// delays. The delays are effectively retries, though they do not wait for the previous
|
||||
/// probe to be finished. The first successful probe will cancel all other probes in the
|
||||
/// set.
|
||||
///
|
||||
/// This is a lot of type-safety by convention. It would be so much nicer to have this
|
||||
/// compile-time checked but that introduces a giant mess of generics and traits and
|
||||
/// associated exploding types.
|
||||
///
|
||||
/// A [`ProbeSet`] implements [`IntoIterator`] similar to how [`Vec`] does.
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct ProbeSet {
|
||||
/// The [`Probe`] all the probes in this set have.
|
||||
proto: Probe,
|
||||
/// The data in the set.
|
||||
probes: Vec<(Duration, Arc<RelayConfig>)>,
|
||||
}
|
||||
|
||||
impl ProbeSet {
|
||||
fn new(proto: Probe) -> Self {
|
||||
Self {
|
||||
probes: Vec::new(),
|
||||
proto,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn proto(&self) -> Probe {
|
||||
self.proto
|
||||
}
|
||||
|
||||
fn push(&mut self, delay: Duration, endpoint: Arc<RelayConfig>) {
|
||||
self.probes.push((delay, endpoint));
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.probes.is_empty()
|
||||
}
|
||||
|
||||
pub(super) fn params(&self) -> impl Iterator<Item = &(Duration, Arc<RelayConfig>)> {
|
||||
self.probes.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// A probe plan.
|
||||
///
|
||||
/// A probe plan contains a number of [`ProbeSet`]s containing probes to be executed.
|
||||
/// Generally the first probe of of a set which completes aborts the remaining probes of a
|
||||
/// set. Sometimes a failing probe can also abort the remaining probes of a set.
|
||||
///
|
||||
/// The [`reportgen`] actor will also abort all the remaining [`ProbeSet`]s once it has
|
||||
/// sufficient information for a report.
|
||||
///
|
||||
/// [`reportgen`]: crate::net_report::reportgen
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct ProbePlan {
|
||||
set: BTreeSet<ProbeSet>,
|
||||
}
|
||||
|
||||
impl ProbePlan {
|
||||
/// Creates an initial probe plan
|
||||
pub(super) fn initial(relay_map: &RelayMap, protocols: &BTreeSet<Probe>) -> Self {
|
||||
let mut plan = Self::default();
|
||||
|
||||
for relay in relay_map.relays::<Vec<_>>() {
|
||||
let mut https_probes = ProbeSet::new(Probe::Https);
|
||||
|
||||
for attempt in 0u32..3 {
|
||||
let delay = HTTPS_OFFSET + DEFAULT_INITIAL_RETRANSMIT * attempt;
|
||||
https_probes.push(delay, relay.clone());
|
||||
}
|
||||
|
||||
plan.add_if_enabled(protocols, https_probes);
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
/// Creates a follow up probe plan using a previous net_report report in browsers.
|
||||
///
|
||||
/// This will only schedule HTTPS probes.
|
||||
pub(super) fn with_last_report(
|
||||
relay_map: &RelayMap,
|
||||
last_report: &Report,
|
||||
protocols: &BTreeSet<Probe>,
|
||||
) -> Self {
|
||||
if last_report.relay_latency.is_empty() {
|
||||
return Self::initial(relay_map, protocols);
|
||||
}
|
||||
|
||||
// TODO: is this good?
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the [`ProbeSet`]s in this plan.
|
||||
pub(super) fn iter(&self) -> impl Iterator<Item = &ProbeSet> {
|
||||
self.set.iter()
|
||||
}
|
||||
|
||||
/// Adds a [`ProbeSet`] if it contains probes and the protocol indicated in
|
||||
/// the [`ProbeSet] matches a protocol in our set of [`Probe`]s.
|
||||
fn add_if_enabled(&mut self, protocols: &BTreeSet<Probe>, set: ProbeSet) {
|
||||
if !set.is_empty() && protocols.contains(&set.proto) {
|
||||
self.set.insert(set);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ProbePlan {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
writeln!(f, "ProbePlan {{")?;
|
||||
for probe_set in self.set.iter() {
|
||||
writeln!(f, r#" ProbeSet("{}") {{"#, probe_set.proto)?;
|
||||
for (delay, endpoint) in probe_set.probes.iter() {
|
||||
writeln!(f, " {delay:?} to {endpoint},")?;
|
||||
}
|
||||
writeln!(f, " }}")?;
|
||||
}
|
||||
writeln!(f, "}}")
|
||||
}
|
||||
}
|
||||
|
||||
impl FromIterator<ProbeSet> for ProbePlan {
|
||||
fn from_iter<T: IntoIterator<Item = ProbeSet>>(iter: T) -> Self {
|
||||
Self {
|
||||
set: iter.into_iter().collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
use crate::net_report::test_utils;
|
||||
|
||||
/// Shorthand which declares a new ProbeSet.
|
||||
///
|
||||
/// `$kind`: The `Probe`.
|
||||
/// `$endpoint`: Expression which will be an `Arc<RelayConfig>`.
|
||||
/// `$delays`: A `Vec` of the delays for this probe.
|
||||
macro_rules! probeset {
|
||||
(proto: Probe::$kind:ident, relay: $endpoint:expr, delays: $delays:expr,) => {
|
||||
ProbeSet {
|
||||
proto: Probe::$kind,
|
||||
probes: $delays.iter().map(|delay| (*delay, $endpoint)).collect(),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn default_protocols() -> BTreeSet<Probe> {
|
||||
BTreeSet::from([Probe::QadIpv4, Probe::QadIpv6, Probe::Https])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_initial_probeplan() {
|
||||
let (_servers, relay_map) = test_utils::relay_map(2).await;
|
||||
let relay_1 = &relay_map.relays::<Vec<_>>()[0];
|
||||
let relay_2 = &relay_map.relays::<Vec<_>>()[1];
|
||||
let plan = ProbePlan::initial(&relay_map, &default_protocols());
|
||||
|
||||
let expected_plan: ProbePlan = [
|
||||
probeset! {
|
||||
proto: Probe::Https,
|
||||
relay: relay_1.clone(),
|
||||
delays: [
|
||||
Duration::from_millis(200),
|
||||
Duration::from_millis(300),
|
||||
Duration::from_millis(400)
|
||||
],
|
||||
},
|
||||
probeset! {
|
||||
proto: Probe::Https,
|
||||
relay: relay_2.clone(),
|
||||
delays: [
|
||||
Duration::from_millis(200),
|
||||
Duration::from_millis(300),
|
||||
Duration::from_millis(400)
|
||||
],
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
println!("expected:");
|
||||
println!("{expected_plan}");
|
||||
println!("actual:");
|
||||
println!("{plan}");
|
||||
// The readable error:
|
||||
assert_eq!(plan.to_string(), expected_plan.to_string());
|
||||
// Just in case there's a bug in the Display impl:
|
||||
assert_eq!(plan, expected_plan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_initial_probeplan_some_protocols() {
|
||||
let (_servers, relay_map) = test_utils::relay_map(2).await;
|
||||
let relay_1 = &relay_map.relays::<Vec<_>>()[0];
|
||||
let relay_2 = &relay_map.relays::<Vec<_>>()[1];
|
||||
let plan = ProbePlan::initial(&relay_map, &BTreeSet::from([Probe::Https]));
|
||||
|
||||
let expected_plan: ProbePlan = [
|
||||
probeset! {
|
||||
proto: Probe::Https,
|
||||
relay: relay_1.clone(),
|
||||
delays: [Duration::from_millis(200),
|
||||
Duration::from_millis(300),
|
||||
Duration::from_millis(400)],
|
||||
},
|
||||
probeset! {
|
||||
proto: Probe::Https,
|
||||
relay: relay_2.clone(),
|
||||
delays: [Duration::from_millis(200),
|
||||
Duration::from_millis(300),
|
||||
Duration::from_millis(400)],
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
println!("expected:");
|
||||
println!("{expected_plan}");
|
||||
println!("actual:");
|
||||
println!("{plan}");
|
||||
// The readable error:
|
||||
assert_eq!(plan.to_string(), expected_plan.to_string());
|
||||
// Just in case there's a bug in the Display impl:
|
||||
assert_eq!(plan, expected_plan);
|
||||
}
|
||||
}
|
||||
Vendored
+221
@@ -0,0 +1,221 @@
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fmt,
|
||||
net::{SocketAddr, SocketAddrV4, SocketAddrV6},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use iroh_base::RelayUrl;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing::{trace, warn};
|
||||
|
||||
use super::{ProbeReport, probes::Probe};
|
||||
|
||||
/// A net_report report.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
#[non_exhaustive]
|
||||
pub struct Report {
|
||||
/// A QAD IPv4 round trip completed.
|
||||
pub udp_v4: bool,
|
||||
/// A QAD IPv6 round trip completed.
|
||||
pub udp_v6: bool,
|
||||
/// Whether the reported public address differs when probing different servers (on IPv4).
|
||||
pub mapping_varies_by_dest_ipv4: Option<bool>,
|
||||
/// Whether the reported public address differs when probing different servers (on IPv6).
|
||||
pub mapping_varies_by_dest_ipv6: Option<bool>,
|
||||
/// The relay server with the lowest latency, if any.
|
||||
pub preferred_relay: Option<RelayUrl>,
|
||||
/// The measured latency to each relay, keyed by relay URL.
|
||||
pub relay_latency: RelayLatencies,
|
||||
/// The discovered global IPv4 address and port, if any.
|
||||
pub global_v4: Option<SocketAddrV4>,
|
||||
/// The discovered global IPv6 address and port, if any.
|
||||
pub global_v6: Option<SocketAddrV6>,
|
||||
/// CaptivePortal is set when we think there's a captive portal that is
|
||||
/// intercepting HTTP traffic.
|
||||
pub captive_portal: Option<bool>,
|
||||
}
|
||||
|
||||
impl fmt::Display for Report {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(&self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Report {
|
||||
/// Do we have any indication that UDP is working?
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
pub fn has_udp(&self) -> bool {
|
||||
self.udp_v4 || self.udp_v6
|
||||
}
|
||||
|
||||
/// Whether the reported public address differs when probing different servers.
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
pub fn mapping_varies_by_dest(&self) -> Option<bool> {
|
||||
match (
|
||||
self.mapping_varies_by_dest_ipv4,
|
||||
self.mapping_varies_by_dest_ipv6,
|
||||
) {
|
||||
(Some(v4), Some(v6)) => Some(v4 || v6),
|
||||
(None, Some(v6)) => Some(v6),
|
||||
(Some(v4), None) => Some(v4),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates a net_report [`Report`] with a new [`ProbeReport`].
|
||||
pub(super) fn update(&mut self, report: &ProbeReport) {
|
||||
match report {
|
||||
ProbeReport::Https(report) => {
|
||||
self.relay_latency
|
||||
.update_relay(report.relay.clone(), report.latency, Probe::Https);
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
ProbeReport::QadIpv4(report) => {
|
||||
self.relay_latency.update_relay(
|
||||
report.relay.clone(),
|
||||
report.latency,
|
||||
Probe::QadIpv4,
|
||||
);
|
||||
let SocketAddr::V4(ipp) = report.addr else {
|
||||
warn!("received IPv6 address from IPv4 QAD: {}", report.addr);
|
||||
return;
|
||||
};
|
||||
|
||||
self.udp_v4 = true;
|
||||
|
||||
if let Some(global) = self.global_v4 {
|
||||
if global == ipp {
|
||||
if self.mapping_varies_by_dest_ipv4.is_none() {
|
||||
self.mapping_varies_by_dest_ipv4 = Some(false);
|
||||
}
|
||||
} else {
|
||||
self.mapping_varies_by_dest_ipv4 = Some(true);
|
||||
warn!("IPv4 address detected by QAD varies by destination");
|
||||
}
|
||||
} else {
|
||||
self.global_v4 = Some(ipp);
|
||||
}
|
||||
trace!(?self.global_v4, ?self.mapping_varies_by_dest_ipv4, %ipp, "stored report");
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
ProbeReport::QadIpv6(report) => {
|
||||
self.relay_latency.update_relay(
|
||||
report.relay.clone(),
|
||||
report.latency,
|
||||
Probe::QadIpv6,
|
||||
);
|
||||
let SocketAddr::V6(ipp) = report.addr else {
|
||||
warn!("received IPv4 address from IPv6 QAD: {}", report.addr);
|
||||
return;
|
||||
};
|
||||
|
||||
self.udp_v6 = true;
|
||||
if let Some(global) = self.global_v6 {
|
||||
if global == ipp {
|
||||
if self.mapping_varies_by_dest_ipv6.is_none() {
|
||||
self.mapping_varies_by_dest_ipv6 = Some(false);
|
||||
}
|
||||
} else {
|
||||
self.mapping_varies_by_dest_ipv6 = Some(true);
|
||||
warn!("IPv6 address detected by QAD varies by destination");
|
||||
}
|
||||
} else {
|
||||
self.global_v6 = Some(ipp);
|
||||
}
|
||||
trace!(?self.global_v6, ?self.mapping_varies_by_dest_ipv6, %ipp, "stored report");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Latencies per relay endpoint.
|
||||
#[derive(Debug, Default, PartialEq, Eq, Clone, Serialize, Deserialize)]
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
pub struct RelayLatencies {
|
||||
#[cfg(not(wasm_browser))]
|
||||
ipv4: BTreeMap<RelayUrl, Duration>,
|
||||
#[cfg(not(wasm_browser))]
|
||||
ipv6: BTreeMap<RelayUrl, Duration>,
|
||||
https: BTreeMap<RelayUrl, Duration>,
|
||||
}
|
||||
|
||||
impl RelayLatencies {
|
||||
/// Updates a relay's latency, if it is faster than before.
|
||||
pub(super) fn update_relay(&mut self, url: RelayUrl, latency: Duration, probe: Probe) {
|
||||
let list = match probe {
|
||||
Probe::Https => &mut self.https,
|
||||
#[cfg(not(wasm_browser))]
|
||||
Probe::QadIpv4 => &mut self.ipv4,
|
||||
#[cfg(not(wasm_browser))]
|
||||
Probe::QadIpv6 => &mut self.ipv6,
|
||||
};
|
||||
let old_latency = list.entry(url).or_insert(latency);
|
||||
if latency < *old_latency {
|
||||
*old_latency = latency;
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges another [`RelayLatencies`] into this one.
|
||||
///
|
||||
/// For each relay the latency is updated using [`RelayLatencies::update_relay`].
|
||||
pub(super) fn merge(&mut self, other: &RelayLatencies) {
|
||||
for (url, latency) in other.https.iter() {
|
||||
self.update_relay(url.clone(), *latency, Probe::Https);
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
for (url, latency) in other.ipv4.iter() {
|
||||
self.update_relay(url.clone(), *latency, Probe::QadIpv4);
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
for (url, latency) in other.ipv6.iter() {
|
||||
self.update_relay(url.clone(), *latency, Probe::QadIpv6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator over all the relays and their latencies.
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
|
||||
self.https
|
||||
.iter()
|
||||
.map(|(url, l)| (Probe::Https, url, *l))
|
||||
.chain(self.ipv4.iter().map(|(url, l)| (Probe::QadIpv4, url, *l)))
|
||||
.chain(self.ipv6.iter().map(|(url, l)| (Probe::QadIpv6, url, *l)))
|
||||
}
|
||||
|
||||
/// Returns an iterator over all the relays and their latencies.
|
||||
#[cfg(wasm_browser)]
|
||||
#[cfg_attr(not(feature = "unstable-net-report"), allow(unreachable_pub))]
|
||||
pub fn iter(&self) -> impl Iterator<Item = (Probe, &'_ RelayUrl, Duration)> + '_ {
|
||||
self.https.iter().map(|(k, v)| (Probe::Https, k, *v))
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.https.is_empty() && self.ipv4.is_empty() && self.ipv6.is_empty()
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.https.is_empty()
|
||||
}
|
||||
|
||||
/// Returns the lowest latency across records.
|
||||
pub(super) fn get(&self, url: &RelayUrl) -> Option<Duration> {
|
||||
let mut list = Vec::with_capacity(3);
|
||||
if let Some(val) = self.https.get(url) {
|
||||
list.push(*val);
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
if let Some(val) = self.ipv4.get(url) {
|
||||
list.push(*val);
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
if let Some(val) = self.ipv6.get(url) {
|
||||
list.push(*val);
|
||||
}
|
||||
list.into_iter().min()
|
||||
}
|
||||
}
|
||||
+997
@@ -0,0 +1,997 @@
|
||||
//! The reportgen actor is responsible for generating a single net_report report.
|
||||
//!
|
||||
//! It is implemented as an actor with [`Client`] as handle.
|
||||
//!
|
||||
//! The actor starts generating the report as soon as it is created, it does not receive any
|
||||
//! messages from the client. It follows roughly these steps:
|
||||
//!
|
||||
//! - Determines host IPv6 support.
|
||||
//! - Creates portmapper future.
|
||||
//! - Creates captive portal detection future.
|
||||
//! - Creates Probe Set futures.
|
||||
//! - These send messages to the reportgen actor.
|
||||
//! - Loops driving the futures and handling actor messages:
|
||||
//! - Disables futures as they are completed or aborted.
|
||||
//! - Stop if there are no outstanding tasks/futures, or on timeout.
|
||||
//! - Sends the completed report to the net_report actor.
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
use std::net::{SocketAddrV4, SocketAddrV6};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use http::StatusCode;
|
||||
use iroh_base::RelayUrl;
|
||||
#[cfg(not(wasm_browser))]
|
||||
use iroh_dns::dns::{DnsError, DnsResolver, StaggeredError};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use iroh_relay::quic::QuicClient;
|
||||
use iroh_relay::{
|
||||
RelayConfig, RelayMap, defaults::DEFAULT_RELAY_QUIC_PORT, http::RELAY_PROBE_PATH,
|
||||
};
|
||||
use n0_error::{e, stack_error};
|
||||
#[cfg(wasm_browser)]
|
||||
use n0_future::future::Pending;
|
||||
use n0_future::{
|
||||
StreamExt as _,
|
||||
task::{self, AbortOnDropHandle, JoinSet},
|
||||
time::{self, Duration, Instant},
|
||||
};
|
||||
use rand::seq::IteratorRandom;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{Instrument, debug, error, info_span, trace, warn};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use url::Url;
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
use super::defaults::timeouts::DNS_TIMEOUT;
|
||||
use super::{
|
||||
Report,
|
||||
probes::{Probe, ProbePlan},
|
||||
};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use crate::address_lookup::DNS_STAGGERING_MS;
|
||||
use crate::{
|
||||
net_report::defaults::timeouts::{
|
||||
CAPTIVE_PORTAL_DELAY, CAPTIVE_PORTAL_TIMEOUT, OVERALL_REPORT_TIMEOUT, PROBES_TIMEOUT,
|
||||
},
|
||||
util::reqwest_client_builder,
|
||||
};
|
||||
|
||||
/// Holds the state for a single report generation.
|
||||
///
|
||||
/// Dropping this will cancel the actor and stop the report generation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Client {
|
||||
_drop_guard: AbortOnDropHandle<()>,
|
||||
}
|
||||
|
||||
/// Some details required from the interface state of the device.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct IfStateDetails {
|
||||
/// Do we have IPv4 capbilities
|
||||
pub(crate) have_v4: bool,
|
||||
/// Do we have IPv6 capbilities
|
||||
pub(crate) have_v6: bool,
|
||||
}
|
||||
|
||||
impl IfStateDetails {
|
||||
#[cfg(test)]
|
||||
pub(super) fn fake() -> Self {
|
||||
IfStateDetails {
|
||||
have_v4: true,
|
||||
have_v6: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<netwatch::netmon::State> for IfStateDetails {
|
||||
fn from(value: netwatch::netmon::State) -> Self {
|
||||
IfStateDetails {
|
||||
have_v4: value.have_v4,
|
||||
have_v6: value.have_v6,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Any state that depends on sockets being available in the current environment.
|
||||
///
|
||||
/// Factored out so it can be disabled easily in browsers.
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct SocketState {
|
||||
/// QUIC client to do QUIC address Discovery
|
||||
pub(super) quic_client: Option<QuicClient>,
|
||||
/// The DNS resolver to use for probes that need to resolve DNS records.
|
||||
pub(super) dns_resolver: DnsResolver,
|
||||
/// The proxy to send the HTTP(S) based probes through, if any.
|
||||
pub(super) proxy_url: Option<Url>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
/// Creates a new actor generating a single report.
|
||||
///
|
||||
/// The actor starts running immediately and only generates a single report, after which
|
||||
/// it shuts down. Dropping this handle will abort the actor.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn new(
|
||||
last_report: Option<Report>,
|
||||
relay_map: RelayMap,
|
||||
protocols: BTreeSet<Probe>,
|
||||
captive_portal_check: bool,
|
||||
if_state: IfStateDetails,
|
||||
shutdown_token: CancellationToken,
|
||||
#[cfg(not(wasm_browser))] socket_state: SocketState,
|
||||
#[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
|
||||
) -> (Self, mpsc::Receiver<ProbeFinished>) {
|
||||
let (msg_tx, msg_rx) = mpsc::channel(32);
|
||||
let actor = Actor {
|
||||
msg_tx,
|
||||
last_report,
|
||||
relay_map,
|
||||
protocols,
|
||||
captive_portal_check,
|
||||
#[cfg(not(wasm_browser))]
|
||||
socket_state,
|
||||
#[cfg(not(wasm_browser))]
|
||||
tls_config,
|
||||
if_state,
|
||||
};
|
||||
let task = task::spawn(
|
||||
actor
|
||||
.run(shutdown_token)
|
||||
.instrument(info_span!("reportgen-actor")),
|
||||
);
|
||||
(
|
||||
Self {
|
||||
_drop_guard: AbortOnDropHandle::new(task),
|
||||
},
|
||||
msg_rx,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The reportstate actor.
|
||||
///
|
||||
/// This actor starts, generates a single report and exits.
|
||||
#[derive(Debug)]
|
||||
struct Actor {
|
||||
msg_tx: mpsc::Sender<ProbeFinished>,
|
||||
|
||||
// Provided state
|
||||
/// The previous report, if it exists.
|
||||
last_report: Option<Report>,
|
||||
/// The relay configuration.
|
||||
relay_map: RelayMap,
|
||||
|
||||
// Internal state.
|
||||
/// Protocols we should attempt to create probes for, if we have the correct
|
||||
/// configuration for that protocol.
|
||||
protocols: BTreeSet<Probe>,
|
||||
|
||||
/// Whether to check for captive portals.
|
||||
captive_portal_check: bool,
|
||||
|
||||
/// Any socket-related state that doesn't exist/work in browsers
|
||||
#[cfg(not(wasm_browser))]
|
||||
socket_state: SocketState,
|
||||
#[cfg(not(wasm_browser))]
|
||||
tls_config: rustls::ClientConfig,
|
||||
if_state: IfStateDetails,
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub(super) enum ProbesError {
|
||||
#[error("Probe failed")]
|
||||
ProbeFailure { source: ProbeError },
|
||||
#[error("All probes failed")]
|
||||
AllProbesFailed,
|
||||
#[error("Probe cancelled")]
|
||||
Cancelled,
|
||||
#[error("Probe timed out")]
|
||||
Timeout,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum ProbeFinished {
|
||||
Regular(Result<ProbeReport, ProbesError>),
|
||||
#[cfg(not(wasm_browser))]
|
||||
CaptivePortal(Option<bool>),
|
||||
}
|
||||
|
||||
impl Actor {
|
||||
async fn run(self, shutdown_token: CancellationToken) {
|
||||
shutdown_token
|
||||
.run_until_cancelled_owned(async {
|
||||
match time::timeout(OVERALL_REPORT_TIMEOUT, self.run_inner()).await {
|
||||
Ok(()) => trace!("reportgen actor finished"),
|
||||
Err(time::Elapsed { .. }) => {
|
||||
warn!("reportgen timed out");
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Runs the main reportgen actor logic.
|
||||
///
|
||||
/// This actor runs by:
|
||||
///
|
||||
/// - Creates a captive portal future.
|
||||
/// - Creates ProbeSet futures in a group of futures.
|
||||
/// - Runs a main loop:
|
||||
/// - Drives all the above futures.
|
||||
/// - Receives actor messages (sent by those futures).
|
||||
/// - Updates the report, cancels unneeded futures.
|
||||
/// - Sends the report to the net_report actor.
|
||||
async fn run_inner(self) {
|
||||
trace!("reportgen actor starting");
|
||||
|
||||
let mut probes = JoinSet::default();
|
||||
|
||||
let _probes_token = self.spawn_probes_task(self.if_state.clone(), &mut probes);
|
||||
let mut num_probes = probes.len();
|
||||
|
||||
let captive_token = self.prepare_captive_portal_task(&mut probes);
|
||||
|
||||
// any reports of working UDP/QUIC?
|
||||
let mut have_udp = false;
|
||||
|
||||
// Check for probes finishing.
|
||||
while let Some(probe_result) = probes.join_next().await {
|
||||
trace!(?probe_result, num_probes, "processing finished probe");
|
||||
match probe_result {
|
||||
Ok(report) => {
|
||||
#[cfg_attr(wasm_browser, allow(irrefutable_let_patterns))]
|
||||
if let ProbeFinished::Regular(report) = &report {
|
||||
have_udp |= report.as_ref().map(|r| r.is_udp()).unwrap_or_default();
|
||||
num_probes -= 1;
|
||||
|
||||
// If all probes are done & we have_udp cancel captive
|
||||
if num_probes == 0 {
|
||||
trace!("all regular probes done");
|
||||
debug_assert!(probes.len() <= 1, "{} probes", probes.len());
|
||||
|
||||
if have_udp {
|
||||
captive_token.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.msg_tx.send(report).await.ok();
|
||||
}
|
||||
Err(e) => {
|
||||
if e.is_panic() {
|
||||
error!("Task panicked {:?}", e);
|
||||
break;
|
||||
}
|
||||
warn!("probes task join error: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the future which will perform the captive portal check.
|
||||
fn prepare_captive_portal_task(&self, tasks: &mut JoinSet<ProbeFinished>) -> CancellationToken {
|
||||
let token = CancellationToken::new();
|
||||
|
||||
// If we're doing a full probe, also check for a captive portal. We
|
||||
// delay by a bit to wait for UDP QAD to finish, to avoid the probe if
|
||||
// it's unnecessary.
|
||||
#[cfg(not(wasm_browser))]
|
||||
if self.captive_portal_check && self.last_report.is_none() {
|
||||
// Even if we're doing a non-incremental update, we may want to try our
|
||||
// preferred relay for captive portal detection.
|
||||
let preferred_relay = self
|
||||
.last_report
|
||||
.as_ref()
|
||||
.and_then(|l| l.preferred_relay.clone());
|
||||
|
||||
let dns_resolver = self.socket_state.dns_resolver.clone();
|
||||
let proxy_url = self.socket_state.proxy_url.clone();
|
||||
let dm = self.relay_map.clone();
|
||||
let token = token.clone();
|
||||
#[cfg(not(wasm_browser))]
|
||||
let tls_config = self.tls_config.clone();
|
||||
tasks.spawn(
|
||||
async move {
|
||||
let res = token
|
||||
.run_until_cancelled_owned(async move {
|
||||
time::sleep(CAPTIVE_PORTAL_DELAY).await;
|
||||
trace!("check started after {CAPTIVE_PORTAL_DELAY:?}");
|
||||
time::timeout(
|
||||
CAPTIVE_PORTAL_TIMEOUT,
|
||||
check_captive_portal(
|
||||
&dns_resolver,
|
||||
&dm,
|
||||
preferred_relay,
|
||||
tls_config,
|
||||
proxy_url.as_ref(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
let res = match res {
|
||||
Some(Ok(Ok(found))) => Some(found),
|
||||
Some(Ok(Err(err))) => {
|
||||
match err {
|
||||
CaptivePortalError::CreateReqwestClient { source, .. }
|
||||
| CaptivePortalError::HttpRequest { source, .. }
|
||||
if source.is_connect() =>
|
||||
{
|
||||
debug!("check_captive_portal failed: {source:#}");
|
||||
}
|
||||
err => warn!("check_captive_portal error: {err:#}"),
|
||||
}
|
||||
None
|
||||
}
|
||||
Some(Err(time::Elapsed { .. })) => {
|
||||
warn!("probe timed out");
|
||||
None
|
||||
}
|
||||
None => {
|
||||
trace!("probe cancelled");
|
||||
None
|
||||
}
|
||||
};
|
||||
ProbeFinished::CaptivePortal(res)
|
||||
}
|
||||
.instrument(info_span!("captive-portal")),
|
||||
);
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
/// Prepares the future which will run all the probes as per generated ProbePlan.
|
||||
///
|
||||
/// Probes operate like the following:
|
||||
///
|
||||
/// - A future is created for each probe in all probe sets.
|
||||
/// - All probes in a set are grouped in [`JoinSet`].
|
||||
/// - All those probe sets are grouped in one overall [`JoinSet`].
|
||||
/// - This future is polled by the main actor loop to make progress.
|
||||
/// - Once a probe future is polled:
|
||||
/// - Many probes start with a delay, they sleep during this time.
|
||||
/// - When a probe starts it first asks the reportgen [`Actor`] if it is still useful
|
||||
/// to run. If not it aborts the entire probe set.
|
||||
/// - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor.
|
||||
/// - Probes get aborted in several ways:
|
||||
/// - A running it can fail and abort the entire probe set if it deems the
|
||||
/// failure permanent. Probes in a probe set are essentially retries.
|
||||
/// - Once there are [`ProbeReport`]s from enough relays, all remaining probes are
|
||||
/// aborted. That is, the main actor loop stops polling them.
|
||||
fn spawn_probes_task(
|
||||
&self,
|
||||
if_state: IfStateDetails,
|
||||
probes: &mut JoinSet<ProbeFinished>,
|
||||
) -> CancellationToken {
|
||||
trace!(?if_state, "local interface details");
|
||||
let plan = match self.last_report {
|
||||
Some(ref report) => {
|
||||
ProbePlan::with_last_report(&self.relay_map, report, &self.protocols)
|
||||
}
|
||||
None => ProbePlan::initial(&self.relay_map, &self.protocols),
|
||||
};
|
||||
trace!(%plan, "probe plan");
|
||||
|
||||
let token = CancellationToken::new();
|
||||
|
||||
for probe_set in plan.iter() {
|
||||
let set_token = token.child_token();
|
||||
let proto = probe_set.proto();
|
||||
for (delay, relay) in probe_set.params() {
|
||||
let probe_token = set_token.child_token();
|
||||
|
||||
let fut = probe_token.run_until_cancelled_owned(time::timeout(
|
||||
PROBES_TIMEOUT,
|
||||
proto.run(
|
||||
*delay,
|
||||
relay.clone(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
self.socket_state.clone(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
self.tls_config.clone(),
|
||||
),
|
||||
));
|
||||
probes.spawn(
|
||||
async move {
|
||||
let res = fut.await;
|
||||
let res = match res {
|
||||
Some(Ok(Ok(report))) => Ok(report),
|
||||
Some(Ok(Err(err))) => {
|
||||
warn!("probe failed: {:#}", err);
|
||||
Err(e!(ProbesError::ProbeFailure, err))
|
||||
}
|
||||
Some(Err(time::Elapsed { .. })) => Err(e!(ProbesError::Timeout)),
|
||||
None => Err(e!(ProbesError::Cancelled)),
|
||||
};
|
||||
ProbeFinished::Regular(res)
|
||||
}
|
||||
.instrument(info_span!(
|
||||
"run-probe",
|
||||
?proto,
|
||||
?delay,
|
||||
relay=%relay.url,
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
token
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of running a probe.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) enum ProbeReport {
|
||||
#[cfg(not(wasm_browser))]
|
||||
QadIpv4(QadProbeReport),
|
||||
#[cfg(not(wasm_browser))]
|
||||
QadIpv6(QadProbeReport),
|
||||
Https(HttpsProbeReport),
|
||||
}
|
||||
|
||||
impl ProbeReport {
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(super) fn is_udp(&self) -> bool {
|
||||
matches!(self, Self::QadIpv4(_) | Self::QadIpv6(_))
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
pub(super) fn is_udp(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct QadProbeReport {
|
||||
/// The relay that was probed
|
||||
pub(super) relay: RelayUrl,
|
||||
/// The latency to the relay.
|
||||
pub(super) latency: Duration,
|
||||
/// The discovered public address.
|
||||
pub(super) addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct HttpsProbeReport {
|
||||
/// The relay that was probed
|
||||
pub(super) relay: RelayUrl,
|
||||
/// The latency to the relay.
|
||||
pub(super) latency: Duration,
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub(super) enum ProbeError {
|
||||
#[error("Client is gone")]
|
||||
ClientGone,
|
||||
#[error("Probe is no longer useful")]
|
||||
NotUseful,
|
||||
#[error("Failed to run HTTPS probe")]
|
||||
Https { source: MeasureHttpsLatencyError },
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub(super) enum QuicError {
|
||||
#[error("No relay available")]
|
||||
NoRelay,
|
||||
#[error("URL must have 'host' to use QUIC address discovery probes")]
|
||||
InvalidUrl,
|
||||
}
|
||||
|
||||
/// Pieces needed to do QUIC address discovery.
|
||||
#[derive(derive_more::Debug, Clone)]
|
||||
pub(crate) struct QuicConfig {
|
||||
/// A QUIC Endpoint
|
||||
#[debug("noq::Endpoint")]
|
||||
pub(crate) ep: noq::Endpoint,
|
||||
/// A client config.
|
||||
pub(crate) client_config: rustls::ClientConfig,
|
||||
/// Enable ipv4 QUIC address discovery probes
|
||||
pub(crate) ipv4: bool,
|
||||
/// Enable ipv6 QUIC address discovery probes
|
||||
pub(crate) ipv6: bool,
|
||||
}
|
||||
|
||||
impl Probe {
|
||||
/// Executes this particular [`Probe`], including using a delayed start if needed.
|
||||
async fn run(
|
||||
self,
|
||||
delay: Duration,
|
||||
relay: Arc<RelayConfig>,
|
||||
#[cfg(not(wasm_browser))] socket_state: SocketState,
|
||||
#[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
|
||||
) -> Result<ProbeReport, ProbeError> {
|
||||
if !delay.is_zero() {
|
||||
trace!("delaying probe");
|
||||
time::sleep(delay).await;
|
||||
}
|
||||
trace!("starting probe");
|
||||
|
||||
let report = match self {
|
||||
Probe::Https => {
|
||||
match run_https_probe(
|
||||
#[cfg(not(wasm_browser))]
|
||||
&socket_state.dns_resolver,
|
||||
relay.url.clone(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
tls_config,
|
||||
#[cfg(not(wasm_browser))]
|
||||
socket_state.proxy_url.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(report) => Ok(ProbeReport::Https(report)),
|
||||
Err(err) => Err(e!(ProbeError::Https, err)),
|
||||
}
|
||||
}
|
||||
#[cfg(not(wasm_browser))]
|
||||
Probe::QadIpv4 | Probe::QadIpv6 => unreachable!("must not be used"),
|
||||
};
|
||||
debug!(?report, "probe finished");
|
||||
report
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
enum CaptivePortalError {
|
||||
#[error(transparent)]
|
||||
DnsLookup {
|
||||
#[error(from)]
|
||||
source: StaggeredError<DnsError>,
|
||||
},
|
||||
#[error("Creating HTTP client failed")]
|
||||
CreateReqwestClient {
|
||||
#[error(std_err)]
|
||||
source: reqwest::Error,
|
||||
},
|
||||
#[error("HTTP request failed")]
|
||||
HttpRequest {
|
||||
#[error(std_err)]
|
||||
source: reqwest::Error,
|
||||
},
|
||||
}
|
||||
|
||||
/// Reports whether or not we think the system is behind a
|
||||
/// captive portal, detected by making a request to a URL that we know should
|
||||
/// return a "204 No Content" response and checking if that's what we get.
|
||||
///
|
||||
/// The boolean return is whether we think we have a captive portal.
|
||||
#[cfg(not(wasm_browser))]
|
||||
async fn check_captive_portal(
|
||||
dns_resolver: &DnsResolver,
|
||||
dm: &RelayMap,
|
||||
preferred_relay: Option<RelayUrl>,
|
||||
tls_config: rustls::ClientConfig,
|
||||
proxy_url: Option<&Url>,
|
||||
) -> Result<bool, CaptivePortalError> {
|
||||
// If we have a preferred relay and we can use it for non-QAD requests, try that;
|
||||
// otherwise, pick a random one suitable for non-STUN requests.
|
||||
|
||||
use crate::util::reqwest_client_builder;
|
||||
|
||||
let preferred_relay = preferred_relay.and_then(|url| dm.get(&url).map(|_| url));
|
||||
|
||||
let url = match preferred_relay {
|
||||
Some(url) => url,
|
||||
None => {
|
||||
let urls: Vec<_> = dm.urls();
|
||||
if urls.is_empty() {
|
||||
trace!("No suitable relay for captive portal check");
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let i = (0..urls.len()).choose(&mut rand::rng()).unwrap_or_default();
|
||||
urls[i].clone()
|
||||
}
|
||||
};
|
||||
|
||||
let mut builder = reqwest_client_builder(tls_config, dns_resolver.clone())
|
||||
.redirect(reqwest::redirect::Policy::none());
|
||||
if let Some(proxy_url) = proxy_url {
|
||||
let proxy = reqwest::Proxy::all(proxy_url.clone())
|
||||
.map_err(|err| e!(CaptivePortalError::CreateReqwestClient, err))?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
let client = builder
|
||||
.build()
|
||||
.map_err(|err| e!(CaptivePortalError::CreateReqwestClient, err))?;
|
||||
|
||||
// Note: the set of valid characters in a challenge and the total
|
||||
// length is limited; see is_challenge_char in bin/iroh-relay for more
|
||||
// details.
|
||||
|
||||
let host_name = url.host_str().unwrap_or_default();
|
||||
let challenge = format!("ts_{host_name}");
|
||||
let portal_url = format!("http://{host_name}/generate_204");
|
||||
let res = client
|
||||
.request(reqwest::Method::GET, portal_url)
|
||||
.header("X-Iroh-Challenge", &challenge)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| e!(CaptivePortalError::HttpRequest, err))?;
|
||||
|
||||
let expected_response = format!("response {challenge}");
|
||||
let is_valid_response = res
|
||||
.headers()
|
||||
.get("X-Iroh-Response")
|
||||
.map(|s| s.to_str().unwrap_or_default())
|
||||
== Some(&expected_response);
|
||||
|
||||
trace!(
|
||||
"check_captive_portal url={} status_code={} valid_response={}",
|
||||
res.url(),
|
||||
res.status(),
|
||||
is_valid_response,
|
||||
);
|
||||
let has_captive = res.status() != 204 || !is_valid_response;
|
||||
|
||||
Ok(has_captive)
|
||||
}
|
||||
|
||||
/// Returns the proper port based on the protocol of the probe.
|
||||
#[cfg(not(wasm_browser))]
|
||||
fn get_quic_port(relay: &RelayConfig) -> Option<u16> {
|
||||
if let Some(ref quic) = relay.quic {
|
||||
if quic.port == 0 {
|
||||
Some(DEFAULT_RELAY_QUIC_PORT)
|
||||
} else {
|
||||
Some(quic.port)
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub(super) enum GetRelayAddrError {
|
||||
#[error("No valid hostname in the relay URL")]
|
||||
InvalidHostname,
|
||||
#[error("No suitable relay address found for {url} ({addr_type})")]
|
||||
NoAddrFound {
|
||||
url: RelayUrl,
|
||||
addr_type: &'static str,
|
||||
},
|
||||
#[error("DNS lookup failed")]
|
||||
DnsLookup { source: StaggeredError<DnsError> },
|
||||
#[error("Relay is not suitable")]
|
||||
UnsupportedRelay,
|
||||
#[error("HTTPS probes are not implemented")]
|
||||
UnsupportedHttps,
|
||||
#[error("No port available for this protocol")]
|
||||
MissingPort,
|
||||
}
|
||||
|
||||
/// Returns the IP address to use to communicate to this relay for quic.
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(super) async fn get_relay_addr_ipv4(
|
||||
dns_resolver: &DnsResolver,
|
||||
relay: &RelayConfig,
|
||||
) -> Result<SocketAddrV4, GetRelayAddrError> {
|
||||
let port = get_quic_port(relay).ok_or_else(|| e!(GetRelayAddrError::MissingPort))?;
|
||||
relay_lookup_ipv4_staggered(dns_resolver, relay, port).await
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(super) async fn get_relay_addr_ipv6(
|
||||
dns_resolver: &DnsResolver,
|
||||
relay: &RelayConfig,
|
||||
) -> Result<SocketAddrV6, GetRelayAddrError> {
|
||||
let port = get_quic_port(relay).ok_or_else(|| e!(GetRelayAddrError::MissingPort))?;
|
||||
relay_lookup_ipv6_staggered(dns_resolver, relay, port).await
|
||||
}
|
||||
|
||||
/// Do a staggared ipv4 DNS lookup based on [`RelayConfig`]
|
||||
///
|
||||
/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`]
|
||||
#[cfg(not(wasm_browser))]
|
||||
async fn relay_lookup_ipv4_staggered(
|
||||
dns_resolver: &DnsResolver,
|
||||
relay: &RelayConfig,
|
||||
port: u16,
|
||||
) -> Result<SocketAddrV4, GetRelayAddrError> {
|
||||
match relay.url.host() {
|
||||
Some(url::Host::Domain(hostname)) => {
|
||||
trace!(%hostname, "Performing DNS A lookup for relay addr");
|
||||
match dns_resolver
|
||||
.lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS)
|
||||
.await
|
||||
{
|
||||
Ok(mut addrs) => addrs
|
||||
.next()
|
||||
.map(|ip| ip.to_canonical())
|
||||
.map(|addr| match addr {
|
||||
IpAddr::V4(ip) => SocketAddrV4::new(ip, port),
|
||||
IpAddr::V6(_) => unreachable!("bad DNS lookup: {:?}", addr),
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
e!(GetRelayAddrError::NoAddrFound {
|
||||
url: relay.url.clone(),
|
||||
addr_type: "A",
|
||||
})
|
||||
}),
|
||||
Err(err) => Err(e!(GetRelayAddrError::DnsLookup, err)),
|
||||
}
|
||||
}
|
||||
Some(url::Host::Ipv4(addr)) => Ok(SocketAddrV4::new(addr, port)),
|
||||
Some(url::Host::Ipv6(_addr)) => Err(e!(GetRelayAddrError::NoAddrFound {
|
||||
url: relay.url.clone(),
|
||||
addr_type: "A",
|
||||
})),
|
||||
None => Err(e!(GetRelayAddrError::InvalidHostname)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Do a staggared ipv6 DNS lookup based on [`RelayConfig`]
|
||||
///
|
||||
/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`]
|
||||
#[cfg(not(wasm_browser))]
|
||||
async fn relay_lookup_ipv6_staggered(
|
||||
dns_resolver: &DnsResolver,
|
||||
relay: &RelayConfig,
|
||||
port: u16,
|
||||
) -> Result<SocketAddrV6, GetRelayAddrError> {
|
||||
match relay.url.host() {
|
||||
Some(url::Host::Domain(hostname)) => {
|
||||
trace!(%hostname, "Performing DNS AAAA lookup for relay addr");
|
||||
match dns_resolver
|
||||
.lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS)
|
||||
.await
|
||||
{
|
||||
Ok(mut addrs) => addrs
|
||||
.next()
|
||||
.map(|addr| match addr {
|
||||
IpAddr::V4(_) => unreachable!("bad DNS lookup: {:?}", addr),
|
||||
IpAddr::V6(ip) => SocketAddrV6::new(ip, port, 0, 0),
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
e!(GetRelayAddrError::NoAddrFound {
|
||||
url: relay.url.clone(),
|
||||
addr_type: "AAAA",
|
||||
})
|
||||
}),
|
||||
Err(err) => Err(e!(GetRelayAddrError::DnsLookup, err)),
|
||||
}
|
||||
}
|
||||
Some(url::Host::Ipv4(_addr)) => Err(e!(GetRelayAddrError::NoAddrFound {
|
||||
url: relay.url.clone(),
|
||||
addr_type: "AAAA",
|
||||
})),
|
||||
Some(url::Host::Ipv6(addr)) => Ok(SocketAddrV6::new(addr, port, 0, 0)),
|
||||
None => Err(e!(GetRelayAddrError::InvalidHostname)),
|
||||
}
|
||||
}
|
||||
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[non_exhaustive]
|
||||
pub(super) enum MeasureHttpsLatencyError {
|
||||
#[error(transparent)]
|
||||
InvalidUrl {
|
||||
#[error(std_err, from)]
|
||||
source: url::ParseError,
|
||||
},
|
||||
#[cfg(not(wasm_browser))]
|
||||
#[error(transparent)]
|
||||
DnsLookup {
|
||||
#[error(from)]
|
||||
source: StaggeredError<DnsError>,
|
||||
},
|
||||
#[error("Creating HTTP client failed")]
|
||||
CreateReqwestClient {
|
||||
#[error(std_err)]
|
||||
source: reqwest::Error,
|
||||
},
|
||||
#[error("HTTP request failed")]
|
||||
HttpRequest {
|
||||
#[error(std_err)]
|
||||
source: reqwest::Error,
|
||||
},
|
||||
#[error("Error response from server {status}: {:?}", status.canonical_reason())]
|
||||
InvalidResponse { status: StatusCode },
|
||||
}
|
||||
|
||||
/// Executes an HTTPS probe.
|
||||
///
|
||||
/// If `certs` is provided they will be added to the trusted root certificates, allowing the
|
||||
/// use of self-signed certificates for servers. Currently this is used for testing.
|
||||
#[allow(clippy::unused_async)]
|
||||
async fn run_https_probe(
|
||||
#[cfg(not(wasm_browser))] dns_resolver: &DnsResolver,
|
||||
relay: RelayUrl,
|
||||
#[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
|
||||
#[cfg(not(wasm_browser))] proxy_url: Option<&Url>,
|
||||
) -> Result<HttpsProbeReport, MeasureHttpsLatencyError> {
|
||||
trace!("HTTPS probe start");
|
||||
let url = relay.join(RELAY_PROBE_PATH)?;
|
||||
|
||||
// This should also use same connection establishment as relay client itself, which
|
||||
// needs to be more configurable so users can do more crazy things:
|
||||
// https://github.com/n0-computer/iroh/issues/2901
|
||||
#[cfg(not(wasm_browser))]
|
||||
let mut builder = reqwest_client_builder(tls_config, dns_resolver.clone())
|
||||
.redirect(reqwest::redirect::Policy::none());
|
||||
#[cfg(wasm_browser)]
|
||||
let builder = reqwest_client_builder();
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
if let Some(proxy_url) = proxy_url {
|
||||
let proxy = reqwest::Proxy::all(proxy_url.clone())
|
||||
.map_err(|err| e!(MeasureHttpsLatencyError::CreateReqwestClient, err))?;
|
||||
builder = builder.proxy(proxy);
|
||||
}
|
||||
|
||||
let client = builder
|
||||
.build()
|
||||
.map_err(|err| e!(MeasureHttpsLatencyError::CreateReqwestClient, err))?;
|
||||
|
||||
let start = Instant::now();
|
||||
let response = client
|
||||
.request(reqwest::Method::GET, url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| e!(MeasureHttpsLatencyError::HttpRequest, err))?;
|
||||
let latency = start.elapsed();
|
||||
if response.status().is_success() {
|
||||
// Drain the response body to be nice to the server, up to a limit.
|
||||
const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB
|
||||
let mut body_size = 0;
|
||||
let mut stream = response.bytes_stream();
|
||||
// ignore failing frames
|
||||
while let Some(Ok(chunk)) = stream.next().await {
|
||||
body_size += chunk.len();
|
||||
if body_size >= MAX_BODY_SIZE {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(HttpsProbeReport { relay, latency })
|
||||
} else {
|
||||
Err(e!(MeasureHttpsLatencyError::InvalidResponse {
|
||||
status: response.status()
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use iroh_dns::dns::DnsResolver;
|
||||
use iroh_relay::tls::{CaTlsConfig, default_provider};
|
||||
use n0_error::{Result, StdResultExt};
|
||||
use n0_tracing_test::traced_test;
|
||||
use tokio::{io::AsyncReadExt, sync::oneshot};
|
||||
|
||||
use super::{super::test_utils, *};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_measure_https_latency() -> Result {
|
||||
let (_server, relay) = test_utils::relay().await;
|
||||
let dns_resolver = DnsResolver::new();
|
||||
tracing::info!(relay_url = ?relay.url , "RELAY_URL");
|
||||
let report = run_https_probe(
|
||||
&dns_resolver,
|
||||
relay.url,
|
||||
CaTlsConfig::insecure_skip_verify()
|
||||
.client_config(default_provider())
|
||||
.expect("infallible"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert!(report.latency > Duration::ZERO);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Spawns a fake HTTP proxy which captures the request line of the first connection
|
||||
/// it receives and then hangs up.
|
||||
///
|
||||
/// Returns the URL to configure as proxy and a receiver for the captured request line.
|
||||
async fn capturing_proxy() -> Result<(Url, oneshot::Receiver<String>)> {
|
||||
let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
.await
|
||||
.anyerr()?;
|
||||
let url: Url = format!("http://{}", listener.local_addr().anyerr()?)
|
||||
.parse()
|
||||
.anyerr()?;
|
||||
let (tx, rx) = oneshot::channel();
|
||||
task::spawn(async move {
|
||||
let Ok((mut stream, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let mut line = Vec::new();
|
||||
let mut byte = [0u8; 1];
|
||||
while let Ok(1) = stream.read(&mut byte).await {
|
||||
if byte[0] == b'\n' {
|
||||
break;
|
||||
}
|
||||
line.push(byte[0]);
|
||||
}
|
||||
tx.send(String::from_utf8_lossy(&line).trim().to_string())
|
||||
.ok();
|
||||
});
|
||||
Ok((url, rx))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_measure_https_latency_via_proxy() -> Result {
|
||||
let (_server, relay) = test_utils::relay().await;
|
||||
let dns_resolver = DnsResolver::new();
|
||||
let (proxy_url, request_line) = capturing_proxy().await?;
|
||||
let target = format!(
|
||||
"{}:{}",
|
||||
relay.url.host_str().expect("relay url has a host"),
|
||||
relay.url.port().expect("relay url has a port")
|
||||
);
|
||||
|
||||
// The probe cannot succeed: the fake proxy never completes the CONNECT tunnel.
|
||||
// What matters is that the probe was attempted via the proxy rather than
|
||||
// connecting to the relay directly.
|
||||
let res = run_https_probe(
|
||||
&dns_resolver,
|
||||
relay.url,
|
||||
CaTlsConfig::insecure_skip_verify()
|
||||
.client_config(default_provider())
|
||||
.expect("infallible"),
|
||||
Some(&proxy_url),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
res.is_err(),
|
||||
"probe must not succeed through a proxy that refuses to tunnel, got {res:?}"
|
||||
);
|
||||
|
||||
let request_line = time::timeout(Duration::from_secs(10), request_line)
|
||||
.await
|
||||
.expect("proxy did not receive a request, the probe bypassed it")
|
||||
.anyerr()?;
|
||||
assert!(
|
||||
request_line.starts_with(&format!("CONNECT {target} ")),
|
||||
"expected the probe to tunnel to {target}, proxy received: {request_line}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_qad_probe_v4() -> Result {
|
||||
let (server, relay) = test_utils::relay().await;
|
||||
let relay = Arc::new(relay);
|
||||
let client_config = iroh_relay::tls::make_dangerous_client_config();
|
||||
let ep = noq::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).anyerr()?;
|
||||
let client_addr = ep.local_addr().anyerr()?;
|
||||
|
||||
let quic_client = iroh_relay::quic::QuicClient::new(ep.clone(), client_config);
|
||||
let dns_resolver = DnsResolver::default();
|
||||
|
||||
let (report, conn) =
|
||||
super::super::run_probe_v4(relay, quic_client, dns_resolver, CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(report.addr, client_addr);
|
||||
drop(conn);
|
||||
ep.wait_idle().await;
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
//! Portmapper integration.
|
||||
//!
|
||||
//! Wraps the real [`portmapper`] crate when the `portmapper` feature is enabled,
|
||||
//! or provides a no-op stub otherwise.
|
||||
|
||||
use std::net::SocketAddrV4;
|
||||
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Configuration for the portmapper service (UPnP, PCP, NAT-PMP).
|
||||
///
|
||||
/// Port mapping asks the local router to open an external port so peers can
|
||||
/// reach this endpoint directly, improving connectivity behind NATs. The
|
||||
/// discovery step (UPnP uses SSDP multicast) can, however, trigger firewall
|
||||
/// prompts on some networks — see [`PortmapperConfig::Disabled`].
|
||||
///
|
||||
/// Used with [`crate::endpoint::Builder::portmapper_config`].
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub enum PortmapperConfig {
|
||||
/// Enable portmapping with default settings.
|
||||
///
|
||||
/// This is the default.
|
||||
#[non_exhaustive]
|
||||
Enabled {},
|
||||
/// Disable portmapping.
|
||||
///
|
||||
/// Skips the UPnP/PCP/NAT-PMP gateway probing. Use this to avoid the
|
||||
/// SSDP multicast discovery that can raise firewall dialogs (notably on
|
||||
/// macOS), at the cost of potentially worse direct connectivity behind
|
||||
/// some NATs.
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl Default for PortmapperConfig {
|
||||
fn default() -> Self {
|
||||
PortmapperConfig::Enabled {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_client(config: &PortmapperConfig) -> Client {
|
||||
match config {
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
PortmapperConfig::Enabled {} => Client::Enabled(::portmapper::Client::default()),
|
||||
_ => {
|
||||
let (tx, rx) = watch::channel(None);
|
||||
Client::Disabled { _tx: tx, rx }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Portmapper client: either the real implementation or a no-op.
|
||||
///
|
||||
/// The disabled variant is used when the `portmapper` feature is off, on wasm,
|
||||
/// or when portmapping is disabled via [`PortmapperConfig::Disabled`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Client {
|
||||
/// The real portmapper client (requires the `portmapper` feature).
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
Enabled(::portmapper::Client),
|
||||
/// No-op: keeps the sender alive so the receiver never closes.
|
||||
Disabled {
|
||||
_tx: watch::Sender<Option<SocketAddrV4>>,
|
||||
rx: watch::Receiver<Option<SocketAddrV4>>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub(crate) fn procure_mapping(&self) {
|
||||
match self {
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
Client::Enabled(c) => c.procure_mapping(),
|
||||
Client::Disabled { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn update_local_port(&self, _port: std::num::NonZeroU16) {
|
||||
match self {
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
Client::Enabled(c) => c.update_local_port(_port),
|
||||
Client::Disabled { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn deactivate(&self) {
|
||||
match self {
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
Client::Enabled(c) => c.deactivate(),
|
||||
Client::Disabled { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn watch_external_address(&self) -> watch::Receiver<Option<SocketAddrV4>> {
|
||||
match self {
|
||||
#[cfg(all(not(wasm_browser), feature = "portmapper"))]
|
||||
Client::Enabled(c) => c.watch_external_address(),
|
||||
Client::Disabled { rx, .. } => rx.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+1059
File diff suppressed because it is too large.
Load diff
Vendored
+135
@@ -0,0 +1,135 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use iroh_base::EndpointId;
|
||||
use portable_atomic::{AtomicU64, Ordering};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
#[cfg(not(wasm_browser))]
|
||||
use tokio_util::task::TaskTracker;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Runtime {
|
||||
id: EndpointId,
|
||||
#[cfg(not(wasm_browser))]
|
||||
tasks: TaskTracker,
|
||||
#[cfg(not(wasm_browser))]
|
||||
cancel: CancellationToken,
|
||||
#[cfg(not(wasm_browser))]
|
||||
task_counter: AtomicU64,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Create a new [`Runtime`] that manages shutting down tasks properly,
|
||||
/// whether gracefully or un-gracefully.
|
||||
pub(crate) fn new(id: EndpointId) -> Self {
|
||||
Self {
|
||||
id,
|
||||
#[cfg(not(wasm_browser))]
|
||||
tasks: TaskTracker::new(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
cancel: CancellationToken::new(),
|
||||
#[cfg(not(wasm_browser))]
|
||||
task_counter: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shutdown the runtime gracefully.
|
||||
///
|
||||
/// Closes the task tracker and waits for all spawned tasks to finish naturally.
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(crate) async fn shutdown(&self) {
|
||||
self.abort();
|
||||
// Waits for all tasks to stop (and thus drop all of their futures).
|
||||
// If the task tracker had already been closed and tasks have all been cleaned up,
|
||||
// this returns immediately.
|
||||
self.tasks.wait().await;
|
||||
}
|
||||
|
||||
/// Shutdown the runtime ASAP, not waiting for any graceful closing of tasks.
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(crate) fn abort(&self) {
|
||||
// Signal all spawned tasks to stop immediately.
|
||||
self.cancel.cancel();
|
||||
// Signal that the runtime should be closed.
|
||||
self.tasks.close();
|
||||
// Does not wait for the tasks to return.
|
||||
}
|
||||
|
||||
/// No-op on wasm. There is no task tracker to close or wait on.
|
||||
#[cfg(wasm_browser)]
|
||||
pub(crate) async fn shutdown(&self) {}
|
||||
|
||||
/// No-op on wasm. There is no task tracker or cancellation to perform.
|
||||
#[cfg(wasm_browser)]
|
||||
pub(crate) fn abort(&self) {}
|
||||
}
|
||||
|
||||
impl noq::Runtime for Runtime {
|
||||
#[cfg(not(wasm_browser))]
|
||||
fn new_timer(&self, i: std::time::Instant) -> Pin<Box<dyn noq::AsyncTimer>> {
|
||||
noq::TokioRuntime.new_timer(i)
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
fn new_timer(&self, deadline: n0_future::time::Instant) -> Pin<Box<dyn noq::AsyncTimer>> {
|
||||
Box::pin(web::Timer(n0_future::time::sleep_until(deadline)))
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
|
||||
// Do not allow spawning more tasks if the runtime should be closed.
|
||||
if self.tasks.is_closed() {
|
||||
tracing::debug!(me = %self.id.fmt_short(), "runtime closed, dropping spawned task");
|
||||
return;
|
||||
}
|
||||
|
||||
use tracing::{Instrument, trace_span};
|
||||
|
||||
let task_id = self.task_counter.fetch_add(1, Ordering::Relaxed);
|
||||
let cancel = self.cancel.clone();
|
||||
let span = trace_span!("runtime", me = %self.id.fmt_short(), task_id);
|
||||
self.tasks.spawn(async move {
|
||||
// wrapping the future in a cancellation token is what allows
|
||||
// us to "abort" tasks in the event the runtime is meant to
|
||||
// close quickly and ungracefully
|
||||
cancel.run_until_cancelled(future.instrument(span)).await;
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
|
||||
wasm_bindgen_futures::spawn_local(future);
|
||||
}
|
||||
|
||||
// We're not actually using this function in iroh
|
||||
#[cfg(not(wasm_browser))]
|
||||
fn wrap_udp_socket(
|
||||
&self,
|
||||
t: std::net::UdpSocket,
|
||||
) -> std::io::Result<Box<dyn noq::AsyncUdpSocket>> {
|
||||
noq::TokioRuntime.wrap_udp_socket(t)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
mod web {
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use n0_future::time;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Timer(pub(crate) time::Sleep);
|
||||
|
||||
impl noq::AsyncTimer for Timer {
|
||||
fn reset(mut self: Pin<&mut Self>, deadline: time::Instant) {
|
||||
Pin::new(&mut self.0).reset(deadline)
|
||||
}
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
|
||||
Pin::new(&mut self.0).poll(cx)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+2866
File diff suppressed because it is too large.
Load diff
+323
@@ -0,0 +1,323 @@
|
||||
//! Default [`PathSelector`] implementation.
|
||||
//!
|
||||
//! [`BiasedRttPathSelector`] preserves iroh's historical "lowest biased RTT wins, with
|
||||
//! stickiness against flapping" behaviour and is what's installed when no custom
|
||||
//! selector is provided.
|
||||
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use rustc_hash::FxHashMap;
|
||||
use tracing::trace;
|
||||
|
||||
use super::{
|
||||
remote_map::{PathSelection, PathSelectionContext, PathSelectionData, PathSelector},
|
||||
transports::AddrKind,
|
||||
};
|
||||
use crate::socket::transports::FourTuple;
|
||||
|
||||
/// How much do we prefer IPv6 over IPv4 by default.
|
||||
const IPV6_RTT_ADVANTAGE: Duration = Duration::from_millis(3);
|
||||
|
||||
/// Stickiness threshold for biased RTT comparisons. Switching to a same-tier path only
|
||||
/// happens when its biased RTT is at least this much better than the current path's.
|
||||
const RTT_SWITCHING_MIN: Duration = Duration::from_millis(5);
|
||||
|
||||
/// Whether a transport is a primary path or a backup.
|
||||
///
|
||||
/// Primary paths are used preferentially. Backup paths are only used when no primary
|
||||
/// path is available. This is independent of the QUIC `PathStatus`; today the only
|
||||
/// transport classified as backup is the relay transport.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum TransportType {
|
||||
/// A primary path: used whenever available.
|
||||
Primary,
|
||||
/// A backup path: only used when no primary path is available.
|
||||
Backup,
|
||||
}
|
||||
|
||||
/// Bias configuration for a single transport kind.
|
||||
///
|
||||
/// Used by [`BiasedRttPathSelector`] to bias path selection per address kind.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) struct TransportBias {
|
||||
transport_type: TransportType,
|
||||
/// RTT bias in nanoseconds. Negative values make this transport more preferred.
|
||||
rtt_bias: i128,
|
||||
}
|
||||
|
||||
impl TransportBias {
|
||||
/// Creates a primary transport bias with no RTT advantage.
|
||||
pub(crate) fn primary() -> Self {
|
||||
Self {
|
||||
transport_type: TransportType::Primary,
|
||||
rtt_bias: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a backup transport bias with no RTT advantage.
|
||||
fn backup() -> Self {
|
||||
Self {
|
||||
transport_type: TransportType::Backup,
|
||||
rtt_bias: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an RTT advantage to this transport, making it more preferred.
|
||||
pub(crate) fn with_rtt_advantage(mut self, advantage: Duration) -> Self {
|
||||
self.rtt_bias -= advantage.as_nanos() as i128;
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds an RTT disadvantage to this transport, making it less preferred.
|
||||
#[cfg(all(test, feature = "unstable-custom-transports"))]
|
||||
pub(crate) fn with_rtt_disadvantage(mut self, disadvantage: Duration) -> Self {
|
||||
self.rtt_bias += disadvantage.as_nanos() as i128;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The default [`PathSelector`] used by iroh.
|
||||
///
|
||||
/// Sorts paths by `(transport_type, biased_rtt)` (primary tier wins, then lowest biased
|
||||
/// RTT). Within the same tier, switching only happens once a candidate's biased RTT is
|
||||
/// at least 5ms better than the currently-selected path — this avoids flapping under
|
||||
/// jitter. Across tiers, switching is immediate.
|
||||
///
|
||||
/// The biases are configured per [`AddrKind`]. Defaults: IPv4 and IPv6 are primary
|
||||
/// (IPv6 has a 3ms RTT advantage), Relay is backup, custom transports are primary with
|
||||
/// no advantage.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct BiasedRttPathSelector {
|
||||
biases: Arc<FxHashMap<AddrKind, TransportBias>>,
|
||||
}
|
||||
|
||||
impl Default for BiasedRttPathSelector {
|
||||
fn default() -> Self {
|
||||
let mut map = FxHashMap::default();
|
||||
map.insert(AddrKind::IpV4, TransportBias::primary());
|
||||
map.insert(
|
||||
AddrKind::IpV6,
|
||||
TransportBias::primary().with_rtt_advantage(IPV6_RTT_ADVANTAGE),
|
||||
);
|
||||
map.insert(AddrKind::Relay, TransportBias::backup());
|
||||
Self {
|
||||
biases: Arc::new(map),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BiasedRttPathSelector {
|
||||
/// Returns a new selector with the given bias added or updated for `kind`.
|
||||
#[cfg(all(test, feature = "unstable-custom-transports"))]
|
||||
pub(crate) fn with_bias(self, kind: AddrKind, bias: TransportBias) -> Self {
|
||||
let mut map = (*self.biases).clone();
|
||||
map.insert(kind, bias);
|
||||
Self {
|
||||
biases: Arc::new(map),
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up the bias for an address. Defaults to primary with no RTT bias.
|
||||
fn bias_for(&self, addr: &FourTuple) -> TransportBias {
|
||||
self.biases
|
||||
.get(&addr.addr_kind())
|
||||
.copied()
|
||||
.unwrap_or_else(TransportBias::primary)
|
||||
}
|
||||
|
||||
/// Computes the sort key for a path: lower is better.
|
||||
fn sort_key(&self, addr: &FourTuple, rtt: Duration) -> (TransportType, i128) {
|
||||
let bias = self.bias_for(addr);
|
||||
let biased_rtt = (rtt.as_nanos() as i128).saturating_add(bias.rtt_bias);
|
||||
(bias.transport_type, biased_rtt)
|
||||
}
|
||||
}
|
||||
|
||||
impl PathSelector for BiasedRttPathSelector {
|
||||
fn select(&self, ctx: &PathSelectionContext<'_>) -> PathSelection {
|
||||
// Single pass: track the best candidate by sort key, and the best (lowest)
|
||||
// sort key seen for the currently-selected address. When the same address
|
||||
// appears multiple times (one path per connection), `min` over `sort_key`
|
||||
// naturally picks the lowest-RTT instance — no separate aggregation needed.
|
||||
let current = ctx.current();
|
||||
let mut best: Option<(PathSelectionData<'_>, (TransportType, i128))> = None;
|
||||
let mut current_key: Option<(TransportType, i128)> = None;
|
||||
|
||||
trace!("dumping path RTTs");
|
||||
for psd in ctx.paths() {
|
||||
let network_path = psd.network_path();
|
||||
// Skip paths whose stats can't be read (e.g. closed concurrently with select).
|
||||
let Some(stats) = psd.stats() else {
|
||||
continue;
|
||||
};
|
||||
let rtt = stats.rtt;
|
||||
trace!(%network_path, ?rtt);
|
||||
let key = self.sort_key(network_path, rtt);
|
||||
|
||||
if Some(network_path) == current && current_key.is_none_or(|c| key < c) {
|
||||
current_key = Some(key);
|
||||
}
|
||||
if best.as_ref().is_none_or(|(_, b)| key < *b) {
|
||||
best = Some((psd, key));
|
||||
}
|
||||
}
|
||||
|
||||
let mut selection = PathSelection::none();
|
||||
let Some((best_psd, (best_tier, best_biased))) = best else {
|
||||
return selection;
|
||||
};
|
||||
|
||||
// If we have no current path or no data for it, switch to the best.
|
||||
let Some((current_tier, current_biased)) = current_key else {
|
||||
selection.set(&best_psd);
|
||||
return selection;
|
||||
};
|
||||
|
||||
if current_tier != best_tier {
|
||||
// Always switch across tiers (e.g. relay -> primary).
|
||||
selection.set(&best_psd);
|
||||
} else if best_biased + RTT_SWITCHING_MIN.as_nanos() as i128 <= current_biased {
|
||||
// For the same tier, only switch when biased RTT is meaningfully better.
|
||||
selection.set(&best_psd);
|
||||
}
|
||||
selection
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
|
||||
use iroh_base::{EndpointId, RelayUrl};
|
||||
use noq::PathStats;
|
||||
|
||||
use super::*;
|
||||
use crate::socket::{
|
||||
remote_map::{PathSelectionContext, PathSelectionData},
|
||||
transports::{self, Addr},
|
||||
};
|
||||
|
||||
fn v4(port: u16) -> transports::FourTuple {
|
||||
transports::FourTuple::from_remote(Addr::Ip(SocketAddr::V4(SocketAddrV4::new(
|
||||
Ipv4Addr::LOCALHOST,
|
||||
port,
|
||||
))))
|
||||
}
|
||||
|
||||
fn v6(port: u16) -> transports::FourTuple {
|
||||
transports::FourTuple::from_remote(Addr::Ip(SocketAddr::V6(SocketAddrV6::new(
|
||||
Ipv6Addr::LOCALHOST,
|
||||
port,
|
||||
0,
|
||||
0,
|
||||
))))
|
||||
}
|
||||
|
||||
fn relay(port: u16) -> transports::FourTuple {
|
||||
let url = format!("https://relay{port}.iroh.computer")
|
||||
.parse::<RelayUrl>()
|
||||
.unwrap();
|
||||
transports::FourTuple::from_remote(Addr::Relay(
|
||||
url,
|
||||
EndpointId::from_bytes(&[0u8; 32]).unwrap(),
|
||||
))
|
||||
}
|
||||
|
||||
fn psd(addr: &transports::FourTuple, rtt_ms: u64) -> PathSelectionData<'_> {
|
||||
// PathStats is #[non_exhaustive], so build via Default + field assignment.
|
||||
let mut stats = PathStats::default();
|
||||
stats.rtt = Duration::from_millis(rtt_ms);
|
||||
PathSelectionData::for_test(addr, Some(stats))
|
||||
}
|
||||
|
||||
/// Runs [`BiasedRttPathSelector::default`] against the given paths and current
|
||||
/// selection, returning the selector's primary pick (cloned, for easier asserts).
|
||||
fn select_with_default(
|
||||
current: Option<&transports::FourTuple>,
|
||||
paths: Vec<PathSelectionData<'_>>,
|
||||
) -> Option<transports::FourTuple> {
|
||||
let ctx = PathSelectionContext::for_test(current, paths);
|
||||
BiasedRttPathSelector::default()
|
||||
.select(&ctx)
|
||||
.selected()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ipv6_wins_over_ipv4_within_bias() {
|
||||
let v4 = v4(1);
|
||||
let v6 = v6(1);
|
||||
|
||||
// Equal RTTs: IPv6 wins because of the bias advantage.
|
||||
let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 10)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v6));
|
||||
|
||||
// IPv6 still wins when 2ms slower (within the 3ms bias).
|
||||
let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 12)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v6));
|
||||
|
||||
// IPv4 wins when IPv6 is 10ms slower (exceeds 3ms bias).
|
||||
let chosen = select_with_default(None, vec![psd(&v4, 10), psd(&v6, 20)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn primary_wins_over_backup_regardless_of_rtt() {
|
||||
let v4 = v4(1);
|
||||
let relay = relay(1);
|
||||
|
||||
// Primary tier beats backup tier even when the backup has a much lower RTT.
|
||||
let chosen = select_with_default(None, vec![psd(&v4, 100), psd(&relay, 10)]);
|
||||
assert!(matches!(
|
||||
chosen.as_ref().map(|t| t.remote()),
|
||||
Some(Addr::Ip(_))
|
||||
));
|
||||
|
||||
// Even more extreme: 1000ms primary still wins over 1ms backup.
|
||||
let chosen = select_with_default(None, vec![psd(&v4, 1000), psd(&relay, 1)]);
|
||||
assert!(matches!(
|
||||
chosen.as_ref().map(|t| t.remote()),
|
||||
Some(Addr::Ip(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_tier_only_switches_with_significant_rtt_diff() {
|
||||
let v4_1 = v4(1);
|
||||
let v4_2 = v4(2);
|
||||
|
||||
// 2ms diff < 5ms threshold → keep current (no switch, primary() == None).
|
||||
let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 18)]);
|
||||
assert_eq!(chosen, None);
|
||||
|
||||
// 4ms diff < 5ms → keep current.
|
||||
let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 16)]);
|
||||
assert_eq!(chosen, None);
|
||||
|
||||
// 5ms diff hits the threshold (the condition is `<=`) → switch.
|
||||
let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 15)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v4_2));
|
||||
|
||||
// 6ms diff > 5ms → switch.
|
||||
let chosen = select_with_default(Some(&v4_1), vec![psd(&v4_1, 20), psd(&v4_2, 14)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v4_2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_current_path_selects_best() {
|
||||
let v4_1 = v4(1);
|
||||
let v4_2 = v4(2);
|
||||
let chosen = select_with_default(None, vec![psd(&v4_1, 20), psd(&v4_2, 10)]);
|
||||
assert_eq!(chosen.as_ref(), Some(&v4_2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_paths_returns_none() {
|
||||
// No current, no candidates: nothing to pick.
|
||||
assert_eq!(select_with_default(None, vec![]), None);
|
||||
|
||||
// Current is set but there are no candidates: keep current (primary() == None).
|
||||
let v4 = v4(1);
|
||||
assert_eq!(select_with_default(Some(&v4), vec![]), None);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
//! This module implements a map that can be modified from only one task but read from many others.
|
||||
//!
|
||||
//! We ensure this map avoids race conditions from multiple writers by doing these two things:
|
||||
//! - We only allow writing from one owner of the `&mut self` [`ConcurrentReadMap`].
|
||||
//! It cannot be cloned.
|
||||
//! - The read-only replicas [`ReadOnlyMap`] can only read, not write, but allow reading from
|
||||
//! concurrent tasks.
|
||||
|
||||
use std::{hash::Hash, sync::Arc};
|
||||
|
||||
use rustc_hash::FxBuildHasher;
|
||||
|
||||
/// A map that can be modified from only one task but read from many others.
|
||||
///
|
||||
/// Only the single `&mut self`-based "leader" which owns this map can modify it, but cheaply
|
||||
/// clonable "followers" can be created with [`ConcurrentReadMap::read_only`].
|
||||
/// These clones will update with recent writes from the leader.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ConcurrentReadMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V, FxBuildHasher>>);
|
||||
|
||||
impl<K: Hash + Eq, V> Default for ConcurrentReadMap<K, V> {
|
||||
fn default() -> Self {
|
||||
Self(Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Hash + Eq, V> ConcurrentReadMap<K, V> {
|
||||
pub(crate) fn get_or_insert_with<F>(&mut self, key: K, f: F) -> V
|
||||
where
|
||||
F: FnOnce() -> V,
|
||||
V: Clone,
|
||||
{
|
||||
self.0.get_or_insert_with(key, f, &self.0.guard()).clone()
|
||||
}
|
||||
|
||||
pub(crate) fn insert(&mut self, key: K, value: V) {
|
||||
self.0.insert(key, value, &self.0.guard());
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, key: &K) {
|
||||
self.0.remove(key, &self.0.guard());
|
||||
}
|
||||
|
||||
pub(crate) fn read_only(&self) -> ReadOnlyMap<K, V> {
|
||||
ReadOnlyMap(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A read replica for a [`ConcurrentReadMap`].
|
||||
///
|
||||
/// These can be cloned cheaply and will read recent writes from the original map.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct ReadOnlyMap<K: Hash + Eq, V>(Arc<papaya::HashMap<K, V, FxBuildHasher>>);
|
||||
|
||||
impl<K: Hash + Eq, V> ReadOnlyMap<K, V> {
|
||||
pub(crate) fn get(&self, key: &K) -> Option<V>
|
||||
where
|
||||
V: Clone,
|
||||
{
|
||||
self.0.get(key, &self.0.guard()).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn guard(&self) -> papaya::LocalGuard<'_> {
|
||||
self.0.guard()
|
||||
}
|
||||
|
||||
pub(crate) fn values<'g, G: papaya::Guard>(&self, guard: &'g G) -> papaya::Values<'g, K, V, G> {
|
||||
self.0.values(guard)
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
//! The various mapped addresses we use.
|
||||
|
||||
//! We use non-IP transports to carry datagrams. Yet Noq needs to address those
|
||||
//! transports using IPv6 addresses. These defines mappings of several IPv6 Unique Local
|
||||
//! Address ranges we use to keep track of the various "fake" address types we use.
|
||||
|
||||
use std::{
|
||||
fmt,
|
||||
hash::Hash,
|
||||
net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use n0_error::{e, stack_error};
|
||||
use rand::Rng;
|
||||
use rustc_hash::FxHashMap;
|
||||
use tracing::trace;
|
||||
|
||||
/// The Prefix/L of all Unique Local Addresses.
|
||||
const ADDR_PREFIXL: u8 = 0xfd;
|
||||
|
||||
/// The Global ID used in n0's Unique Local Addresses.
|
||||
const ADDR_GLOBAL_ID: [u8; 5] = [0x15, 0x07, 0x0a, 0x51, 0x0b];
|
||||
|
||||
/// The Subnet ID for [`RelayMappedAddr]: fd15:70a:510b:1::/64.
|
||||
const RELAY_MAPPED_SUBNET: [u8; 2] = [0x00, 0x01];
|
||||
|
||||
/// The Subnet ID for [`CustomMappedAddr`]: fd15:70a:510b:3::/64.
|
||||
const CUSTOM_MAPPED_SUBNET: [u8; 2] = [0x00, 0x03];
|
||||
|
||||
/// The Subnet ID for [`EndpointIdMappedAddr`]: fd15:70a:510b::/64.
|
||||
const ENDPOINT_ID_SUBNET: [u8; 2] = [0x00, 0x00];
|
||||
|
||||
/// A default fake addr, using the maximum addr that the internal fake addrs could be using.
|
||||
pub(crate) const DEFAULT_FAKE_ADDR: SocketAddrV6 = SocketAddrV6::new(
|
||||
Ipv6Addr::new(
|
||||
u16::from_be_bytes([ADDR_PREFIXL, 21]),
|
||||
u16::from_be_bytes([7, 10]),
|
||||
u16::from_be_bytes([81, 11]),
|
||||
u16::from_be_bytes([0, 0]),
|
||||
u16::MAX,
|
||||
u16::MAX,
|
||||
u16::MAX,
|
||||
u16::MAX,
|
||||
),
|
||||
MAPPED_PORT,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
|
||||
/// The dummy port used for all mapped addresses.
|
||||
///
|
||||
/// We map each entity, usually an [`crate::EndpointId`], to an IPv6 address. But socket addresses
|
||||
/// involve ports, so we use a dummy fixed port when creating socket addresses.
|
||||
const MAPPED_PORT: u16 = 12345;
|
||||
|
||||
/// Generic mapped address.
|
||||
///
|
||||
/// Allows implementing [`AddrMap`].
|
||||
pub(crate) trait MappedAddr {
|
||||
/// Generates a new mapped address in the IPv6 Unique Local Address space.
|
||||
///
|
||||
/// The host bits are random so a remote peer cannot guess one of our live mapped
|
||||
/// addresses (uniqueness is ensured by [`AddrMap::get`]).
|
||||
fn generate() -> Self;
|
||||
|
||||
/// Returns a consistent [`SocketAddr`] for the mapped addr.
|
||||
///
|
||||
/// This socket address does not have a routable IP address. It uses a fake but
|
||||
/// consistent port number, since the port does not play a role in the addressing. This
|
||||
/// socket address is only to be used to pass into Noq.
|
||||
fn private_socket_addr(&self) -> SocketAddr;
|
||||
}
|
||||
|
||||
/// An enum encompassing all the mapped and unmapped addresses.
|
||||
///
|
||||
/// This is essentially a slightly-stronger typed version of the IPv6 mapped addresses that
|
||||
/// we use on the Noq side. It categorises the addressed in what kind of mapped or
|
||||
/// unmapped addresses they are.
|
||||
///
|
||||
/// It does not guarantee that a mapped address exists in the mapping. Or that a particular
|
||||
/// address is even supported on this platform. Hence no wasm exceptions here.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum MultipathMappedAddr {
|
||||
/// An address for a [`crate::EndpointId`], via one or more paths.
|
||||
Mixed(EndpointIdMappedAddr),
|
||||
/// An address for a particular [`crate::EndpointId`] via a particular relay.
|
||||
Relay(RelayMappedAddr),
|
||||
/// An IP based transport address.
|
||||
Ip(SocketAddr),
|
||||
/// Custom transport address.
|
||||
Custom(CustomMappedAddr),
|
||||
}
|
||||
|
||||
impl From<SocketAddr> for MultipathMappedAddr {
|
||||
fn from(value: SocketAddr) -> Self {
|
||||
match value.ip() {
|
||||
IpAddr::V4(_) => Self::Ip(value),
|
||||
IpAddr::V6(addr) => {
|
||||
if let Ok(addr) = EndpointIdMappedAddr::try_from(addr) {
|
||||
return Self::Mixed(addr);
|
||||
}
|
||||
if let Ok(addr) = RelayMappedAddr::try_from(addr) {
|
||||
return Self::Relay(addr);
|
||||
}
|
||||
if let Ok(addr) = CustomMappedAddr::try_from(addr) {
|
||||
return Self::Custom(addr);
|
||||
}
|
||||
Self::Ip(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An address used to address a endpoint on any or all paths.
|
||||
///
|
||||
/// This is only used for initially connecting to a remote endpoint. We instruct Noq to
|
||||
/// send to this address, and duplicate all packets for this address to send on all paths we
|
||||
/// might want to send the initial on:
|
||||
///
|
||||
/// - If this the first connection to the remote endpoint we don't know which path will work
|
||||
/// and send to all of them.
|
||||
///
|
||||
/// - If there already is an active connection to this endpoint we now which path to use.
|
||||
///
|
||||
/// It is but a newtype around an IPv6 Unique Local Addr. And in our QUIC-facing socket
|
||||
/// APIs like [`noq::AsyncUdpSocket`] it comes in as the inner [`Ipv6Addr`], in those
|
||||
/// interfaces we have to be careful to do the conversion to this type.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct EndpointIdMappedAddr(Ipv6Addr);
|
||||
|
||||
impl MappedAddr for EndpointIdMappedAddr {
|
||||
/// Generates a globally unique fake UDP address.
|
||||
///
|
||||
/// This generates and IPv6 Unique Local Address according to RFC 4193.
|
||||
fn generate() -> Self {
|
||||
let mut addr = [0u8; 16];
|
||||
addr[0] = ADDR_PREFIXL;
|
||||
addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
|
||||
addr[6..8].copy_from_slice(&ENDPOINT_ID_SUBNET);
|
||||
rand::rng().fill_bytes(&mut addr[8..16]);
|
||||
|
||||
Self(Ipv6Addr::from(addr))
|
||||
}
|
||||
|
||||
/// Returns a consistent [`SocketAddr`] for the [`EndpointIdMappedAddr`].
|
||||
///
|
||||
/// This socket address does not have a routable IP address and port.
|
||||
///
|
||||
/// This uses a made-up port number, since the port does not play a role in the
|
||||
/// addressing. This socket address is only to be used to pass into Noq.
|
||||
fn private_socket_addr(&self) -> SocketAddr {
|
||||
SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EndpointIdMappedAddr {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "EndpointIdMappedAddr({})", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Ipv6Addr> for EndpointIdMappedAddr {
|
||||
type Error = EndpointIdMappedAddrError;
|
||||
|
||||
fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
|
||||
let octets = value.octets();
|
||||
if octets[0] == ADDR_PREFIXL
|
||||
&& octets[1..6] == ADDR_GLOBAL_ID
|
||||
&& octets[6..8] == ENDPOINT_ID_SUBNET
|
||||
{
|
||||
return Ok(Self(value));
|
||||
}
|
||||
Err(e!(EndpointIdMappedAddrError))
|
||||
}
|
||||
}
|
||||
|
||||
/// Can occur when converting a [`SocketAddr`] to an [`EndpointIdMappedAddr`]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[error("Failed to convert")]
|
||||
pub(crate) struct EndpointIdMappedAddrError;
|
||||
|
||||
/// An Ipv6 ULA address, identifying a relay path for a [`crate::EndpointId`].
|
||||
///
|
||||
/// Since iroh endpoint are reachable via a relay server we have a network path indicated by
|
||||
/// the `(EndpointId, RelayUrl)`. However Noq can only handle socket addresses, so we use
|
||||
/// IPv6 addresses in a private IPv6 Unique Local Address range, which map to a unique
|
||||
/// `(EndointId, RelayUrl)` pair.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub(crate) struct RelayMappedAddr(Ipv6Addr);
|
||||
|
||||
impl MappedAddr for RelayMappedAddr {
|
||||
/// Generates a globally unique fake UDP address.
|
||||
///
|
||||
/// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
|
||||
/// which is recognised by iroh as an IP mapped address.
|
||||
fn generate() -> Self {
|
||||
let mut addr = [0u8; 16];
|
||||
addr[0] = ADDR_PREFIXL;
|
||||
addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
|
||||
addr[6..8].copy_from_slice(&RELAY_MAPPED_SUBNET);
|
||||
rand::rng().fill_bytes(&mut addr[8..16]);
|
||||
|
||||
Self(Ipv6Addr::from(addr))
|
||||
}
|
||||
|
||||
/// Returns a consistent [`SocketAddr`] for the [`RelayMappedAddr`].
|
||||
///
|
||||
/// This socket address does not have a routable IP address and port.
|
||||
///
|
||||
/// This uses a made-up port number, since the port does not play a role in the
|
||||
/// addressing. This socket address is only to be used to pass into Noq.
|
||||
fn private_socket_addr(&self) -> SocketAddr {
|
||||
SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Ipv6Addr> for RelayMappedAddr {
|
||||
type Error = RelayMappedAddrError;
|
||||
|
||||
fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
|
||||
let octets = value.octets();
|
||||
if octets[0] == ADDR_PREFIXL
|
||||
&& octets[1..6] == ADDR_GLOBAL_ID
|
||||
&& octets[6..8] == RELAY_MAPPED_SUBNET
|
||||
{
|
||||
return Ok(Self(value));
|
||||
}
|
||||
Err(e!(RelayMappedAddrError))
|
||||
}
|
||||
}
|
||||
|
||||
/// Can occur when converting a [`SocketAddr`] to an [`RelayMappedAddr`]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[error("Failed to convert")]
|
||||
pub(crate) struct RelayMappedAddrError;
|
||||
|
||||
impl std::fmt::Display for RelayMappedAddr {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "RelayMappedAddr({})", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// An Ipv6 ULA address, identifying a custom transport path.
|
||||
///
|
||||
/// Custom transports allow user-defined transport mechanisms. However Noq can only handle
|
||||
/// socket addresses, so we use IPv6 addresses in a private IPv6 Unique Local Address range,
|
||||
/// which map to a unique [`iroh_base::CustomAddr`].
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
|
||||
pub(crate) struct CustomMappedAddr(Ipv6Addr);
|
||||
|
||||
impl MappedAddr for CustomMappedAddr {
|
||||
/// Generates a globally unique fake UDP address.
|
||||
///
|
||||
/// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
|
||||
/// which is recognised by iroh as an IP mapped address.
|
||||
fn generate() -> Self {
|
||||
let mut addr = [0u8; 16];
|
||||
addr[0] = ADDR_PREFIXL;
|
||||
addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
|
||||
addr[6..8].copy_from_slice(&CUSTOM_MAPPED_SUBNET);
|
||||
rand::rng().fill_bytes(&mut addr[8..16]);
|
||||
|
||||
Self(Ipv6Addr::from(addr))
|
||||
}
|
||||
|
||||
/// Returns a consistent [`SocketAddr`] for the [`CustomMappedAddr`].
|
||||
///
|
||||
/// This socket address does not have a routable IP address and port.
|
||||
///
|
||||
/// This uses a made-up port number, since the port does not play a role in the
|
||||
/// addressing. This socket address is only to be used to pass into Noq.
|
||||
fn private_socket_addr(&self) -> SocketAddr {
|
||||
SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<IpAddr> for CustomMappedAddr {
|
||||
type Error = CustomMappedAddrError;
|
||||
|
||||
fn try_from(value: IpAddr) -> std::result::Result<Self, Self::Error> {
|
||||
match value {
|
||||
IpAddr::V4(_) => Err(e!(CustomMappedAddrError)),
|
||||
IpAddr::V6(addr) => addr.try_into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<Ipv6Addr> for CustomMappedAddr {
|
||||
type Error = CustomMappedAddrError;
|
||||
|
||||
fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
|
||||
let octets = value.octets();
|
||||
if octets[0] == ADDR_PREFIXL
|
||||
&& octets[1..6] == ADDR_GLOBAL_ID
|
||||
&& octets[6..8] == CUSTOM_MAPPED_SUBNET
|
||||
{
|
||||
return Ok(Self(value));
|
||||
}
|
||||
Err(e!(CustomMappedAddrError))
|
||||
}
|
||||
}
|
||||
|
||||
/// Can occur when converting a [`SocketAddr`] to a [`CustomMappedAddr`]
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[error("Failed to convert")]
|
||||
pub(crate) struct CustomMappedAddrError;
|
||||
|
||||
impl std::fmt::Display for CustomMappedAddr {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "CustomMappedAddr({})", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A bi-directional map between a key and a [`MappedAddr`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct AddrMap<K, V> {
|
||||
inner: Arc<std::sync::Mutex<AddrMapInner<K, V>>>,
|
||||
}
|
||||
|
||||
// Manual impl because derive ends up requiring T: Default.
|
||||
impl<K, V> Default for AddrMap<K, V> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
inner: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K, V> AddrMap<K, V>
|
||||
where
|
||||
K: Eq + Hash + Clone + fmt::Debug,
|
||||
V: MappedAddr + Eq + Hash + Copy + fmt::Debug,
|
||||
{
|
||||
/// Returns the [`MappedAddr`], generating one if needed.
|
||||
pub(super) fn get(&self, key: &K) -> V {
|
||||
let mut inner = self.inner.lock().expect("poisoned");
|
||||
match inner.addrs.get(key) {
|
||||
Some(addr) => *addr,
|
||||
None => {
|
||||
let addr = loop {
|
||||
let candidate = V::generate();
|
||||
if !inner.lookup.contains_key(&candidate) {
|
||||
break candidate;
|
||||
}
|
||||
};
|
||||
inner.addrs.insert(key.clone(), addr);
|
||||
inner.lookup.insert(addr, key.clone());
|
||||
trace!(?addr, ?key, "generated new addr");
|
||||
addr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the reverse lookup.
|
||||
pub(super) fn lookup(&self, addr: &V) -> Option<K> {
|
||||
let inner = self.inner.lock().expect("poisoned");
|
||||
inner.lookup.get(addr).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AddrMapInner<K, V> {
|
||||
addrs: FxHashMap<K, V>,
|
||||
lookup: FxHashMap<V, K>,
|
||||
}
|
||||
|
||||
// Manual impl because derive ends up requiring T: Default.
|
||||
impl<K, V> Default for AddrMapInner<K, V> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
addrs: Default::default(),
|
||||
lookup: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+126
@@ -0,0 +1,126 @@
|
||||
use iroh_metrics::{Counter, MetricsGroup};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Metrics collected by the iroh socket.
|
||||
#[derive(Debug, Serialize, Deserialize, MetricsGroup)]
|
||||
#[non_exhaustive]
|
||||
#[metrics(name = "socket", default)]
|
||||
pub struct Metrics {
|
||||
/// Intended to count updates to the local direct address set, but currently unused
|
||||
/// (never incremented).
|
||||
pub update_direct_addrs: Counter,
|
||||
|
||||
/// Number of bytes sent over IPv4.
|
||||
pub send_ipv4: Counter,
|
||||
/// Number of bytes sent over IPv6.
|
||||
pub send_ipv6: Counter,
|
||||
/// Number of bytes sent over the relay transport.
|
||||
pub send_relay: Counter,
|
||||
|
||||
/// Number of data bytes received over the relay transport.
|
||||
pub recv_data_relay: Counter,
|
||||
/// Number of data bytes received over any custom transport.
|
||||
pub recv_data_custom: Counter,
|
||||
/// Number of data bytes received over IPv4.
|
||||
pub recv_data_ipv4: Counter,
|
||||
/// Number of data bytes received over IPv6.
|
||||
pub recv_data_ipv6: Counter,
|
||||
/// Number of QUIC datagrams received.
|
||||
pub recv_datagrams: Counter,
|
||||
/// Number of receive events that used GRO (coalesced datagram batches).
|
||||
///
|
||||
/// This counts batches, not the individual datagrams within them. See
|
||||
/// [`Self::recv_datagrams`] for the datagram count.
|
||||
pub recv_gro_datagrams: Counter,
|
||||
|
||||
/// Number of times the home relay changed to a different relay.
|
||||
///
|
||||
/// This includes the initial assignment from no home relay to a home relay.
|
||||
pub relay_home_change: Counter,
|
||||
|
||||
/// Number of connections to a relay server that were established.
|
||||
///
|
||||
/// Failed dial attempts are not counted. A relay that is reconnected to is counted
|
||||
/// once per connection, so this grows on every reconnect.
|
||||
pub relay_conns_success: Counter,
|
||||
/// Number of failed attempts to connect to a relay server.
|
||||
///
|
||||
/// Each attempt is counted, so an unreachable relay increments this on every retry.
|
||||
pub relay_conns_failed: Counter,
|
||||
/// Number of connections to a relay server that ended.
|
||||
///
|
||||
/// Paired with [`Self::relay_conns_success`], so the number of current connections is
|
||||
/// `relay_conns_success` - `relay_conns_closed`.
|
||||
pub relay_conns_closed: Counter,
|
||||
/// Number of relay connections on which the relay reported rate limiting.
|
||||
///
|
||||
/// This is incremented at most once per connection, so it counts the affected
|
||||
/// connections and not how often the relay reported the problem. Relate it to
|
||||
/// [`Self::relay_conns_success`] to see how many connections were affected.
|
||||
pub relay_conns_ratelimited: Counter,
|
||||
|
||||
/*
|
||||
* Holepunching metrics
|
||||
*/
|
||||
/// The number of times holepunching is initiated on a connection.
|
||||
///
|
||||
/// This can be incremented multiple times for a single connection. Note that only the
|
||||
/// client-side of a connection will increment this counter.
|
||||
pub holepunch_attempts: Counter,
|
||||
/// The number of network paths to peers that are direct.
|
||||
///
|
||||
/// This can be incremented multiple times for a single connection.
|
||||
pub paths_direct: Counter,
|
||||
/// The number of network paths to peers that are relayed.
|
||||
///
|
||||
/// This would typically only be incremented once for a single connection.
|
||||
pub paths_relay: Counter,
|
||||
/// The number of network paths to peers that are user defined.
|
||||
///
|
||||
/// This would typically only be incremented once for a single connection.
|
||||
pub paths_custom: Counter,
|
||||
/// The number of connections that have been direct connections.
|
||||
///
|
||||
/// This is only incremented once for each opened connection. See `num_conns_opened` for
|
||||
/// the number of opened connections.
|
||||
pub num_conns_direct: Counter,
|
||||
|
||||
/*
|
||||
* Connection Metrics
|
||||
*
|
||||
* These all only count connections that completed the TLS handshake successfully. This means
|
||||
* that short lived 0RTT connections are potentially not included in these counts.
|
||||
*/
|
||||
/// Number of connections opened (only handshaked connections are counted).
|
||||
pub num_conns_opened: Counter,
|
||||
/// Number of connections closed (only handshaked connections are counted).
|
||||
pub num_conns_closed: Counter,
|
||||
|
||||
/// Number of IP transport paths opened.
|
||||
pub transport_ip_paths_added: Counter,
|
||||
/// Number of IP transport paths closed.
|
||||
pub transport_ip_paths_removed: Counter,
|
||||
/// Number of relay transport paths opened.
|
||||
pub transport_relay_paths_added: Counter,
|
||||
/// Number of relay transport paths closed.
|
||||
pub transport_relay_paths_removed: Counter,
|
||||
/// Number of custom transport paths opened.
|
||||
pub transport_custom_paths_added: Counter,
|
||||
/// Number of custom transport paths closed.
|
||||
pub transport_custom_paths_removed: Counter,
|
||||
|
||||
/// Number of iterations of the main socket actor loop.
|
||||
pub actor_tick_main: Counter,
|
||||
/// Number of actor messages processed by the socket actor loop.
|
||||
pub actor_tick_msg: Counter,
|
||||
/// Number of periodic re-STUN timer ticks handled by the socket actor loop.
|
||||
pub actor_tick_re_stun: Counter,
|
||||
/// Number of port-mapping change events handled by the socket actor loop.
|
||||
pub actor_tick_portmap_changed: Counter,
|
||||
/// Intended to count direct address heartbeat ticks, but currently unused (never incremented).
|
||||
pub actor_tick_direct_addr_heartbeat: Counter,
|
||||
/// Number of local network interface (link) change events handled by the socket actor loop.
|
||||
pub actor_link_change: Counter,
|
||||
/// Number of times an input watcher or receiver closed in the socket actor loop.
|
||||
pub actor_tick_other: Counter,
|
||||
}
|
||||
Vendored
+515
@@ -0,0 +1,515 @@
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
future::poll_fn,
|
||||
hash::Hash,
|
||||
net::SocketAddr,
|
||||
sync::Arc,
|
||||
task::{Context, Poll, Waker, ready},
|
||||
};
|
||||
|
||||
use iroh_base::{CustomAddr, EndpointAddr, EndpointId, RelayUrl};
|
||||
use n0_future::task::JoinSet;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::{Span, error, trace};
|
||||
|
||||
pub(crate) use self::remote_state::PathStateReceiver;
|
||||
use self::remote_state::RemoteStateActor;
|
||||
pub(super) use self::remote_state::RemoteStateMessage;
|
||||
pub use self::remote_state::{
|
||||
Path, PathEvent, PathEventStream, PathList, PathListIter, PathListStream, RemoteInfo,
|
||||
TransportAddrInfo, TransportAddrUsage,
|
||||
};
|
||||
#[cfg(feature = "unstable-custom-transports")]
|
||||
pub use self::remote_state::{
|
||||
PathSelection, PathSelectionContext, PathSelectionData, PathSelector,
|
||||
};
|
||||
#[cfg(not(feature = "unstable-custom-transports"))]
|
||||
pub(crate) use self::remote_state::{
|
||||
PathSelection, PathSelectionContext, PathSelectionData, PathSelector,
|
||||
};
|
||||
use super::{
|
||||
DirectAddr, Metrics as SocketMetrics,
|
||||
mapped_addrs::{
|
||||
AddrMap, CustomMappedAddr, EndpointIdMappedAddr, MappedAddr, MultipathMappedAddr,
|
||||
RelayMappedAddr,
|
||||
},
|
||||
transports,
|
||||
};
|
||||
use crate::{
|
||||
address_lookup::{self, AddressLookupFailed},
|
||||
endpoint::LocalTransportAddr,
|
||||
socket::concurrent_read_map::{ConcurrentReadMap, ReadOnlyMap},
|
||||
};
|
||||
|
||||
mod remote_state;
|
||||
|
||||
// TODO: use this
|
||||
// /// Number of endpoints that are inactive for which we keep info about. This limit is enforced
|
||||
// /// periodically via [`NodeMap::prune_inactive`].
|
||||
// const MAX_INACTIVE_NODES: usize = 30;
|
||||
|
||||
/// Map containing all the state for endpoints.
|
||||
///
|
||||
/// - Has actors which each manage all the connection state for a remote endpoint.
|
||||
///
|
||||
/// - Has the mapped addresses we use to refer to non-IP transports destinations into IPv6
|
||||
/// addressing space that is used by Noq.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RemoteMap {
|
||||
/// Maps for converting between mapped and IP/relay addrs.
|
||||
pub(super) mapped_addrs: MappedAddrs,
|
||||
|
||||
/// The senders for the inbox of each `RemoteStateActor` that runs.
|
||||
///
|
||||
/// This is separated out of `Tasks` to make keeping a mutable borrow of the senders possible
|
||||
/// while we're spawning a task using another mutable borrow of `Tasks`.
|
||||
senders: ConcurrentReadMap<EndpointId, mpsc::Sender<RemoteStateMessage>>,
|
||||
|
||||
/// The state kept for spawning new actors and cleaning them up.
|
||||
tasks: Tasks,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct MappedAddrs {
|
||||
/// The mapping between [`EndpointId`]s and [`EndpointIdMappedAddr`]s.
|
||||
pub(super) endpoint_addrs: AddrMap<EndpointId, EndpointIdMappedAddr>,
|
||||
/// The mapping between endpoints via a relay and their [`RelayMappedAddr`]s.
|
||||
pub(super) relay_addrs: AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
|
||||
/// The mapping between custom transport addresses and their [`CustomMappedAddr`]s.
|
||||
pub(super) custom_addrs: AddrMap<CustomAddr, CustomMappedAddr>,
|
||||
}
|
||||
|
||||
impl MappedAddrs {
|
||||
/// Converts a possibly mapped-IP address into a [`transports::Addr`].
|
||||
pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> Option<transports::Addr> {
|
||||
to_transport_addr(addr, &self.relay_addrs, &self.custom_addrs)
|
||||
}
|
||||
|
||||
/// Converts a possibly mapped-IP 4-tuple into a [`transports::FourTuple`].
|
||||
pub(crate) fn to_transport_tuple(
|
||||
&self,
|
||||
four_tuple: &noq::FourTuple,
|
||||
) -> Option<transports::FourTuple> {
|
||||
let remote = to_transport_addr(four_tuple.remote(), &self.relay_addrs, &self.custom_addrs)?;
|
||||
let local = LocalTransportAddr::from_noq_local_ip(
|
||||
four_tuple.local_ip(),
|
||||
&remote,
|
||||
&self.custom_addrs,
|
||||
);
|
||||
Some(transports::FourTuple::new(remote, local))
|
||||
}
|
||||
|
||||
/// Converts a [`transports::FourTuple`] to a mapped-IP 4-tuple.
|
||||
pub(crate) fn to_mapped_tuple(&self, four_tuple: &transports::FourTuple) -> noq::FourTuple {
|
||||
let (remote, local) = match four_tuple {
|
||||
transports::FourTuple::Ip { remote, local } => (*remote, *local),
|
||||
transports::FourTuple::Relay { url, endpoint_id } => (
|
||||
self.relay_addrs
|
||||
.get(&(url.clone(), *endpoint_id))
|
||||
.private_socket_addr(),
|
||||
None,
|
||||
),
|
||||
transports::FourTuple::Custom { remote, local } => {
|
||||
let remote = self.custom_addrs.get(remote).private_socket_addr();
|
||||
let local = local.as_ref().map(|custom_addr| {
|
||||
self.custom_addrs
|
||||
.get(custom_addr)
|
||||
.private_socket_addr()
|
||||
.ip()
|
||||
});
|
||||
(remote, local)
|
||||
}
|
||||
};
|
||||
noq::FourTuple::new(remote, local)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a mapped socket address to a transport address.
|
||||
///
|
||||
/// This takes a socket address, converts it into a [`MultipathMappedAddr`] and then tries
|
||||
/// to convert the mapped address into a [`transports::Addr`].
|
||||
///
|
||||
/// Returns `Some` with the transport address for IP, relay, or custom mapped addresses
|
||||
/// if an entry exists in the corresponding map.
|
||||
///
|
||||
/// Returns `None` for [`MultipathMappedAddr::Mixed`] addresses or unknown mapped addresses.
|
||||
fn to_transport_addr(
|
||||
addr: impl Into<MultipathMappedAddr>,
|
||||
relay_addrs: &AddrMap<(RelayUrl, EndpointId), RelayMappedAddr>,
|
||||
custom_addrs: &AddrMap<CustomAddr, CustomMappedAddr>,
|
||||
) -> Option<transports::Addr> {
|
||||
match addr.into() {
|
||||
MultipathMappedAddr::Mixed(_) => {
|
||||
error!(
|
||||
"Failed to convert addr to transport addr: Mixed mapped addr has no transport address"
|
||||
);
|
||||
None
|
||||
}
|
||||
MultipathMappedAddr::Relay(relay_mapped_addr) => {
|
||||
match relay_addrs.lookup(&relay_mapped_addr) {
|
||||
Some(parts) => Some(transports::Addr::from(parts)),
|
||||
None => {
|
||||
error!("Failed to convert addr to transport addr: Unknown relay mapped addr");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
MultipathMappedAddr::Custom(custom_mapped_addr) => {
|
||||
match custom_addrs.lookup(&custom_mapped_addr) {
|
||||
Some(custom_addr) => Some(transports::Addr::Custom(custom_addr)),
|
||||
None => {
|
||||
error!("Failed to convert addr to transport addr: Unknown custom mapped addr");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
MultipathMappedAddr::Ip(addr) => Some(transports::Addr::from(addr)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores the state required for starting and cleaning up the `RemoteStateActor`s.
|
||||
///
|
||||
/// When this is dropped, this will abort all tasks.
|
||||
#[derive(Debug)]
|
||||
struct Tasks {
|
||||
//
|
||||
// State required for spawning new actors.
|
||||
//
|
||||
metrics: Arc<SocketMetrics>,
|
||||
/// The "direct" addresses known for our local endpoint
|
||||
local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
|
||||
address_lookup: address_lookup::AddressLookupServices,
|
||||
shutdown_token: CancellationToken,
|
||||
|
||||
//
|
||||
// State for task-tracking spawned actors.
|
||||
//
|
||||
/// All the `RemoteStateActor` tasks, stored inside a `JoinSet`.
|
||||
///
|
||||
/// These tasks return their endpoint ID and the list of messages they didn't get to handle
|
||||
/// when they shut down.
|
||||
tasks: JoinSet<(EndpointId, Vec<RemoteStateMessage>)>,
|
||||
/// The waker that notifies `poll_cleanup` when the join set is populated with another task.
|
||||
poll_cleanup_waker: Option<Waker>,
|
||||
/// The path selector used by all [`RemoteStateActor`]s spawned by this map.
|
||||
path_selector: Arc<dyn PathSelector>,
|
||||
/// The tracing span for this endpoint, to be used as parent span for `RemoteStateActor` tasks.
|
||||
span: Span,
|
||||
}
|
||||
|
||||
impl RemoteMap {
|
||||
/// Creates a new [`RemoteMap`].
|
||||
pub(super) fn new(
|
||||
metrics: Arc<SocketMetrics>,
|
||||
local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
|
||||
address_lookup: address_lookup::AddressLookupServices,
|
||||
shutdown_token: CancellationToken,
|
||||
path_selector: Arc<dyn PathSelector>,
|
||||
span: Span,
|
||||
) -> Self {
|
||||
Self {
|
||||
mapped_addrs: Default::default(),
|
||||
senders: Default::default(),
|
||||
tasks: Tasks {
|
||||
metrics,
|
||||
local_direct_addrs,
|
||||
address_lookup,
|
||||
shutdown_token,
|
||||
tasks: Default::default(),
|
||||
poll_cleanup_waker: None,
|
||||
path_selector,
|
||||
span,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans up terminated `RemoteStateActor` tasks.
|
||||
///
|
||||
/// This polls for terminated actor tasks, and removes the corresponding actor sender
|
||||
/// from our sender map, or restarts the actor if it has pending messages.
|
||||
///
|
||||
/// Resolves to the actor's remote endpoint ID whenever a `RemoteStateActor` task joined,
|
||||
/// independent of whether the task was restarted or not.
|
||||
///
|
||||
/// Returns pending if there was no actor to be cleaned up right now, and registers
|
||||
/// for moments where this could become the case.
|
||||
///
|
||||
/// This function should be called in a loop to clean up expired tasks.
|
||||
/// Only one task is allowed to poll this function concurrently.
|
||||
pub(super) async fn cleanup(&mut self) -> EndpointId {
|
||||
loop {
|
||||
let (remote_id, leftover_messages) = poll_fn(|cx| self.poll_join_next(cx)).await;
|
||||
if self.remove_or_restart_actor(remote_id, leftover_messages) {
|
||||
return remote_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls for the next joined actor task.
|
||||
///
|
||||
/// Returns [`Poll::Pending`] if no tasks are running, and is woken when the task set changes.
|
||||
fn poll_join_next(
|
||||
&mut self,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<(EndpointId, Vec<RemoteStateMessage>)> {
|
||||
while let Some(result) = ready!(self.tasks.tasks.poll_join_next(cx)) {
|
||||
match result {
|
||||
Ok((remote_id, leftover_msgs)) => {
|
||||
return Poll::Ready((remote_id, leftover_msgs));
|
||||
}
|
||||
Err(err) => {
|
||||
if let Ok(panic) = err.try_into_panic() {
|
||||
error!("RemoteStateActor panicked.");
|
||||
std::panic::resume_unwind(panic);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// There's nothing to clean up.
|
||||
// Let's get woken when there's another task.
|
||||
// If we're called after that, then we'll fall into `poll_join_next` and
|
||||
// properly wait for a task to finish.
|
||||
self.tasks.poll_cleanup_waker.replace(cx.waker().clone());
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
/// Removes an actor sender if `leftover_msgs` is empty, or restarts the actor otherwise.
|
||||
fn remove_or_restart_actor(
|
||||
&mut self,
|
||||
remote_id: iroh_base::PublicKey,
|
||||
leftover_msgs: Vec<RemoteStateMessage>,
|
||||
) -> bool {
|
||||
if leftover_msgs.is_empty() {
|
||||
// the actor shut down cleanly
|
||||
self.senders.remove(&remote_id);
|
||||
trace!(%remote_id, "cleaned up RemoteStateActor");
|
||||
true
|
||||
} else {
|
||||
// The remote actor got messages while it was closing, so we're restarting
|
||||
trace!(%remote_id, "restarting terminated RemoteStateActor: messages received during shutdown");
|
||||
let sender =
|
||||
self.tasks
|
||||
.start_remote_state_actor(remote_id, leftover_msgs, &self.mapped_addrs);
|
||||
// We don't have to be careful about guards - only one thread is modifying this hashmap at a time.
|
||||
self.senders.insert(remote_id, sender);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn on_network_change(&mut self, is_major: bool) {
|
||||
let read = self.senders.read_only();
|
||||
let guard = read.guard();
|
||||
for sender in read.values(&guard) {
|
||||
sender
|
||||
.try_send(RemoteStateMessage::NetworkChange { is_major })
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve_remote(
|
||||
&mut self,
|
||||
addr: EndpointAddr,
|
||||
tx: oneshot::Sender<Result<(), AddressLookupFailed>>,
|
||||
) {
|
||||
let EndpointAddr { id, addrs } = addr;
|
||||
self.send_to_actor(id, RemoteStateMessage::ResolveRemote(addrs, tx))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn add_connection(
|
||||
&mut self,
|
||||
remote: EndpointId,
|
||||
conn: noq::Connection,
|
||||
tx: oneshot::Sender<PathStateReceiver>,
|
||||
) {
|
||||
self.send_to_actor(remote, RemoteStateMessage::AddConnection(conn, tx))
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sends a message to a `RemoteStateActor`, starting it if not running already.
|
||||
///
|
||||
/// When sending fails, the actor must be terminating, in which case we wait for its task to
|
||||
/// join and then restart the sender.
|
||||
async fn send_to_actor(&mut self, remote_id: EndpointId, message: RemoteStateMessage) {
|
||||
let sender = self.senders.get_or_insert_with(remote_id, || {
|
||||
self.tasks
|
||||
.start_remote_state_actor(remote_id, vec![], &self.mapped_addrs)
|
||||
});
|
||||
|
||||
if let Err(mpsc::error::SendError(message)) = sender.send(message).await {
|
||||
// The send failed, which means the RemoteStateActor is terminating. We call the cleanup
|
||||
// function so that its task is processed. This ensures that the leftover messages are
|
||||
// properly enqueued into a new actor, and that a later cleanup does not reap a newly
|
||||
// created sender again. We can be sure that the task has not been cleaned up yet
|
||||
// because we take a `&mut self` reference.
|
||||
loop {
|
||||
let (id, leftover_messages) = poll_fn(|cx| self.poll_join_next(cx)).await;
|
||||
if id != remote_id {
|
||||
self.remove_or_restart_actor(id, leftover_messages);
|
||||
} else {
|
||||
let mut messages = leftover_messages;
|
||||
messages.push(message);
|
||||
self.remove_or_restart_actor(id, messages);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn senders(&self) -> ReadOnlyMap<EndpointId, mpsc::Sender<RemoteStateMessage>> {
|
||||
self.senders.read_only()
|
||||
}
|
||||
}
|
||||
|
||||
impl Tasks {
|
||||
/// Starts a new remote state actor and returns a handle and a sender.
|
||||
///
|
||||
/// The handle is not inserted into the endpoint map, this must be done by the caller of this function.
|
||||
fn start_remote_state_actor(
|
||||
&mut self,
|
||||
eid: EndpointId,
|
||||
initial_msgs: Vec<RemoteStateMessage>,
|
||||
mapped_addrs: &MappedAddrs,
|
||||
) -> mpsc::Sender<RemoteStateMessage> {
|
||||
// Ensure there is a RemoteMappedAddr for this EndpointId.
|
||||
mapped_addrs.endpoint_addrs.get(&eid);
|
||||
let sender = RemoteStateActor::new(
|
||||
eid,
|
||||
self.local_direct_addrs.clone(),
|
||||
mapped_addrs.clone(),
|
||||
self.metrics.clone(),
|
||||
self.address_lookup.clone(),
|
||||
self.path_selector.clone(),
|
||||
)
|
||||
.start(
|
||||
initial_msgs,
|
||||
&mut self.tasks,
|
||||
self.shutdown_token.clone(),
|
||||
self.span.clone(),
|
||||
);
|
||||
if let Some(waker) = self.poll_cleanup_waker.take() {
|
||||
// Notify something waiting for changes to tasks when there's a new task.
|
||||
waker.wake();
|
||||
}
|
||||
sender
|
||||
}
|
||||
}
|
||||
|
||||
/// The origin or *source* through which an address associated with a remote endpoint
|
||||
/// was discovered.
|
||||
///
|
||||
/// An aggregate of the [`Source`]s of all the addresses of an endpoint describe the
|
||||
/// [`Source`]s of the endpoint itself.
|
||||
///
|
||||
/// A [`Source`] helps track how and where an address was learned. Multiple
|
||||
/// sources can be associated with a single address, if we have discovered this
|
||||
/// address through multiple means.
|
||||
#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)]
|
||||
#[strum(serialize_all = "kebab-case")]
|
||||
#[allow(private_interfaces)]
|
||||
#[non_exhaustive]
|
||||
pub(crate) enum Source {
|
||||
/// Application layer added the address directly.
|
||||
App,
|
||||
/// The address was discovered by an Address Lookup system
|
||||
#[strum(serialize = "{name}")]
|
||||
AddressLookup {
|
||||
/// The name of the Address Lookup that discovered the address.
|
||||
name: String,
|
||||
},
|
||||
/// The address was added as a path within a connection.
|
||||
Connection,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
|
||||
use iroh_base::{SecretKey, TransportAddr};
|
||||
use n0_future::future::now_or_never;
|
||||
use n0_tracing_test::traced_test;
|
||||
use n0_watcher::Watchable;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::Span;
|
||||
|
||||
use super::*;
|
||||
use crate::socket::biased_rtt_path_selector::BiasedRttPathSelector;
|
||||
|
||||
fn make_remote_map() -> (RemoteMap, CancellationToken, impl Sized) {
|
||||
let metrics = Arc::new(SocketMetrics::default());
|
||||
let watchable: Watchable<BTreeSet<DirectAddr>> = Watchable::new(BTreeSet::new());
|
||||
let local_direct_addrs = watchable.watch();
|
||||
let shutdown_token = CancellationToken::new();
|
||||
let remote_map = RemoteMap::new(
|
||||
metrics,
|
||||
local_direct_addrs,
|
||||
address_lookup::AddressLookupServices::default(),
|
||||
shutdown_token.clone(),
|
||||
Arc::new(BiasedRttPathSelector::default()),
|
||||
Span::none(),
|
||||
);
|
||||
let guards = (watchable, shutdown_token.clone().drop_guard());
|
||||
(remote_map, shutdown_token, guards)
|
||||
}
|
||||
|
||||
/// Regression test: No new RemoteStateActors may be started before
|
||||
/// the task of its previous incarnation was processed.
|
||||
#[tokio::test(flavor = "current_thread", start_paused = true)]
|
||||
#[traced_test]
|
||||
async fn poll_cleanup_preserves_restarted_sender() {
|
||||
let (mut remote_map, _shutdown_token, _guards) = make_remote_map();
|
||||
let eid = SecretKey::from_bytes(&[0u8; 32]).public();
|
||||
|
||||
// Non-empty addrs so each `resolve_remote` resolves its tx
|
||||
// immediately and does not park in `paths.pending_resolve_requests`;
|
||||
// the actor would never idle out otherwise.
|
||||
let addr_with_ip = |port: u16| {
|
||||
EndpointAddr::from_parts(
|
||||
eid,
|
||||
[TransportAddr::Ip(SocketAddr::from(([127, 0, 0, 1], port)))],
|
||||
)
|
||||
};
|
||||
|
||||
// 1. Spawn A1 and let it process a real `ResolveRemote`.
|
||||
let (tx1, rx1) = oneshot::channel();
|
||||
remote_map.resolve_remote(addr_with_ip(1234), tx1).await;
|
||||
assert!(
|
||||
matches!(rx1.await, Ok(Ok(()))),
|
||||
"First resolve completes Ok"
|
||||
);
|
||||
|
||||
// 2. Advance past idle timeout.
|
||||
tokio::time::sleep(Duration::from_secs(65)).await;
|
||||
|
||||
// 3. Call `resolve_remote` again. The actor A1 has terminated but its task
|
||||
// has not yet been cleaned up. A1's sender is still in the sender map
|
||||
// but is closed. This will spawn a new actor A2.
|
||||
// Before our fixes, `resolve_remote` would spawn a new actor, and when
|
||||
// `cleanup` was then called, the sender to this new actor would be
|
||||
// removed again. We fixed this by first processing the joined task for the
|
||||
// terminated actor, so that it is removed from our task list *before*
|
||||
// starting a new actor.
|
||||
// We also resume time here so that we don't immediately idle-out again.
|
||||
tokio::time::resume();
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
remote_map.resolve_remote(addr_with_ip(5678), tx2).await;
|
||||
|
||||
// 4. Drive `cleanup`, like the socket actor does.
|
||||
// Before our fixes, this would remove the sender to the just-started A2 from the sender map.
|
||||
now_or_never(remote_map.cleanup());
|
||||
|
||||
// 5. A third `resolve_remote`, this time with no addrs.
|
||||
// With our fix, this reaches the actor spawned above (A2); without
|
||||
// the fix this would start a new actor because A2 was falsely removed from
|
||||
// the senders map.
|
||||
let (tx3, rx3) = oneshot::channel();
|
||||
remote_map.resolve_remote(EndpointAddr::new(eid), tx3).await;
|
||||
|
||||
let outcome2 = rx2.await.expect("the resolve tx must be sent");
|
||||
let outcome3 = rx3.await.expect("the resolve tx must be sent");
|
||||
assert!(outcome2.is_ok(), "expected Ok, but got {outcome2:?}");
|
||||
assert!(outcome3.is_ok(), "expected Ok, but got {outcome3:?}");
|
||||
}
|
||||
}
|
||||
+1527
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,691 @@
|
||||
//! The state kept for each network path to a remote endpoint.
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, HashSet, VecDeque},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use n0_error::e;
|
||||
use n0_future::time::Instant;
|
||||
use rustc_hash::FxHashMap;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::trace;
|
||||
|
||||
use super::{Source, TransportAddrInfo, TransportAddrUsage};
|
||||
use crate::{address_lookup::AddressLookupFailed, metrics::SocketMetrics, socket::transports};
|
||||
|
||||
/// Maximum number of non-relay paths we keep around per endpoint.
|
||||
pub(super) const MAX_NON_RELAY_PATHS: usize = 30;
|
||||
|
||||
/// Maximum number of inactive non-relay paths we keep around per endpoint.
|
||||
///
|
||||
/// These are paths that at one point been opened and are now closed.
|
||||
pub(super) const MAX_INACTIVE_NON_RELAY_PATHS: usize = 10;
|
||||
|
||||
/// Map of all paths that we are aware of for a remote endpoint.
|
||||
///
|
||||
/// Also stores a list of resolve requests which are triggered once at least one path is known,
|
||||
/// or once this struct is notified of a failed Address Lookup run.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RemotePathState {
|
||||
/// All possible paths we are aware of.
|
||||
///
|
||||
/// These paths might be entirely impossible to use, since they are added by Address Lookup
|
||||
/// mechanisms. The are only potentially usable.
|
||||
paths: FxHashMap<transports::Addr, PathState>,
|
||||
/// Pending resolve requests from [`Self::resolve_remote`].
|
||||
pending_resolve_requests: VecDeque<oneshot::Sender<Result<(), AddressLookupFailed>>>,
|
||||
metrics: Arc<SocketMetrics>,
|
||||
}
|
||||
|
||||
/// Describes the usability of this path, i.e. whether it has ever been opened,
|
||||
/// when it was closed, or if it has never been usable.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) enum PathStatus {
|
||||
/// This path is open and active.
|
||||
Open,
|
||||
/// This path was once opened, but was abandoned at the given [`Instant`].
|
||||
Inactive(Instant),
|
||||
/// This path was never usable (we attempted holepunching and it didn't work).
|
||||
Unusable,
|
||||
/// We have not yet attempted holepunching, or holepunching is currently in
|
||||
/// progress, so we do not know the usability of this path.
|
||||
#[default]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl RemotePathState {
|
||||
pub(super) fn new(metrics: Arc<SocketMetrics>) -> Self {
|
||||
Self {
|
||||
paths: Default::default(),
|
||||
pending_resolve_requests: Default::default(),
|
||||
metrics,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_remote_addrs(&self) -> Vec<TransportAddrInfo> {
|
||||
self.paths
|
||||
.iter()
|
||||
.flat_map(|(addr, state)| {
|
||||
let usage = match state.status {
|
||||
PathStatus::Open => TransportAddrUsage::Active,
|
||||
PathStatus::Inactive(_) | PathStatus::Unusable | PathStatus::Unknown => {
|
||||
TransportAddrUsage::Inactive
|
||||
}
|
||||
};
|
||||
Some(TransportAddrInfo {
|
||||
addr: addr.clone().into(),
|
||||
usage,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Insert a new address of an open path into our list of paths.
|
||||
///
|
||||
/// This will emit pending resolve requests and trigger pruning paths.
|
||||
pub(super) fn insert_open_path(&mut self, addr: transports::Addr, source: Source) {
|
||||
match addr {
|
||||
transports::Addr::Ip(_) => self.metrics.transport_ip_paths_added.inc(),
|
||||
transports::Addr::Relay(_, _) => self.metrics.transport_relay_paths_added.inc(),
|
||||
transports::Addr::Custom(_) => self.metrics.transport_custom_paths_added.inc(),
|
||||
};
|
||||
let state = self.paths.entry(addr).or_default();
|
||||
state.status = PathStatus::Open;
|
||||
state.sources.insert(source.clone(), Instant::now());
|
||||
self.emit_pending_resolve_requests(None);
|
||||
self.prune_paths();
|
||||
}
|
||||
|
||||
/// Mark a path as abandoned.
|
||||
///
|
||||
/// If this path does not exist, it does nothing to the
|
||||
/// `RemotePathState`
|
||||
pub(super) fn abandoned_path(&mut self, addr: &transports::Addr) {
|
||||
if let Some(state) = self.paths.get_mut(addr) {
|
||||
if matches!(state.status, PathStatus::Open) {
|
||||
match addr {
|
||||
transports::Addr::Ip(_) => self.metrics.transport_ip_paths_removed.inc(),
|
||||
transports::Addr::Relay(_, _) => {
|
||||
self.metrics.transport_relay_paths_removed.inc()
|
||||
}
|
||||
transports::Addr::Custom(_) => {
|
||||
self.metrics.transport_custom_paths_removed.inc()
|
||||
}
|
||||
};
|
||||
}
|
||||
match state.status {
|
||||
PathStatus::Open | PathStatus::Inactive(_) => {
|
||||
state.status = PathStatus::Inactive(Instant::now());
|
||||
}
|
||||
PathStatus::Unusable | PathStatus::Unknown => {
|
||||
state.status = PathStatus::Unusable;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts multiple addresses of unknown status into our list of potential paths.
|
||||
///
|
||||
/// If this caused the path set to transition from empty to non-empty, any
|
||||
/// pending resolve requests are woken with `Ok(())`. Inserts that add no
|
||||
/// new paths (empty iterator, or only duplicates) are a no-op: waking
|
||||
/// pending requests while the path set is still empty would send a bogus
|
||||
/// `AddressLookupFailed::NoResults` while an address lookup is in flight.
|
||||
pub(super) fn insert_multiple(
|
||||
&mut self,
|
||||
addrs: impl Iterator<Item = transports::Addr>,
|
||||
source: Source,
|
||||
) {
|
||||
let now = Instant::now();
|
||||
let was_empty = self.paths.is_empty();
|
||||
for addr in addrs {
|
||||
self.paths
|
||||
.entry(addr)
|
||||
.or_default()
|
||||
.sources
|
||||
.insert(source.clone(), now);
|
||||
}
|
||||
trace!("added addressing information");
|
||||
if was_empty && !self.paths.is_empty() {
|
||||
self.emit_pending_resolve_requests(None);
|
||||
}
|
||||
self.prune_paths();
|
||||
}
|
||||
|
||||
/// Sends back on `tx` once a possible path to the remote is known.
|
||||
///
|
||||
/// If there already is a known path, `Ok(())` is returned immediately. Otherwise an
|
||||
/// address lookup is performed and the result is sent back once that
|
||||
/// completes. [`AddressLookupFailed`] is sent if there are no known paths.
|
||||
pub(super) fn resolve_remote(&mut self, tx: oneshot::Sender<Result<(), AddressLookupFailed>>) {
|
||||
if !self.paths.is_empty() {
|
||||
tx.send(Ok(())).ok();
|
||||
} else {
|
||||
self.pending_resolve_requests.push_back(tx);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if there are any queued resolve requests from [`Self::resolve_remote`].
|
||||
pub(super) fn resolve_requests_is_empty(&self) -> bool {
|
||||
self.pending_resolve_requests.is_empty()
|
||||
}
|
||||
|
||||
/// Notifies that a Address Lookup run has finished.
|
||||
///
|
||||
/// This will emit pending resolve requests.
|
||||
pub(super) fn address_lookup_finished(&mut self, result: Result<(), AddressLookupFailed>) {
|
||||
self.emit_pending_resolve_requests(result.err());
|
||||
}
|
||||
|
||||
/// Returns an iterator over the addresses of all paths.
|
||||
pub(super) fn addrs(&self) -> impl Iterator<Item = &transports::Addr> {
|
||||
self.paths.keys()
|
||||
}
|
||||
|
||||
/// Returns whether this stores any addresses.
|
||||
pub(super) fn is_empty(&self) -> bool {
|
||||
self.paths.is_empty()
|
||||
}
|
||||
|
||||
/// Replies to all pending resolve requests.
|
||||
///
|
||||
/// This is a no-op if no requests are queued. Replies `Ok` if we have any known paths,
|
||||
/// otherwise with the provided `address_lookup_error` or with [`AddressLookupFailed::NoResults`].
|
||||
fn emit_pending_resolve_requests(&mut self, address_lookup_error: Option<AddressLookupFailed>) {
|
||||
if self.pending_resolve_requests.is_empty() {
|
||||
return;
|
||||
}
|
||||
let result = match (self.paths.is_empty(), address_lookup_error) {
|
||||
(false, _) => Ok(()),
|
||||
(true, Some(err)) => Err(err),
|
||||
(true, None) => Err(e!(AddressLookupFailed::NoResults { errors: Vec::new() })),
|
||||
};
|
||||
for tx in self.pending_resolve_requests.drain(..) {
|
||||
tx.send(result.clone()).ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Prune paths.
|
||||
///
|
||||
/// Should be invoked any time we insert a new path.
|
||||
///
|
||||
/// We currently only prune non-relay paths. For more information on the
|
||||
/// criteria for when and which paths we prune, look at the [`prune_non_relay_paths`] function.
|
||||
pub(super) fn prune_paths(&mut self) {
|
||||
prune_non_relay_paths(&mut self.paths);
|
||||
}
|
||||
}
|
||||
|
||||
/// The state of a single path to the remote endpoint.
|
||||
///
|
||||
/// Each path is identified by the destination [`transports::Addr`] and they are stored in
|
||||
/// the [`RemotePathState`] map in [`RemoteStateActor`].
|
||||
///
|
||||
/// [`RemoteStateActor`]: super::RemoteStateActor
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct PathState {
|
||||
/// How we learned about this path, and when.
|
||||
///
|
||||
/// We keep track of only the latest [`Instant`] for each [`Source`], keeping the size
|
||||
/// of the map of sources down to one entry per type of source.
|
||||
pub(super) sources: HashMap<Source, Instant>,
|
||||
/// The usability status of this path.
|
||||
pub(super) status: PathStatus,
|
||||
}
|
||||
|
||||
/// Prunes the non-relay paths in the paths HashMap.
|
||||
///
|
||||
/// Only prunes if the number of non-relay paths is above [`MAX_NON_RELAY_PATHS`].
|
||||
///
|
||||
/// Keeps paths that are open or of unknown status.
|
||||
///
|
||||
/// Always prunes paths that have unsuccessfully holepunched.
|
||||
///
|
||||
/// Keeps [`MAX_INACTIVE_NON_RELAY_PATHS`] of the most recently closed paths
|
||||
/// that are not currently being used but have successfully been
|
||||
/// holepunched previously.
|
||||
///
|
||||
/// This all ensures that:
|
||||
///
|
||||
/// - We do not have unbounded growth of paths.
|
||||
/// - If we have many paths for this remote, we prune the paths that cannot hole punch.
|
||||
/// - We do not prune holepunched paths that are currently not in use too quickly. For
|
||||
/// example, if a large number of untested paths are added at once, we will not
|
||||
/// immediately prune all of the unused, but valid, paths at once.
|
||||
fn prune_non_relay_paths(paths: &mut FxHashMap<transports::Addr, PathState>) {
|
||||
// if the total number of paths is less than the max, bail early
|
||||
if paths.len() < MAX_NON_RELAY_PATHS {
|
||||
return;
|
||||
}
|
||||
|
||||
let primary_paths: Vec<_> = paths.iter().filter(|(addr, _)| !addr.is_relay()).collect();
|
||||
|
||||
// if the total number of non-relay paths is less than the max, bail early
|
||||
if primary_paths.len() < MAX_NON_RELAY_PATHS {
|
||||
return;
|
||||
}
|
||||
|
||||
// paths that were opened at one point but have previously been closed
|
||||
let mut inactive = Vec::with_capacity(primary_paths.len());
|
||||
// paths where we attempted hole punching but it not successful
|
||||
let mut failed = Vec::with_capacity(primary_paths.len());
|
||||
|
||||
for (addr, state) in primary_paths {
|
||||
match state.status {
|
||||
PathStatus::Inactive(t) => {
|
||||
// paths where holepunching succeeded at one point, but the path was closed.
|
||||
inactive.push((addr.clone(), t));
|
||||
}
|
||||
PathStatus::Unusable => {
|
||||
// paths where holepunching has been attempted and failed.
|
||||
failed.push(addr.clone());
|
||||
}
|
||||
_ => {
|
||||
// ignore paths that are open or the status is unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All paths are bad, don't prune all of them.
|
||||
//
|
||||
// This implies that `inactive` is empty.
|
||||
if failed.len() == paths.len() {
|
||||
// leave the max number of non-relay paths
|
||||
failed.truncate(paths.len().saturating_sub(MAX_NON_RELAY_PATHS));
|
||||
}
|
||||
|
||||
// sort the potentially prunable from most recently closed to least recently closed
|
||||
inactive.sort_by_key(|b| std::cmp::Reverse(b.1));
|
||||
|
||||
// Prune the "oldest" closed paths.
|
||||
let old_inactive =
|
||||
inactive.split_off(inactive.len().saturating_sub(MAX_INACTIVE_NON_RELAY_PATHS));
|
||||
|
||||
// collect all the paths that should be pruned
|
||||
let must_prune: HashSet<_> = failed
|
||||
.into_iter()
|
||||
.chain(old_inactive.into_iter().map(|(addr, _)| addr))
|
||||
.collect();
|
||||
|
||||
paths.retain(|addr, _| !must_prune.contains(addr));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
net::{Ipv4Addr, SocketAddrV4},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use iroh_base::{RelayUrl, SecretKey};
|
||||
use rand::{RngExt, SeedableRng};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn ip_addr(port: u16) -> transports::Addr {
|
||||
transports::Addr::Ip(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port).into())
|
||||
}
|
||||
|
||||
fn path_state_inactive(closed: Instant) -> PathState {
|
||||
PathState {
|
||||
sources: HashMap::new(),
|
||||
status: PathStatus::Inactive(closed),
|
||||
}
|
||||
}
|
||||
|
||||
fn path_state_unusable() -> PathState {
|
||||
PathState {
|
||||
sources: HashMap::new(),
|
||||
status: PathStatus::Unusable,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_under_max_paths() {
|
||||
let mut paths = FxHashMap::default();
|
||||
for i in 0..20 {
|
||||
paths.insert(ip_addr(i), PathState::default());
|
||||
}
|
||||
|
||||
prune_non_relay_paths(&mut paths);
|
||||
assert_eq!(
|
||||
20,
|
||||
paths.len(),
|
||||
"should not prune when under MAX_NON_RELAY_PATHS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_at_max_paths_no_prunable() {
|
||||
let mut paths = FxHashMap::default();
|
||||
// All paths are active (never abandoned), so none should be pruned
|
||||
for i in 0..MAX_NON_RELAY_PATHS {
|
||||
paths.insert(ip_addr(i as u16), PathState::default());
|
||||
}
|
||||
|
||||
prune_non_relay_paths(&mut paths);
|
||||
assert_eq!(
|
||||
MAX_NON_RELAY_PATHS,
|
||||
paths.len(),
|
||||
"should not prune active paths"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_failed_holepunch() {
|
||||
let mut paths = FxHashMap::default();
|
||||
|
||||
// Add 20 active paths
|
||||
for i in 0..20 {
|
||||
paths.insert(ip_addr(i), PathState::default());
|
||||
}
|
||||
|
||||
// Add 15 failed holepunch paths (must_prune)
|
||||
for i in 20..35 {
|
||||
paths.insert(ip_addr(i), path_state_unusable());
|
||||
}
|
||||
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// All failed holepunch paths should be pruned
|
||||
assert_eq!(20, paths.len());
|
||||
for i in 0..20 {
|
||||
assert!(paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
for i in 20..35 {
|
||||
assert!(!paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_keeps_most_recent_inactive() {
|
||||
let mut paths = FxHashMap::default();
|
||||
let now = Instant::now();
|
||||
|
||||
// Add 15 active paths
|
||||
for i in 0..15 {
|
||||
paths.insert(ip_addr(i), PathState::default());
|
||||
}
|
||||
|
||||
// Add 20 inactive paths with different abandon times
|
||||
// Ports 15-34, with port 34 being most recently abandoned
|
||||
for i in 0..20 {
|
||||
let abandoned_time = now - Duration::from_secs((20 - i) as u64);
|
||||
paths.insert(ip_addr(15 + i as u16), path_state_inactive(abandoned_time));
|
||||
}
|
||||
|
||||
assert_eq!(35, paths.len());
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// Should keep 15 active + 10 most recently abandoned
|
||||
assert_eq!(25, paths.len());
|
||||
|
||||
// Active paths should remain
|
||||
for i in 0..15 {
|
||||
assert!(paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
|
||||
// Most recently abandoned (ports 25-34) should remain
|
||||
for i in 25..35 {
|
||||
assert!(paths.contains_key(&ip_addr(i)), "port {} should be kept", i);
|
||||
}
|
||||
|
||||
// Oldest abandoned (ports 15-24) should be pruned
|
||||
for i in 15..25 {
|
||||
assert!(
|
||||
!paths.contains_key(&ip_addr(i)),
|
||||
"port {} should be pruned",
|
||||
i
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_mixed_must_and_can_prune() {
|
||||
let mut paths = FxHashMap::default();
|
||||
let now = Instant::now();
|
||||
|
||||
// Add 15 active paths
|
||||
for i in 0..15 {
|
||||
paths.insert(ip_addr(i), PathState::default());
|
||||
}
|
||||
|
||||
// Add 5 failed holepunch paths
|
||||
for i in 15..20 {
|
||||
paths.insert(ip_addr(i), path_state_unusable());
|
||||
}
|
||||
|
||||
// Add 15 usable but abandoned paths
|
||||
for i in 0..15 {
|
||||
let abandoned_time = now - Duration::from_secs((15 - i) as u64);
|
||||
paths.insert(ip_addr(20 + i as u16), path_state_inactive(abandoned_time));
|
||||
}
|
||||
|
||||
assert_eq!(35, paths.len());
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// Remove all failed paths -> down to 30
|
||||
// Keep MAX_INACTIVE_NON_RELAY_PATHS, eg remove 5 usable but abandoned paths -> down to 20
|
||||
assert_eq!(20, paths.len());
|
||||
|
||||
// Active paths should remain
|
||||
for i in 0..15 {
|
||||
assert!(paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
|
||||
// Failed holepunch should be pruned
|
||||
for i in 15..20 {
|
||||
assert!(!paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
|
||||
// Most recently abandoned (ports 30-34) should remain
|
||||
for i in 30..35 {
|
||||
assert!(paths.contains_key(&ip_addr(i)), "port {} should be kept", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_relay_paths_not_counted() {
|
||||
let mut paths = FxHashMap::default();
|
||||
|
||||
// Add 25 IP paths (under MAX_NON_RELAY_PATHS)
|
||||
for i in 0..25 {
|
||||
paths.insert(ip_addr(i), path_state_unusable());
|
||||
}
|
||||
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
|
||||
let relay_url: RelayUrl = url::Url::parse("https://localhost")
|
||||
.expect("should be valid url")
|
||||
.into();
|
||||
// Add 10 relay addresses
|
||||
for _ in 0..10 {
|
||||
let id = SecretKey::from_bytes(&rng.random()).public();
|
||||
let relay_addr = transports::Addr::Relay(relay_url.clone(), id);
|
||||
paths.insert(relay_addr, PathState::default());
|
||||
}
|
||||
|
||||
assert_eq!(35, paths.len()); // 25 IP + 10 relay
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// Should not prune since non-relay paths < MAX_NON_RELAY_PATHS
|
||||
assert_eq!(35, paths.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_preserves_never_dialed() {
|
||||
let mut paths = FxHashMap::default();
|
||||
|
||||
// Add 20 never-dialed paths (PathStatus::Unknown)
|
||||
for i in 0..20 {
|
||||
paths.insert(ip_addr(i), PathState::default());
|
||||
}
|
||||
|
||||
// Add 15 failed paths to trigger pruning
|
||||
for i in 20..35 {
|
||||
paths.insert(ip_addr(i), path_state_unusable());
|
||||
}
|
||||
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// Never-dialed paths should be preserved
|
||||
for i in 0..20 {
|
||||
assert!(paths.contains_key(&ip_addr(i)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_prune_all_paths_failed() {
|
||||
let mut paths = FxHashMap::default();
|
||||
|
||||
// Add 40 failed holepunch paths (all paths have failed)
|
||||
for i in 0..40 {
|
||||
paths.insert(ip_addr(i), path_state_unusable());
|
||||
}
|
||||
|
||||
assert_eq!(40, paths.len());
|
||||
prune_non_relay_paths(&mut paths);
|
||||
|
||||
// Should keep MAX_NON_RELAY_PATHS instead of pruning everything
|
||||
// This prevents catastrophic loss of all path information
|
||||
assert_eq!(
|
||||
MAX_NON_RELAY_PATHS,
|
||||
paths.len(),
|
||||
"should keep MAX_NON_RELAY_PATHS when all paths failed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert_open_path() {
|
||||
let mut state = RemotePathState::new(Default::default());
|
||||
let addr = ip_addr(1000);
|
||||
let source = Source::Connection;
|
||||
|
||||
assert!(state.is_empty());
|
||||
|
||||
state.insert_open_path(addr.clone(), source.clone());
|
||||
|
||||
assert!(!state.is_empty());
|
||||
assert!(state.paths.contains_key(&addr));
|
||||
let path = &state.paths[&addr];
|
||||
assert!(matches!(path.status, PathStatus::Open));
|
||||
assert_eq!(path.sources.len(), 1);
|
||||
assert!(path.sources.contains_key(&source));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_abandoned_path() {
|
||||
let metrics = Arc::new(SocketMetrics::default());
|
||||
let mut state = RemotePathState::new(metrics.clone());
|
||||
|
||||
// Test: Open goes to Inactive
|
||||
let addr_open = ip_addr(1000);
|
||||
state.insert_open_path(addr_open.clone(), Source::Connection);
|
||||
assert!(matches!(state.paths[&addr_open].status, PathStatus::Open));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
|
||||
state.abandoned_path(&addr_open);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_open].status,
|
||||
PathStatus::Inactive(_)
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
|
||||
// Test: Inactive stays Inactive
|
||||
state.abandoned_path(&addr_open);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_open].status,
|
||||
PathStatus::Inactive(_)
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
|
||||
// Test: Unknown goes to Unusable
|
||||
let addr_unknown = ip_addr(2000);
|
||||
state.insert_multiple([addr_unknown.clone()].into_iter(), Source::Connection);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_unknown].status,
|
||||
PathStatus::Unknown
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
|
||||
state.abandoned_path(&addr_unknown);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_unknown].status,
|
||||
PathStatus::Unusable
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
|
||||
// Test: Unusable stays Unusable
|
||||
state.abandoned_path(&addr_unknown);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_unknown].status,
|
||||
PathStatus::Unusable
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 1);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
|
||||
// Test: Unusable can go to open
|
||||
state.insert_open_path(addr_unknown.clone(), Source::Connection);
|
||||
assert!(matches!(
|
||||
state.paths[&addr_unknown].status,
|
||||
PathStatus::Open
|
||||
));
|
||||
assert_eq!(metrics.transport_ip_paths_added.get(), 2);
|
||||
assert_eq!(metrics.transport_ip_paths_removed.get(), 1);
|
||||
}
|
||||
|
||||
/// An empty `insert_multiple` must not drain pending resolve requests.
|
||||
///
|
||||
/// This reproduces the race where multiple concurrent `connect_with_opts`
|
||||
/// calls send `ResolveRemote` messages with empty addrs. The first pushes
|
||||
/// a tx, then the second's `insert_multiple([])` used to drain that tx
|
||||
/// with `NoResults { errors: [] }`, even though an address lookup was
|
||||
/// still in flight and would shortly have resolved it.
|
||||
#[test]
|
||||
fn empty_insert_does_not_drain_pending() {
|
||||
let metrics = Arc::new(SocketMetrics::default());
|
||||
let mut state = RemotePathState::new(metrics);
|
||||
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
state.resolve_remote(tx);
|
||||
|
||||
// Second concurrent resolve arrives with empty addrs (no app-provided
|
||||
// addresses) while address lookup is still running.
|
||||
state.insert_multiple(std::iter::empty(), Source::App);
|
||||
|
||||
assert!(
|
||||
rx.try_recv().is_err(),
|
||||
"pending tx must stay pending while paths are empty and lookup is in flight"
|
||||
);
|
||||
|
||||
// When real addresses arrive, the tx resolves Ok.
|
||||
state.insert_multiple([ip_addr(4242)].into_iter(), Source::App);
|
||||
let resolved = rx.try_recv().expect("tx should have been woken");
|
||||
assert!(resolved.is_ok(), "expected Ok once a path was added");
|
||||
}
|
||||
|
||||
/// `address_lookup_finished(Ok(()))` drains pending requests with `NoResults` when no paths are known.
|
||||
///
|
||||
/// This is the "lookup done but nothing was found" signal and it must
|
||||
/// still reach callers.
|
||||
#[test]
|
||||
fn address_lookup_finished_empty_emits_no_results() {
|
||||
let metrics = Arc::new(SocketMetrics::default());
|
||||
let mut state = RemotePathState::new(metrics);
|
||||
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
state.resolve_remote(tx);
|
||||
|
||||
state.address_lookup_finished(Ok(()));
|
||||
|
||||
let resolved = rx.try_recv().expect("tx should have been woken");
|
||||
assert!(matches!(
|
||||
resolved,
|
||||
Err(AddressLookupFailed::NoResults { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
//! Path observation for a [`Connection`].
|
||||
//!
|
||||
//! [`Connection::paths`] returns a borrowed [`PathList`] with live
|
||||
//! statistics. [`Connection::path_events`] returns a `'static` stream
|
||||
//! of [`PathEvent`]s. Subscribing to the event stream before reading
|
||||
//! the snapshot ensures any change that happens between the read and
|
||||
//! the next poll is observed by the subscriber.
|
||||
//!
|
||||
//! Closed paths are not retained in [`PathList`]; their final
|
||||
//! statistics arrive inline on [`PathEvent::Closed`].
|
||||
//!
|
||||
//! # Internal structure
|
||||
//!
|
||||
//! [`PathStateSender`] (owned by the [`RemoteStateActor`]) and
|
||||
//! [`PathStateReceiver`] (held by the [`Connection`]) share a
|
||||
//! [`Mutex`]`<`[`State`]`>`, a [`Notify`], and a [`broadcast`] channel.
|
||||
//! The receiver holds a [`WeakSender`]; when the actor drops the
|
||||
//! sender, outstanding event streams end.
|
||||
//!
|
||||
//! [`Connection`]: crate::endpoint::Connection
|
||||
//! [`Connection::paths`]: crate::endpoint::Connection::paths
|
||||
//! [`Connection::path_events`]: crate::endpoint::Connection::path_events
|
||||
//! [`RemoteStateActor`]: super::RemoteStateActor
|
||||
//! [`WeakSender`]: broadcast::WeakSender
|
||||
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use iroh_base::TransportAddr;
|
||||
use n0_future::{StreamExt, time::Duration};
|
||||
use noq::WeakPathHandle;
|
||||
use noq_proto::PathId;
|
||||
use smallvec::SmallVec;
|
||||
use tokio::sync::{Notify, broadcast, futures::Notified};
|
||||
use tokio_stream::{
|
||||
Stream,
|
||||
wrappers::{BroadcastStream, errors::BroadcastStreamRecvError},
|
||||
};
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{
|
||||
endpoint::PathStats,
|
||||
socket::transports::{self, LocalTransportAddr},
|
||||
};
|
||||
|
||||
/// Per-connection broadcast channel capacity for path events.
|
||||
const BROADCAST_CAPACITY: usize = 8;
|
||||
|
||||
/// Lifecycle notifications for a transmission paths in a connection.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum PathEvent {
|
||||
/// A new network path was opened.
|
||||
#[non_exhaustive]
|
||||
Opened {
|
||||
/// Path identifier.
|
||||
id: PathId,
|
||||
/// Remote transport address.
|
||||
remote_addr: TransportAddr,
|
||||
/// Local address of the path, if known.
|
||||
local_addr: LocalTransportAddr,
|
||||
},
|
||||
/// A network path was closed.
|
||||
#[non_exhaustive]
|
||||
Closed {
|
||||
/// Path identifier.
|
||||
id: PathId,
|
||||
/// Remote transport address.
|
||||
remote_addr: TransportAddr,
|
||||
/// Local address of the path, if known.
|
||||
local_addr: LocalTransportAddr,
|
||||
/// Path statistics captured at close time.
|
||||
last_stats: Box<PathStats>,
|
||||
},
|
||||
/// This path was selected for transmission of application data.
|
||||
#[non_exhaustive]
|
||||
Selected {
|
||||
/// Path identifier of the newly selected path.
|
||||
id: PathId,
|
||||
/// Remote transport address of the newly selected path.
|
||||
remote_addr: TransportAddr,
|
||||
/// The local address of the newly selected path, if known.
|
||||
local_addr: LocalTransportAddr,
|
||||
},
|
||||
/// Events were dropped before the subscriber received them.
|
||||
///
|
||||
/// Yielded when the subscriber does not poll the stream fast
|
||||
/// enough to keep up with the writer. The current set of open
|
||||
/// paths and the selected path remain accessible via
|
||||
/// [`Connection::paths`].
|
||||
///
|
||||
/// [`Connection::paths`]: crate::endpoint::Connection::paths
|
||||
#[non_exhaustive]
|
||||
Lagged {
|
||||
/// Number of events dropped since the last delivered event.
|
||||
missed: u64,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, derive_more::Debug)]
|
||||
#[debug("PathData({}, {})", self.handle.id(), self.remote_addr)]
|
||||
struct PathData {
|
||||
handle: WeakPathHandle,
|
||||
remote_addr: TransportAddr,
|
||||
local_addr: LocalTransportAddr,
|
||||
}
|
||||
|
||||
impl PathData {
|
||||
/// Returns a strong [`noq::Path`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This may panic if the passed `noq::Connection` is not the one to which this path belongs.
|
||||
fn upgrade(&self, _conn: &noq::Connection) -> noq::Path {
|
||||
self.handle
|
||||
.upgrade()
|
||||
.expect("Wrong Connection reference passed to PathData::upgrade")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
struct State {
|
||||
list: SmallVec<[PathData; 4]>,
|
||||
selected: Option<PathId>,
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
notify: Notify,
|
||||
}
|
||||
|
||||
/// The writer-side handle for a connection's path state.
|
||||
///
|
||||
/// Owned by the [`RemoteStateActor`]; the only handle that mutates
|
||||
/// state and emits events. When dropped, every outstanding
|
||||
/// [`PathEventStream`] ends.
|
||||
///
|
||||
/// [`RemoteStateActor`]: super::RemoteStateActor
|
||||
#[derive(Debug)]
|
||||
pub(super) struct PathStateSender {
|
||||
shared: Arc<Shared>,
|
||||
events: broadcast::Sender<PathEvent>,
|
||||
}
|
||||
|
||||
impl PathStateSender {
|
||||
/// Creates a sender/receiver pair sharing empty state.
|
||||
///
|
||||
/// Gets passed a clone of the custom address map, so that we can convert local addresses
|
||||
/// to the public [`LocalTransportAddr`] exposed to users.
|
||||
pub(super) fn new() -> (Self, PathStateReceiver) {
|
||||
let (events, _) = broadcast::channel(BROADCAST_CAPACITY);
|
||||
let shared = Arc::new(Shared {
|
||||
state: Default::default(),
|
||||
notify: Notify::new(),
|
||||
});
|
||||
let receiver = PathStateReceiver {
|
||||
shared: shared.clone(),
|
||||
events: events.downgrade(),
|
||||
};
|
||||
let sender = PathStateSender { shared, events };
|
||||
(sender, receiver)
|
||||
}
|
||||
|
||||
/// Records a newly-opened path and emits [`PathEvent::Opened`].
|
||||
pub(super) fn record_opened(
|
||||
&self,
|
||||
handle: WeakPathHandle,
|
||||
network_path: transports::FourTuple,
|
||||
) {
|
||||
let id = handle.id();
|
||||
let remote_addr: TransportAddr = network_path.remote().into();
|
||||
let local_addr = network_path.local();
|
||||
{
|
||||
let mut state = self.shared.state.lock().expect("poisoned");
|
||||
let entry = PathData {
|
||||
handle,
|
||||
remote_addr: remote_addr.clone(),
|
||||
local_addr: local_addr.clone(),
|
||||
};
|
||||
match state.list.iter().position(|e| e.handle.id() == id) {
|
||||
Some(idx) => state.list[idx] = entry,
|
||||
None => state.list.push(entry),
|
||||
}
|
||||
}
|
||||
self.shared.notify.notify_waiters();
|
||||
let _ = self.events.send(PathEvent::Opened {
|
||||
id,
|
||||
remote_addr,
|
||||
local_addr,
|
||||
});
|
||||
}
|
||||
|
||||
/// Records that a path was abandoned by `noq`.
|
||||
pub(super) fn record_abandoned(&self, id: PathId, conn: &noq::Connection) {
|
||||
let removed = {
|
||||
let mut state = self.shared.state.lock().expect("poisoned");
|
||||
if state.selected == Some(id) {
|
||||
state.selected = None;
|
||||
}
|
||||
state
|
||||
.list
|
||||
.iter()
|
||||
.position(|e| e.handle.id() == id)
|
||||
.map(|pos| state.list.remove(pos))
|
||||
};
|
||||
if let Some(data) = removed {
|
||||
let stats = data.upgrade(conn).stats();
|
||||
self.shared.notify.notify_waiters();
|
||||
let _ = self.events.send(PathEvent::Closed {
|
||||
id,
|
||||
remote_addr: data.remote_addr.clone(),
|
||||
local_addr: data.local_addr.clone(),
|
||||
last_stats: Box::new(stats),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the selected transmission path.
|
||||
pub(super) fn record_selected(&self, network_path: &transports::FourTuple) {
|
||||
let remote_addr: TransportAddr = network_path.remote().into();
|
||||
let local_addr = network_path.local();
|
||||
let event = {
|
||||
let mut state = self.shared.state.lock().expect("poisoned");
|
||||
let selected_path_id = state
|
||||
.list
|
||||
.iter()
|
||||
.find(|p| p.remote_addr == remote_addr && p.local_addr == local_addr)
|
||||
.map(|p| p.handle.id());
|
||||
if selected_path_id != state.selected {
|
||||
state.selected = selected_path_id;
|
||||
selected_path_id.map(|path_id| PathEvent::Selected {
|
||||
id: path_id,
|
||||
remote_addr: remote_addr.clone(),
|
||||
local_addr: local_addr.clone(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(event) = event {
|
||||
let _ = self.events.send(event);
|
||||
self.shared.notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the writer side of the path observation.
|
||||
///
|
||||
/// Emits a final [`PathEvent::Closed`] for every remaining open
|
||||
/// path with its statistics taken from `closed.path_stats`, marks
|
||||
/// the state closed, and drops the sender. No-op if already closed.
|
||||
///
|
||||
/// [`WeakPathHandle`]: noq::WeakPathHandle
|
||||
pub(super) fn close(self, closed: noq::Closed) {
|
||||
let mut state = self.shared.state.lock().expect("poisoned");
|
||||
if !state.closed {
|
||||
for path in state.list.iter() {
|
||||
if let Some(stats) = closed
|
||||
.path_stats
|
||||
.iter()
|
||||
.find(|(id, _stats)| *id == path.handle.id())
|
||||
.map(|(_id, stats)| stats)
|
||||
{
|
||||
let _ = self.events.send(PathEvent::Closed {
|
||||
id: path.handle.id(),
|
||||
remote_addr: path.remote_addr.clone(),
|
||||
local_addr: path.local_addr.clone(),
|
||||
last_stats: Box::new(*stats),
|
||||
});
|
||||
} else {
|
||||
warn!(
|
||||
"Connection close event is missing path stats for path {}",
|
||||
path.handle.id()
|
||||
);
|
||||
}
|
||||
}
|
||||
state.closed = true;
|
||||
self.shared.notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PathStateSender {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.shared.state.lock().expect("poisoned");
|
||||
if !state.closed {
|
||||
state.closed = true;
|
||||
self.shared.notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reader-side handle for a connection's path state.
|
||||
///
|
||||
/// Held by a [`Connection`]. Cheap to clone.
|
||||
///
|
||||
/// [`Connection`]: crate::endpoint::Connection
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct PathStateReceiver {
|
||||
shared: Arc<Shared>,
|
||||
events: broadcast::WeakSender<PathEvent>,
|
||||
}
|
||||
|
||||
impl PathStateReceiver {
|
||||
/// Returns a snapshot of the currently-open paths, tied to `conn`.
|
||||
pub(crate) fn get<'a>(&self, conn: &'a noq::Connection) -> PathList<'a> {
|
||||
PathList {
|
||||
snapshot: self.shared.state.lock().expect("poisoned").clone(),
|
||||
conn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a stream of [`PathEvent`]s.
|
||||
///
|
||||
/// Already closed if the sender has been dropped.
|
||||
pub(crate) fn events(&self) -> PathEventStream {
|
||||
let receiver = if let Some(sender) = self.events.upgrade() {
|
||||
sender.subscribe()
|
||||
} else {
|
||||
let (_tx, rx) = broadcast::channel(1);
|
||||
rx
|
||||
};
|
||||
PathEventStream {
|
||||
inner: BroadcastStream::new(receiver),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a stream of [`PathList`] snapshots tied to `conn`.
|
||||
///
|
||||
/// Yields the current snapshot on the first poll, then a fresh
|
||||
/// snapshot on every state change. Ends when the state is marked
|
||||
/// closed.
|
||||
pub(crate) fn stream<'a>(&'a self, conn: &'a noq::Connection) -> PathListStream<'a> {
|
||||
PathListStream {
|
||||
shared: &self.shared,
|
||||
conn,
|
||||
notified: Box::pin(self.shared.notify.notified()),
|
||||
first_poll: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed snapshot of a connection's currently-open paths.
|
||||
///
|
||||
/// Returned by [`Connection::paths`]. The list is captured at call
|
||||
/// time and does not reflect later changes. Closed paths are not
|
||||
/// retained; to track per-path totals over the connection's lifetime,
|
||||
/// accumulate from [`PathEvent::Closed`].
|
||||
///
|
||||
/// [`Connection::paths`]: crate::endpoint::Connection::paths
|
||||
#[derive(Clone, derive_more::Debug)]
|
||||
pub struct PathList<'conn> {
|
||||
snapshot: State,
|
||||
#[debug(skip)]
|
||||
conn: &'conn noq::Connection,
|
||||
}
|
||||
|
||||
impl<'conn> PathList<'conn> {
|
||||
/// Returns the number of open paths.
|
||||
pub fn len(&self) -> usize {
|
||||
self.snapshot.list.len()
|
||||
}
|
||||
|
||||
/// Returns `true` if no paths are open.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.snapshot.list.is_empty()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the open paths.
|
||||
pub fn iter(&self) -> PathListIter<'_> {
|
||||
PathListIter {
|
||||
inner: self.snapshot.list.iter(),
|
||||
selected: self.snapshot.selected,
|
||||
conn: self.conn,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path with the given [`PathId`].
|
||||
///
|
||||
/// Returns `None` if no open path with that id is present in
|
||||
/// this snapshot.
|
||||
pub fn get(&self, id: PathId) -> Option<Path<'_>> {
|
||||
self.iter().find(|p| p.id() == id)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a PathList<'a> {
|
||||
type IntoIter = PathListIter<'a>;
|
||||
type Item = Path<'a>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// An iterator over the open paths in a [`PathList`] snapshot.
|
||||
#[derive(Debug)]
|
||||
pub struct PathListIter<'a> {
|
||||
inner: std::slice::Iter<'a, PathData>,
|
||||
selected: Option<PathId>,
|
||||
conn: &'a noq::Connection,
|
||||
}
|
||||
|
||||
impl<'a> PathListIter<'a> {
|
||||
fn item(&self, data: &'a PathData) -> Path<'a> {
|
||||
Path {
|
||||
data,
|
||||
is_selected: self.selected == Some(data.handle.id()),
|
||||
conn: self.conn,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for PathListIter<'a> {
|
||||
type Item = Path<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.inner.next().map(|d| self.item(d))
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
self.inner.size_hint()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DoubleEndedIterator for PathListIter<'a> {
|
||||
fn next_back(&mut self) -> Option<Self::Item> {
|
||||
self.inner.next_back().map(|d| self.item(d))
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for PathListIter<'_> {}
|
||||
|
||||
/// A single path within a [`PathList`] snapshot.
|
||||
///
|
||||
/// Borrows from the enclosing [`PathList`] and from the [`Connection`]
|
||||
/// that produced it, so a [`Path`] cannot cross a task boundary. If you need
|
||||
/// to send path data to other tasks, you can clone [`Self::remote_addr`] or
|
||||
/// [`Self::stats`] into an owned value first.
|
||||
///
|
||||
/// [`Connection`]: crate::endpoint::Connection
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Path<'a> {
|
||||
data: &'a PathData,
|
||||
is_selected: bool,
|
||||
/// Reference to a `noq::Connection` for safe upgrading via [`PathData::upgrade`]
|
||||
conn: &'a noq::Connection,
|
||||
}
|
||||
|
||||
impl<'conn> Path<'conn> {
|
||||
/// Returns the path's [`PathId`].
|
||||
pub fn id(&self) -> PathId {
|
||||
self.data.handle.id()
|
||||
}
|
||||
|
||||
/// Returns the path's remote transport address.
|
||||
pub fn remote_addr(&self) -> &TransportAddr {
|
||||
&self.data.remote_addr
|
||||
}
|
||||
|
||||
/// Returns the path's local address, if known.
|
||||
pub fn local_addr(&self) -> &LocalTransportAddr {
|
||||
&self.data.local_addr
|
||||
}
|
||||
|
||||
/// Returns `true` if this path is currently selected for application data transmission.
|
||||
pub fn is_selected(&self) -> bool {
|
||||
self.is_selected
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a direct IP path.
|
||||
pub fn is_ip(&self) -> bool {
|
||||
self.data.remote_addr.is_ip()
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a relay path.
|
||||
pub fn is_relay(&self) -> bool {
|
||||
self.data.remote_addr.is_relay()
|
||||
}
|
||||
|
||||
/// Returns the path's statistics.
|
||||
///
|
||||
/// Returns live statistics from the QUIC state for an open path, or
|
||||
/// the final statistics retained by `noq` for a path that closed
|
||||
/// after this snapshot was taken.
|
||||
pub fn stats(&self) -> PathStats {
|
||||
self.data.upgrade(self.conn).stats()
|
||||
}
|
||||
|
||||
/// Returns the path's round-trip time estimate.
|
||||
pub fn rtt(&self) -> Duration {
|
||||
self.stats().rtt
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream of [`PathList`] snapshots for a connection.
|
||||
///
|
||||
/// Returned by [`Connection::paths_stream`]. Yields the current
|
||||
/// snapshot on the first poll and a fresh snapshot whenever the open
|
||||
/// paths or the selected path change. Ends when the connection closes.
|
||||
///
|
||||
/// [`Connection::paths_stream`]: crate::endpoint::Connection::paths_stream
|
||||
#[derive(Debug)]
|
||||
pub struct PathListStream<'conn> {
|
||||
shared: &'conn Shared,
|
||||
conn: &'conn noq::Connection,
|
||||
notified: Pin<Box<Notified<'conn>>>,
|
||||
first_poll: bool,
|
||||
}
|
||||
|
||||
impl<'conn> Stream for PathListStream<'conn> {
|
||||
type Item = PathList<'conn>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let this = self.get_mut();
|
||||
if this.first_poll {
|
||||
this.first_poll = false;
|
||||
} else {
|
||||
std::task::ready!(this.notified.as_mut().poll(cx));
|
||||
this.notified.set(this.shared.notify.notified());
|
||||
}
|
||||
this.notified.as_mut().enable();
|
||||
let snapshot = this.shared.state.lock().expect("poisoned").clone();
|
||||
if snapshot.closed {
|
||||
Poll::Ready(None)
|
||||
} else {
|
||||
Poll::Ready(Some(PathList {
|
||||
snapshot,
|
||||
conn: this.conn,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `'static` stream of [`PathEvent`]s.
|
||||
///
|
||||
/// Returned by [`Connection::path_events`].
|
||||
///
|
||||
/// [`Connection::path_events`]: crate::endpoint::Connection::path_events
|
||||
#[derive(Debug)]
|
||||
pub struct PathEventStream {
|
||||
inner: BroadcastStream<PathEvent>,
|
||||
}
|
||||
|
||||
impl Stream for PathEventStream {
|
||||
type Item = PathEvent;
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
self.inner.poll_next(cx).map(|event| match event? {
|
||||
Ok(event) => Some(event),
|
||||
Err(BroadcastStreamRecvError::Lagged(missed)) => Some(PathEvent::Lagged { missed }),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Retry admission, shared by every connection to one remote endpoint.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
pub(super) const MAX_PENDING_OPEN_PATHS: usize = 64;
|
||||
|
||||
pub(super) fn queue_pending_open_path<T: Clone + Eq>(pending: &mut VecDeque<T>, path: &T) {
|
||||
if pending.contains(path) {
|
||||
return;
|
||||
}
|
||||
// Candidate churn must also stay bounded when every address is distinct.
|
||||
if pending.len() == MAX_PENDING_OPEN_PATHS {
|
||||
pending.pop_front();
|
||||
}
|
||||
pending.push_back(path.clone());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn repeated_connection_failures_do_not_multiply_retry_work() {
|
||||
let mut pending = VecDeque::new();
|
||||
queue_pending_open_path(&mut pending, &1);
|
||||
for _ in 0..8 {
|
||||
// The actor takes the current queue and retries every path on
|
||||
// every live connection. Stock iroh multiplies it by four here.
|
||||
let batch = std::mem::take(&mut pending);
|
||||
for path in batch {
|
||||
for _ in 0..4 {
|
||||
queue_pending_open_path(&mut pending, &path);
|
||||
}
|
||||
}
|
||||
assert_eq!(pending, VecDeque::from([1]));
|
||||
}
|
||||
// A later successful attempt leaves nothing queued.
|
||||
let batch = std::mem::take(&mut pending);
|
||||
assert_eq!(batch, VecDeque::from([1]));
|
||||
assert!(pending.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unique_paths_stay_in_order_and_duplicates_do_not_evict_them() {
|
||||
let mut pending = VecDeque::new();
|
||||
for path in 0..MAX_PENDING_OPEN_PATHS {
|
||||
queue_pending_open_path(&mut pending, &path);
|
||||
}
|
||||
for _ in 0..100 {
|
||||
queue_pending_open_path(&mut pending, &0);
|
||||
}
|
||||
assert_eq!(
|
||||
pending,
|
||||
(0..MAX_PENDING_OPEN_PATHS).collect::<VecDeque<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_churn_evicts_oldest_and_keeps_retry_memory_bounded() {
|
||||
let mut pending = VecDeque::new();
|
||||
for path in 0..10_000 {
|
||||
queue_pending_open_path(&mut pending, &path);
|
||||
assert!(pending.len() <= MAX_PENDING_OPEN_PATHS);
|
||||
assert!(pending.capacity() <= MAX_PENDING_OPEN_PATHS);
|
||||
}
|
||||
assert_eq!(
|
||||
pending,
|
||||
(10_000 - MAX_PENDING_OPEN_PATHS..10_000).collect::<VecDeque<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use iroh_base::{EndpointId, TransportAddr};
|
||||
|
||||
/// Information about a remote endpoint.
|
||||
///
|
||||
/// This information is a snapshot in time, i.e. it is not updating and may
|
||||
/// already be outdated by the time you are reading this. Updated information
|
||||
/// can only be retrieved by calling [`Endpoint::remote_info`] again.
|
||||
///
|
||||
/// [`Endpoint::remote_info`]: crate::Endpoint::remote_info
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RemoteInfo {
|
||||
pub(super) endpoint_id: EndpointId,
|
||||
pub(super) addrs: Vec<TransportAddrInfo>,
|
||||
}
|
||||
|
||||
impl RemoteInfo {
|
||||
/// Returns the remote's endpoint id.
|
||||
pub fn id(&self) -> EndpointId {
|
||||
self.endpoint_id
|
||||
}
|
||||
|
||||
/// Returns an iterator over known all addresses for this remote.
|
||||
///
|
||||
/// Note that this may include outdated or unusable addresses.
|
||||
pub fn addrs(&self) -> impl Iterator<Item = &TransportAddrInfo> {
|
||||
self.addrs.iter()
|
||||
}
|
||||
|
||||
/// Converts into an iterator over known all addresses for this remote.
|
||||
///
|
||||
/// Note that this may include outdated or unusable addresses. You can use [`TransportAddrInfo::usage`]
|
||||
/// to filter for addresses that are actively used.
|
||||
///
|
||||
/// You can use this to construct an [`EndpointAddr`] for this remote:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # use iroh::{Endpoint, EndpointId, EndpointAddr, endpoint::presets};
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// # let endpoint = Endpoint::bind(presets::N0).await.unwrap();
|
||||
/// # let remote_id = EndpointId::from_bytes(&[0u8; 32]).unwrap();
|
||||
/// let info = endpoint.remote_info(remote_id).await.unwrap();
|
||||
/// let addr = EndpointAddr::from_parts(info.id(), info.into_addrs().map(|addr| addr.into_addr()));
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`EndpointAddr`]: crate::EndpointAddr
|
||||
pub fn into_addrs(self) -> impl Iterator<Item = TransportAddrInfo> {
|
||||
self.addrs.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Address of a remote with some metadata
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TransportAddrInfo {
|
||||
pub(super) addr: TransportAddr,
|
||||
pub(super) usage: TransportAddrUsage,
|
||||
}
|
||||
|
||||
impl TransportAddrInfo {
|
||||
/// Returns the [`TransportAddr`].
|
||||
pub fn addr(&self) -> &TransportAddr {
|
||||
&self.addr
|
||||
}
|
||||
|
||||
/// Converts into [`TransportAddr`].
|
||||
pub fn into_addr(self) -> TransportAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
/// Returns information how this address is used.
|
||||
pub fn usage(&self) -> TransportAddrUsage {
|
||||
self.usage
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TransportAddrInfo> for TransportAddr {
|
||||
fn from(value: TransportAddrInfo) -> Self {
|
||||
value.addr
|
||||
}
|
||||
}
|
||||
|
||||
/// Information how a transport address is used.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub enum TransportAddrUsage {
|
||||
/// The address is in active use.
|
||||
Active,
|
||||
/// The address is not currently used.
|
||||
Inactive,
|
||||
}
|
||||
Vendored
+1460
File diff suppressed because it is too large.
Load diff
+105
@@ -0,0 +1,105 @@
|
||||
// The items in this module are exported from [`crate::endpoint::transports`] only if
|
||||
// the "unstable-custom-transports" feature is enabled
|
||||
#![cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
|
||||
|
||||
use std::{
|
||||
io,
|
||||
num::NonZeroUsize,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use iroh_base::CustomAddr;
|
||||
|
||||
use super::{RecvInfo, Transmit};
|
||||
|
||||
/// Custom transport.
|
||||
///
|
||||
/// Usually a transport will only deal with a single custom address type, but
|
||||
/// the signature allows for dealing with multiple custom address types.
|
||||
///
|
||||
/// A transport is a factory for custom endpoints. Whenever an iroh endpoint is
|
||||
/// created using [crate::endpoint::Builder::bind], a new custom endpoint will
|
||||
/// be created using [CustomTransport::bind].
|
||||
pub trait CustomTransport: std::fmt::Debug + Send + Sync + 'static {
|
||||
/// Create a custom endpoint
|
||||
///
|
||||
/// Analogously to [std::net::UdpSocket::bind], this is where the actual
|
||||
/// underlying hardware resource is created.
|
||||
fn bind(&self) -> io::Result<Box<dyn CustomEndpoint>>;
|
||||
}
|
||||
|
||||
/// Custom endpoint created by a [CustomTransport].
|
||||
///
|
||||
/// An endpoint has a local address (or multiple local addresses), can receive
|
||||
/// packets, and can create senders to send packets.
|
||||
pub trait CustomEndpoint: std::fmt::Debug + Send + Sync + 'static {
|
||||
/// A watcher for local addresses for this custom endpoint.
|
||||
fn watch_local_addrs(&self) -> n0_watcher::Direct<Vec<CustomAddr>>;
|
||||
/// Create a custom sender for this custom endpoint.
|
||||
fn create_sender(&self) -> Arc<dyn CustomSender>;
|
||||
/// poll receiving a packet on this custom endpoint.
|
||||
///
|
||||
/// This will be called with `bufs`, `metas` and `recv_infos` of the same length.
|
||||
/// It is acceptable to panic if this is not the case.
|
||||
///
|
||||
/// The maximum length of the slices is [`noq_udp::BATCH_SIZE`].
|
||||
/// It is acceptable to panic if this is exceeded.
|
||||
///
|
||||
/// On success, all three slices must be filled up to the returned length,
|
||||
/// and the returned length must be less than or equal to the length of the slices.
|
||||
///
|
||||
/// It does not make much sense to return addresses unrelated to this transport.
|
||||
///
|
||||
/// For each filled slot, write a [`RecvInfo::new`] carrying the remote
|
||||
/// custom address and, if the transport can identify it, the local custom
|
||||
/// address that received the packet. The latter surfaces via
|
||||
/// [`crate::endpoint::Incoming::local_addr`].
|
||||
fn poll_recv(
|
||||
&mut self,
|
||||
cx: &mut Context,
|
||||
bufs: &mut [io::IoSliceMut<'_>],
|
||||
metas: &mut [noq_udp::RecvMeta],
|
||||
recv_infos: &mut [RecvInfo],
|
||||
) -> Poll<io::Result<usize>>;
|
||||
|
||||
/// Maximum number of segments to transmit (GSO).
|
||||
///
|
||||
/// This controls how many datagrams Noq will batch into a single transmit.
|
||||
/// The default is 1 (no batching). Custom transports that support batching
|
||||
/// can override this to allow more efficient transmission.
|
||||
fn max_transmit_segments(&self) -> NonZeroUsize {
|
||||
NonZeroUsize::MIN
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Box<dyn CustomEndpoint> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "CustomTransport")
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom sender
|
||||
///
|
||||
/// A sender provides a poll based interface to send packets to custom addresses.
|
||||
/// It can decide whether it wants to send to a given custom address type.
|
||||
///
|
||||
/// This is not enforced at type level, but [CustomSender::poll_send] should
|
||||
/// only be called with addresses for which [CustomSender::is_valid_send_addr]
|
||||
/// returns true.
|
||||
pub trait CustomSender: std::fmt::Debug + Send + Sync + 'static {
|
||||
/// True if this sender can send to the given address.
|
||||
fn is_valid_send_addr(&self, addr: &CustomAddr) -> bool;
|
||||
/// poll sending a packet on this sender.
|
||||
///
|
||||
/// This will only be called from iroh with addresses for which [CustomSender::is_valid_send_addr] returns true.
|
||||
///
|
||||
/// You should handle invalid addresses by returning an error.
|
||||
fn poll_send(
|
||||
&self,
|
||||
cx: &mut std::task::Context,
|
||||
dst: &CustomAddr,
|
||||
src: Option<&CustomAddr>,
|
||||
transmit: &Transmit<'_>,
|
||||
) -> Poll<io::Result<()>>;
|
||||
}
|
||||
+548
@@ -0,0 +1,548 @@
|
||||
use std::{
|
||||
io,
|
||||
net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
|
||||
num::NonZeroUsize,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use ipnet::{Ipv4Net, Ipv6Net};
|
||||
use n0_watcher::Watchable;
|
||||
use netwatch::{UdpSender, UdpSocket};
|
||||
use pin_project::pin_project;
|
||||
use tracing::{debug, info, trace};
|
||||
|
||||
use super::{RecvInfo, Transmit};
|
||||
use crate::metrics::{EndpointMetrics, SocketMetrics};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct IpTransport {
|
||||
config: Config,
|
||||
socket: Arc<UdpSocket>,
|
||||
local_addr: Watchable<SocketAddr>,
|
||||
metrics: Arc<SocketMetrics>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for IpTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let version = if self.config.is_ipv4() { "v4" } else { "v6" };
|
||||
write!(f, "IpTransport({version})")
|
||||
}
|
||||
}
|
||||
|
||||
/// IP transport configuration
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum Config {
|
||||
/// General IPv4 binding
|
||||
V4 {
|
||||
/// The IP address to bind on
|
||||
ip_net: Ipv4Net,
|
||||
/// The port to bind on
|
||||
port: u16,
|
||||
/// Is binding mandatory?
|
||||
is_required: bool,
|
||||
/// Is this a default route?
|
||||
is_default: bool,
|
||||
},
|
||||
/// General IPv6 binding
|
||||
V6 {
|
||||
/// The IP address to bind on
|
||||
ip_net: Ipv6Net,
|
||||
/// The scope id.
|
||||
scope_id: u32,
|
||||
/// The port to bind on
|
||||
port: u16,
|
||||
/// Is binding mandatory?
|
||||
is_required: bool,
|
||||
/// Is this a default route?
|
||||
is_default: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Is this a v4 config.
|
||||
pub(crate) fn is_ipv4(&self) -> bool {
|
||||
matches!(self, | Self::V4 { .. })
|
||||
}
|
||||
|
||||
/// Is this a v6 config.
|
||||
pub(crate) fn is_ipv6(&self) -> bool {
|
||||
matches!(self, | Self::V6 { .. })
|
||||
}
|
||||
|
||||
/// Returns the prefix len for the address.
|
||||
pub(crate) fn prefix_len(&self) -> u8 {
|
||||
match self {
|
||||
Self::V4 { ip_net, .. } => ip_net.prefix_len(),
|
||||
Self::V6 { ip_net, .. } => ip_net.prefix_len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this a default config?
|
||||
pub(crate) fn is_default(&self) -> bool {
|
||||
match self {
|
||||
Self::V4 { is_default, .. } => *is_default,
|
||||
Self::V6 { is_default, .. } => *is_default,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this required to bind.
|
||||
pub(crate) fn is_required(&self) -> bool {
|
||||
match self {
|
||||
Self::V4 { is_required, .. } => *is_required,
|
||||
Self::V6 { is_required, .. } => *is_required,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_valid_default_addr(&self, src: Option<IpAddr>, dst: SocketAddr) -> bool {
|
||||
match src {
|
||||
Some(src) => match (self, src) {
|
||||
(Self::V4 { is_default, .. }, IpAddr::V4(_)) => *is_default,
|
||||
(Self::V6 { is_default, .. }, IpAddr::V6(_)) => *is_default,
|
||||
_ => false,
|
||||
},
|
||||
None => match (self, dst) {
|
||||
(Self::V4 { is_default, .. }, SocketAddr::V4(_)) => *is_default,
|
||||
(Self::V6 { is_default, .. }, SocketAddr::V6(_)) => *is_default,
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Does this configuration match to send to the given `src` and `dst` address.
|
||||
pub(crate) fn is_valid_send_addr(&self, src: Option<IpAddr>, dst: SocketAddr) -> bool {
|
||||
match src {
|
||||
Some(src) => match (self, src) {
|
||||
(Self::V4 { ip_net, .. }, IpAddr::V4(src)) => {
|
||||
ip_net.addr().is_unspecified() || ip_net.addr() == src
|
||||
}
|
||||
(Self::V6 { ip_net, .. }, IpAddr::V6(src)) => {
|
||||
ip_net.addr().is_unspecified() || ip_net.addr() == src
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
None => {
|
||||
match (self, dst) {
|
||||
(Self::V4 { ip_net, .. }, SocketAddr::V4(dst_v4)) => {
|
||||
ip_net.contains(dst_v4.ip())
|
||||
}
|
||||
(
|
||||
Self::V6 {
|
||||
ip_net, scope_id, ..
|
||||
},
|
||||
SocketAddr::V6(dst_v6),
|
||||
) => {
|
||||
if ip_net.contains(dst_v6.ip()) {
|
||||
return true;
|
||||
}
|
||||
if dst_v6.ip().is_unicast_link_local() {
|
||||
// If we have a link local interface, use the scope id
|
||||
if *scope_id == dst_v6.scope_id() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Config> for SocketAddr {
|
||||
fn from(value: Config) -> Self {
|
||||
match value {
|
||||
Config::V4 { ip_net, port, .. } => {
|
||||
SocketAddr::V4(SocketAddrV4::new(ip_net.addr(), port))
|
||||
}
|
||||
Config::V6 {
|
||||
ip_net,
|
||||
scope_id,
|
||||
port,
|
||||
..
|
||||
} => SocketAddr::V6(SocketAddrV6::new(ip_net.addr(), port, 0, scope_id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl IpTransport {
|
||||
pub(crate) fn bind(config: Config, metrics: Arc<SocketMetrics>) -> io::Result<Self> {
|
||||
let addr: SocketAddr = config.into();
|
||||
debug!(?addr, "binding");
|
||||
let socket = netwatch::UdpSocket::bind_full(addr).inspect_err(|err| {
|
||||
debug!(%addr, "failed to bind: {err:#}");
|
||||
})?;
|
||||
let local_addr = socket.local_addr()?;
|
||||
debug!(%addr, %local_addr, "successfully bound");
|
||||
// Currently gets updated on manual rebind
|
||||
// TODO: update when UdpSocket under the hood rebinds automatically
|
||||
let local_addr = Watchable::new(local_addr);
|
||||
|
||||
Ok(Self {
|
||||
config,
|
||||
socket: Arc::new(socket),
|
||||
local_addr,
|
||||
metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
|
||||
pub(super) fn poll_recv(
|
||||
&mut self,
|
||||
cx: &mut Context,
|
||||
bufs: &mut [io::IoSliceMut<'_>],
|
||||
metas: &mut [noq_udp::RecvMeta],
|
||||
recv_infos: &mut [RecvInfo],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
|
||||
assert_eq!(
|
||||
bufs.len(),
|
||||
recv_infos.len(),
|
||||
"non matching bufs & recv_infos"
|
||||
);
|
||||
match self.socket.poll_recv_noq(cx, bufs, metas) {
|
||||
Poll::Pending => Poll::Pending,
|
||||
Poll::Ready(Ok(n)) => {
|
||||
for i in 0..n {
|
||||
let meta = &mut metas[i];
|
||||
let recv_info = &mut recv_infos[i];
|
||||
if meta.addr.is_ipv4() {
|
||||
// The AsyncUdpSocket is an AF_INET6 socket and needs to show this
|
||||
// as coming from an IPv4-mapped IPv6 addresses, since Noq will
|
||||
// use those when sending on an INET6 socket.
|
||||
let v6_ip = match meta.addr.ip() {
|
||||
IpAddr::V4(ipv4_addr) => ipv4_addr.to_ipv6_mapped(),
|
||||
IpAddr::V6(ipv6_addr) => ipv6_addr,
|
||||
};
|
||||
meta.addr = SocketAddr::new(v6_ip.into(), meta.addr.port());
|
||||
}
|
||||
// The transport addresses are internal to iroh and we always want those
|
||||
// to remain the canonical address.
|
||||
*recv_info = RecvInfo::from_addr(
|
||||
SocketAddr::new(meta.addr.ip().to_canonical(), meta.addr.port()).into(),
|
||||
);
|
||||
}
|
||||
Poll::Ready(Ok(n))
|
||||
}
|
||||
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn local_addr_watch(&self) -> n0_watcher::Direct<SocketAddr> {
|
||||
self.local_addr.watch()
|
||||
}
|
||||
|
||||
pub(super) fn max_transmit_segments(&self) -> NonZeroUsize {
|
||||
self.socket.max_gso_segments()
|
||||
}
|
||||
|
||||
pub(super) fn max_receive_segments(&self) -> NonZeroUsize {
|
||||
self.socket.gro_segments()
|
||||
}
|
||||
|
||||
pub(super) fn may_fragment(&self) -> bool {
|
||||
self.socket.may_fragment()
|
||||
}
|
||||
|
||||
pub(crate) fn bind_addr(&self) -> SocketAddr {
|
||||
self.config.into()
|
||||
}
|
||||
|
||||
pub(super) fn create_network_change_sender(&self) -> IpNetworkChangeSender {
|
||||
IpNetworkChangeSender {
|
||||
socket: self.socket.clone(),
|
||||
local_addr: self.local_addr.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_sender(&self) -> IpSender {
|
||||
let sender = self.socket.clone().create_sender();
|
||||
IpSender {
|
||||
config: self.config,
|
||||
sender,
|
||||
metrics: self.metrics.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct IpNetworkChangeSender {
|
||||
socket: Arc<UdpSocket>,
|
||||
local_addr: Watchable<SocketAddr>,
|
||||
}
|
||||
|
||||
impl IpNetworkChangeSender {
|
||||
pub(super) fn rebind(&self) -> io::Result<()> {
|
||||
let old_addr = self.local_addr.get();
|
||||
self.socket.rebind()?;
|
||||
let addr = self.socket.local_addr()?;
|
||||
self.local_addr.set(addr).ok();
|
||||
trace!("rebound from {} to {}", old_addr, addr);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn on_network_change(&self, _info: &crate::socket::Report) {
|
||||
// Nothing to do for now
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[pin_project]
|
||||
pub(super) struct IpSender {
|
||||
config: Config,
|
||||
#[pin]
|
||||
sender: UdpSender,
|
||||
metrics: Arc<SocketMetrics>,
|
||||
}
|
||||
|
||||
impl IpSender {
|
||||
pub(super) fn is_valid_send_addr(&self, src: Option<IpAddr>, dst: &SocketAddr) -> bool {
|
||||
self.config.is_valid_send_addr(src, *dst)
|
||||
}
|
||||
|
||||
pub(super) fn is_valid_default_addr(&self, src: Option<IpAddr>, dst: &SocketAddr) -> bool {
|
||||
self.config.is_valid_default_addr(src, *dst)
|
||||
}
|
||||
|
||||
/// Creates a canonical socket address.
|
||||
///
|
||||
/// We may be asked to send IPv4-mapped IPv6 addresses. But our sockets are configured
|
||||
/// to only send their actual family. So we need to map those back to the canonical
|
||||
/// addresses.
|
||||
#[inline]
|
||||
fn canonical_addr(addr: SocketAddr) -> SocketAddr {
|
||||
SocketAddr::new(addr.ip().to_canonical(), addr.port())
|
||||
}
|
||||
|
||||
pub(super) fn poll_send(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut std::task::Context,
|
||||
dst: SocketAddr,
|
||||
src: Option<IpAddr>,
|
||||
transmit: &Transmit<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let total_bytes = transmit.contents.len() as u64;
|
||||
let res = Pin::new(&mut self.sender).poll_send(
|
||||
&noq_udp::Transmit {
|
||||
destination: Self::canonical_addr(dst),
|
||||
ecn: transmit.ecn,
|
||||
contents: transmit.contents,
|
||||
segment_size: transmit.segment_size,
|
||||
src_ip: src,
|
||||
},
|
||||
cx,
|
||||
);
|
||||
|
||||
match res {
|
||||
Poll::Ready(Ok(res)) => {
|
||||
match dst {
|
||||
SocketAddr::V4(_) => {
|
||||
self.metrics.send_ipv4.inc_by(total_bytes);
|
||||
}
|
||||
SocketAddr::V6(_) => {
|
||||
self.metrics.send_ipv6.inc_by(total_bytes);
|
||||
}
|
||||
}
|
||||
Poll::Ready(Ok(res))
|
||||
}
|
||||
Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct IpTransportsSender {
|
||||
/// Stored sorted by prefix len
|
||||
v4: Vec<IpSender>,
|
||||
default_v4_index: Option<usize>,
|
||||
/// Stored sorted by prefix len
|
||||
v6: Vec<IpSender>,
|
||||
default_v6_index: Option<usize>,
|
||||
}
|
||||
|
||||
impl IpTransportsSender {
|
||||
pub(super) fn v4_iter_mut(&mut self) -> impl Iterator<Item = &mut IpSender> {
|
||||
self.v4.iter_mut()
|
||||
}
|
||||
|
||||
pub(super) fn v4_default_mut(&mut self) -> Option<&mut IpSender> {
|
||||
if let Some(i) = self.default_v4_index {
|
||||
return Some(&mut self.v4[i]);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn v6_iter_mut(&mut self) -> impl Iterator<Item = &mut IpSender> {
|
||||
self.v6.iter_mut()
|
||||
}
|
||||
|
||||
pub(super) fn v6_default_mut(&mut self) -> Option<&mut IpSender> {
|
||||
if let Some(i) = self.default_v6_index {
|
||||
return Some(&mut self.v6[i]);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct IpTransports {
|
||||
v4: Vec<IpTransport>,
|
||||
default_v4_index: Option<usize>,
|
||||
v6: Vec<IpTransport>,
|
||||
default_v6_index: Option<usize>,
|
||||
}
|
||||
|
||||
impl IpTransports {
|
||||
pub(super) fn create_sender(&self) -> IpTransportsSender {
|
||||
let ip_v4 = self.v4.iter().map(|t| t.create_sender()).collect();
|
||||
let ip_v6 = self.v6.iter().map(|t| t.create_sender()).collect();
|
||||
|
||||
IpTransportsSender {
|
||||
v4: ip_v4,
|
||||
default_v4_index: self.default_v4_index,
|
||||
v6: ip_v6,
|
||||
default_v6_index: self.default_v6_index,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn iter(&self) -> impl Iterator<Item = &IpTransport> {
|
||||
self.v4.iter().chain(self.v6.iter())
|
||||
}
|
||||
|
||||
pub(super) fn bind(
|
||||
configs: impl Iterator<Item = Config>,
|
||||
metrics: &EndpointMetrics,
|
||||
) -> io::Result<Self> {
|
||||
let mut has_v4_default = false;
|
||||
let mut ip_v4 = Vec::new();
|
||||
|
||||
let mut has_v6_default = false;
|
||||
let mut ip_v6 = Vec::new();
|
||||
|
||||
for config in configs {
|
||||
match IpTransport::bind(config, metrics.socket.clone()) {
|
||||
Ok(transport) => {
|
||||
if config.is_ipv4() {
|
||||
if config.is_default() {
|
||||
if has_v4_default {
|
||||
return Err(io::Error::other(
|
||||
"can only have a single IPv4 default transport",
|
||||
));
|
||||
}
|
||||
has_v4_default = true;
|
||||
}
|
||||
ip_v4.push(transport);
|
||||
} else if config.is_ipv6() {
|
||||
if config.is_default() {
|
||||
if has_v6_default {
|
||||
return Err(io::Error::other(
|
||||
"can only have a single IPv6 default transport",
|
||||
));
|
||||
}
|
||||
has_v6_default = true;
|
||||
}
|
||||
ip_v6.push(transport);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if config.is_required() {
|
||||
return Err(err);
|
||||
}
|
||||
info!("ignoring non required bind failure: {:?}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort in descending order by prefix len
|
||||
ip_v4.sort_by_key(|i| std::cmp::Reverse(i.config.prefix_len()));
|
||||
ip_v6.sort_by_key(|i| std::cmp::Reverse(i.config.prefix_len()));
|
||||
|
||||
let default_v4_index = ip_v4.iter().position(|i| i.config.is_default());
|
||||
let default_v6_index = ip_v6.iter().position(|i| i.config.is_default());
|
||||
|
||||
Ok(Self {
|
||||
v4: ip_v4,
|
||||
default_v4_index,
|
||||
v6: ip_v6,
|
||||
default_v6_index,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn iter_mut(&mut self) -> impl Iterator<Item = &mut IpTransport> {
|
||||
self.v4.iter_mut().chain(self.v6.iter_mut())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_bind_sorting() -> n0_error::Result {
|
||||
let has_ipv6 = tokio::net::UdpSocket::bind("[::1]:0").await.is_ok();
|
||||
eprintln!("testing with ipv6? {has_ipv6}");
|
||||
|
||||
let metrics = EndpointMetrics::default();
|
||||
let config = vec![
|
||||
Config::V4 {
|
||||
ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 8).unwrap(),
|
||||
port: 2222,
|
||||
is_required: true,
|
||||
is_default: false,
|
||||
},
|
||||
Config::V4 {
|
||||
ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 24).unwrap(),
|
||||
port: 1111,
|
||||
is_required: true,
|
||||
is_default: true,
|
||||
},
|
||||
Config::V4 {
|
||||
ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 0).unwrap(),
|
||||
port: 9999,
|
||||
is_required: true,
|
||||
is_default: false,
|
||||
},
|
||||
Config::V6 {
|
||||
ip_net: Ipv6Net::new("::1".parse().unwrap(), 4).unwrap(),
|
||||
port: 2228,
|
||||
scope_id: 0,
|
||||
is_required: has_ipv6,
|
||||
is_default: false,
|
||||
},
|
||||
Config::V6 {
|
||||
ip_net: Ipv6Net::new("::1".parse().unwrap(), 2).unwrap(),
|
||||
port: 9998,
|
||||
scope_id: 0,
|
||||
is_required: has_ipv6,
|
||||
is_default: true,
|
||||
},
|
||||
Config::V6 {
|
||||
ip_net: Ipv6Net::new("::1".parse().unwrap(), 32).unwrap(),
|
||||
port: 1118,
|
||||
scope_id: 0,
|
||||
is_required: has_ipv6,
|
||||
is_default: false,
|
||||
},
|
||||
];
|
||||
|
||||
let transports = IpTransports::bind(config.into_iter(), &metrics)?;
|
||||
assert_eq!(transports.v4[0].config.prefix_len(), 24);
|
||||
assert_eq!(transports.v4[1].config.prefix_len(), 8);
|
||||
assert_eq!(transports.v4[2].config.prefix_len(), 0);
|
||||
|
||||
assert_eq!(transports.default_v4_index, Some(0));
|
||||
|
||||
if has_ipv6 {
|
||||
assert_eq!(transports.v6[0].config.prefix_len(), 32);
|
||||
assert_eq!(transports.v6[1].config.prefix_len(), 4);
|
||||
assert_eq!(transports.v6[2].config.prefix_len(), 2);
|
||||
|
||||
assert_eq!(transports.default_v6_index, Some(2));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
use std::{
|
||||
io,
|
||||
num::NonZeroU16,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh_base::{EndpointId, RelayUrl};
|
||||
use iroh_relay::protos::relay::Datagrams;
|
||||
use n0_future::{
|
||||
ready,
|
||||
task::{self, AbortOnDropHandle},
|
||||
};
|
||||
use n0_watcher::Watcher as _;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_util::sync::{CancellationToken, PollSender};
|
||||
use tracing::{Instrument, error, info_span, warn};
|
||||
|
||||
use super::{RecvInfo, Transmit};
|
||||
use crate::endpoint::RelayStatus;
|
||||
|
||||
mod actor;
|
||||
|
||||
pub(crate) use self::actor::{
|
||||
Config as RelayActorConfig, HomeRelayWatch, RelayConnectionFailure, RelayConnectionState,
|
||||
};
|
||||
use self::actor::{RelayActor, RelayActorMessage, RelayRecvDatagram, RelaySendItem};
|
||||
|
||||
type RelayAddrWatcher =
|
||||
n0_watcher::Map<n0_watcher::Direct<Option<RelayStatus>>, Option<(RelayUrl, EndpointId)>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct RelayTransport {
|
||||
/// Queue to receive datagrams from relays for [`noq::AsyncUdpSocket::poll_recv`].
|
||||
relay_datagram_recv_queue: mpsc::Receiver<RelayRecvDatagram>,
|
||||
/// Channel on which to send datagrams via a relay server.
|
||||
relay_datagram_send_channel: mpsc::Sender<RelaySendItem>,
|
||||
/// A datagram from the last poll_recv that didn't quite fit our buffers.
|
||||
pending_item: Option<RelayRecvDatagram>,
|
||||
actor_sender: mpsc::Sender<RelayActorMessage>,
|
||||
_actor_handle: AbortOnDropHandle<()>,
|
||||
my_relay: HomeRelayWatch,
|
||||
my_endpoint_id: EndpointId,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RelayTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "RelayTransport")
|
||||
}
|
||||
}
|
||||
|
||||
impl RelayTransport {
|
||||
pub(crate) fn new(config: RelayActorConfig, cancel_token: CancellationToken) -> Self {
|
||||
let (relay_datagram_send_tx, relay_datagram_send_rx) = mpsc::channel(256);
|
||||
|
||||
let (relay_datagram_recv_tx, relay_datagram_recv_rx) = mpsc::channel(512);
|
||||
|
||||
let (actor_sender, actor_receiver) = mpsc::channel(256);
|
||||
|
||||
let my_endpoint_id = config.secret_key.public();
|
||||
let my_relay = config.my_relay.clone();
|
||||
|
||||
let relay_actor = RelayActor::new(config, relay_datagram_recv_tx, cancel_token);
|
||||
|
||||
let actor_handle = AbortOnDropHandle::new(task::spawn(
|
||||
async move {
|
||||
relay_actor
|
||||
.run(actor_receiver, relay_datagram_send_rx)
|
||||
.await;
|
||||
}
|
||||
.instrument(info_span!("relay-actor")),
|
||||
));
|
||||
|
||||
Self {
|
||||
relay_datagram_recv_queue: relay_datagram_recv_rx,
|
||||
relay_datagram_send_channel: relay_datagram_send_tx,
|
||||
pending_item: None,
|
||||
actor_sender,
|
||||
_actor_handle: actor_handle,
|
||||
my_relay,
|
||||
my_endpoint_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_sender(&self) -> RelaySender {
|
||||
RelaySender {
|
||||
sender: PollSender::new(self.relay_datagram_send_channel.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn poll_recv(
|
||||
&mut self,
|
||||
cx: &mut Context,
|
||||
bufs: &mut [io::IoSliceMut<'_>],
|
||||
metas: &mut [noq_udp::RecvMeta],
|
||||
recv_infos: &mut [RecvInfo],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
|
||||
assert_eq!(
|
||||
bufs.len(),
|
||||
recv_infos.len(),
|
||||
"non matching bufs & recv_infos"
|
||||
);
|
||||
let mut num_msgs = 0;
|
||||
for i in 0..bufs.len() {
|
||||
let buf_out = &mut bufs[i];
|
||||
let meta_out = &mut metas[i];
|
||||
let recv_info = &mut recv_infos[i];
|
||||
let dm = match self.poll_recv_queue(cx) {
|
||||
Poll::Ready(Some(recv)) => recv,
|
||||
Poll::Ready(None) => {
|
||||
error!("relay_recv_channel closed");
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::NotConnected,
|
||||
"connection closed",
|
||||
)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
// This *tries* to make the datagrams fit into our buffer by re-batching them.
|
||||
let num_segments = dm
|
||||
.datagrams
|
||||
.segment_size
|
||||
.map_or(1, |ss| buf_out.len() / u16::from(ss) as usize);
|
||||
let datagrams = dm.datagrams.take_segments(num_segments);
|
||||
let empty_now = datagrams.contents.is_empty();
|
||||
let empty_after = dm.datagrams.contents.is_empty();
|
||||
|
||||
let dm = RelayRecvDatagram {
|
||||
datagrams,
|
||||
src: dm.src,
|
||||
url: dm.url.clone(),
|
||||
};
|
||||
|
||||
// If `take_segments` processed the whole contents (empty_after) or none at all
|
||||
// (empty_now) we shouldn't process what's left in `self.pending_item`.
|
||||
// In the first case the remaining `pending_item` is empty and can be dropped.
|
||||
// In the second case a single segment could not fit into the buffer, future
|
||||
// calls to `poll_recv` would not change this so drop the `pending_item` with
|
||||
// the oversized segment size.
|
||||
if empty_after || empty_now {
|
||||
self.pending_item = None;
|
||||
}
|
||||
if empty_now {
|
||||
warn!(
|
||||
noq_buf_len = buf_out.len(),
|
||||
segment_size = ?dm.datagrams.segment_size,
|
||||
"dropping received datagram: segment_size too large");
|
||||
continue;
|
||||
}
|
||||
|
||||
if buf_out.len() < dm.datagrams.contents.len() {
|
||||
// Our receive buffer isn't big enough to process this datagram.
|
||||
// Continuing would cause a panic.
|
||||
warn!(
|
||||
noq_buf_len = buf_out.len(),
|
||||
datagram_len = dm.datagrams.contents.len(),
|
||||
segment_size = ?dm.datagrams.segment_size,
|
||||
"dropping received datagram: noq buffer too small"
|
||||
);
|
||||
break;
|
||||
// In theory we could put some logic in here to fragment the datagram in case
|
||||
// we still have enough room in our `buf_out` left to fit a couple of
|
||||
// `dm.datagrams.segment_size`es, but we *should* have cut those datagrams
|
||||
// to appropriate sizes earlier in the pipeline (just before we put them
|
||||
// into the `relay_datagram_recv_queue` in the `ActiveRelayActor`).
|
||||
// So the only case in which this happens is we receive a datagram via the relay
|
||||
// that's essentially bigger than our configured `max_udp_payload_size`.
|
||||
// In that case we drop it and let MTU discovery take over.
|
||||
}
|
||||
|
||||
buf_out[..dm.datagrams.contents.len()].copy_from_slice(&dm.datagrams.contents);
|
||||
meta_out.len = dm.datagrams.contents.len();
|
||||
meta_out.stride = dm
|
||||
.datagrams
|
||||
.segment_size
|
||||
.map_or(dm.datagrams.contents.len(), |s| u16::from(s) as usize);
|
||||
meta_out.ecn = None;
|
||||
meta_out.dst_ip = None;
|
||||
|
||||
*recv_info = RecvInfo::from_addr((dm.url, dm.src).into());
|
||||
num_msgs += 1;
|
||||
}
|
||||
|
||||
// If we have any msgs to report, they are in the first `num_msgs_total` slots
|
||||
if num_msgs > 0 {
|
||||
assert!(num_msgs <= metas.len());
|
||||
Poll::Ready(Ok(num_msgs))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn local_addr_watch(&self) -> RelayAddrWatcher {
|
||||
let my_endpoint_id = self.my_endpoint_id;
|
||||
self.my_relay
|
||||
.watch()
|
||||
.map(move |status| status.map(|status| (status.url().clone(), my_endpoint_id)))
|
||||
}
|
||||
|
||||
pub(super) fn my_relay_status(&self) -> n0_watcher::Direct<Option<RelayStatus>> {
|
||||
self.my_relay.watch()
|
||||
}
|
||||
|
||||
pub(super) fn create_network_change_sender(&self) -> RelayNetworkChangeSender {
|
||||
RelayNetworkChangeSender {
|
||||
sender: self.actor_sender.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes sure we have a pending item stored, if not, it'll poll a new one from the queue.
|
||||
///
|
||||
/// Returns a mutable reference to the stored pending item.
|
||||
#[inline]
|
||||
fn poll_recv_queue<'a>(
|
||||
&'a mut self,
|
||||
cx: &mut Context,
|
||||
) -> Poll<Option<&'a mut RelayRecvDatagram>> {
|
||||
// Borrow checker doesn't quite understand an if let Some(_)... here
|
||||
if self.pending_item.is_some() {
|
||||
return Poll::Ready(self.pending_item.as_mut());
|
||||
}
|
||||
|
||||
let item = match self.relay_datagram_recv_queue.poll_recv(cx) {
|
||||
Poll::Ready(Some(item)) => item,
|
||||
Poll::Ready(None) => return Poll::Ready(None),
|
||||
Poll::Pending => return Poll::Pending,
|
||||
};
|
||||
|
||||
Poll::Ready(Some(self.pending_item.insert(item)))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct RelayNetworkChangeSender {
|
||||
sender: mpsc::Sender<RelayActorMessage>,
|
||||
}
|
||||
|
||||
impl RelayNetworkChangeSender {
|
||||
pub(super) fn on_network_change(&self, report: &crate::socket::Report) {
|
||||
self.send_relay_actor(RelayActorMessage::NetworkChange {
|
||||
report: report.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Triggers an immediate health check on relay connections after a network change.
|
||||
pub(super) fn check_connection_after_network_change(&self) {
|
||||
self.send_relay_actor(RelayActorMessage::CheckConnectionAfterNetworkChange);
|
||||
}
|
||||
|
||||
pub(super) fn rebind(&self) -> io::Result<()> {
|
||||
self.send_relay_actor(RelayActorMessage::MaybeCloseRelaysOnRebind);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_relay_actor(&self, msg: RelayActorMessage) {
|
||||
match self.sender.try_send(msg) {
|
||||
Ok(_) => {}
|
||||
Err(mpsc::error::TrySendError::Closed(_)) => {
|
||||
warn!("unable to send to relay actor, already closed");
|
||||
}
|
||||
Err(mpsc::error::TrySendError::Full(_)) => {
|
||||
warn!("dropping message for relay actor, channel is full");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sender to send datagrams to the [`RelayActor`].
|
||||
///
|
||||
/// This includes the waker coordination required to support [`noq::UdpSender::poll_send`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct RelaySender {
|
||||
sender: PollSender<RelaySendItem>,
|
||||
}
|
||||
|
||||
impl RelaySender {
|
||||
pub(super) fn is_valid_send_addr(&self, _url: &RelayUrl, _endpoint_id: &EndpointId) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn poll_send(
|
||||
&mut self,
|
||||
cx: &mut Context,
|
||||
dest_url: RelayUrl,
|
||||
dest_endpoint: EndpointId,
|
||||
transmit: &Transmit<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
match ready!(self.sender.poll_reserve(cx)) {
|
||||
Ok(()) => {
|
||||
let contents = datagrams_from_transmit(transmit);
|
||||
let item = RelaySendItem {
|
||||
remote_endpoint: dest_endpoint,
|
||||
url: dest_url.clone(),
|
||||
datagrams: contents,
|
||||
};
|
||||
match self.sender.send_item(item) {
|
||||
Ok(()) => Poll::Ready(Ok(())),
|
||||
Err(_err) => Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::ConnectionReset,
|
||||
"channel to actor is closed",
|
||||
))),
|
||||
}
|
||||
}
|
||||
Err(_err) => Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::ConnectionReset,
|
||||
"channel to actor is closed",
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate a UDP transmit to the `Datagrams` type for sending over the relay.
|
||||
fn datagrams_from_transmit(transmit: &Transmit<'_>) -> Datagrams {
|
||||
Datagrams {
|
||||
ecn: transmit.ecn.map(|ecn| match ecn {
|
||||
noq_udp::EcnCodepoint::Ect0 => noq_proto::EcnCodepoint::Ect0,
|
||||
noq_udp::EcnCodepoint::Ect1 => noq_proto::EcnCodepoint::Ect1,
|
||||
noq_udp::EcnCodepoint::Ce => noq_proto::EcnCodepoint::Ce,
|
||||
}),
|
||||
segment_size: transmit
|
||||
.segment_size
|
||||
.map(|ss| ss as u16)
|
||||
.and_then(NonZeroU16::new),
|
||||
contents: Bytes::copy_from_slice(transmit.contents),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
num::NonZeroU16,
|
||||
sync::{Arc, atomic::AtomicBool},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use iroh_base::{EndpointId, SecretKey};
|
||||
use iroh_relay::{
|
||||
RelayMap,
|
||||
tls::{CaTlsConfig, default_provider},
|
||||
};
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::debug;
|
||||
|
||||
use super::*;
|
||||
use crate::{defaults::staging, dns::DnsResolver};
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_relay_datagram_queue() {
|
||||
let capacity = 16;
|
||||
let (sender, mut receiver) = mpsc::channel(capacity);
|
||||
let url = staging::default_na_east_relay().url;
|
||||
|
||||
let mut tasks = JoinSet::new();
|
||||
|
||||
tasks.spawn({
|
||||
async move {
|
||||
let mut expected_msgs: BTreeSet<usize> = (0..capacity).collect();
|
||||
while !expected_msgs.is_empty() {
|
||||
let datagram: RelayRecvDatagram = receiver.recv().await.unwrap();
|
||||
let msg_num = usize::from_le_bytes(datagram.datagrams.contents.as_ref().try_into().unwrap());
|
||||
debug!("Received {msg_num}");
|
||||
|
||||
if !expected_msgs.remove(&msg_num) {
|
||||
panic!("Received message number {msg_num} twice or more, but expected it only exactly once.");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
for i in 0..capacity {
|
||||
tasks.spawn({
|
||||
let sender = sender.clone();
|
||||
let url = url.clone();
|
||||
async move {
|
||||
debug!("Sending {i}");
|
||||
sender
|
||||
.try_send(RelayRecvDatagram {
|
||||
url,
|
||||
src: EndpointId::from_bytes(&[0u8; 32]).unwrap(),
|
||||
datagrams: Datagrams::from(&i.to_le_bytes()),
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// We expect all of this work to be done in 10 seconds max.
|
||||
if tokio::time::timeout(Duration::from_secs(10), tasks.join_all())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
panic!("Timeout - not all messages between 0 and {capacity} received.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a [`RelayTransport`] that never actually dials a relay (its home
|
||||
/// relay watcher is left unset), just so we get a real `poll_recv` to exercise.
|
||||
fn test_relay_transport() -> RelayTransport {
|
||||
let config = RelayActorConfig {
|
||||
my_relay: HomeRelayWatch::default(),
|
||||
secret_key: SecretKey::from_bytes(&[7u8; 32]),
|
||||
dns_resolver: DnsResolver::new(),
|
||||
proxy_url: None,
|
||||
ipv6_reported: Arc::new(AtomicBool::new(false)),
|
||||
tls_config: CaTlsConfig::insecure_skip_verify()
|
||||
.client_config(default_provider())
|
||||
.expect("infallible"),
|
||||
metrics: Default::default(),
|
||||
relay_map: RelayMap::empty(),
|
||||
};
|
||||
RelayTransport::new(config, CancellationToken::new())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn progress_is_made_for_large_segment_size_datagram_batch() {
|
||||
let mut transport = test_relay_transport();
|
||||
|
||||
let url = staging::default_na_east_relay().url;
|
||||
let src = EndpointId::from_bytes(&[3u8; 32]).unwrap();
|
||||
|
||||
// Fat datagram batch with segment size larger than the buffer
|
||||
let datagrams = Datagrams {
|
||||
ecn: None,
|
||||
segment_size: NonZeroU16::new(2000),
|
||||
contents: Bytes::from(vec![0u8; 4000]),
|
||||
};
|
||||
|
||||
transport.pending_item = Some(RelayRecvDatagram {
|
||||
url,
|
||||
src,
|
||||
datagrams,
|
||||
});
|
||||
|
||||
let waker = std::task::Waker::noop();
|
||||
let mut cx = Context::from_waker(waker);
|
||||
|
||||
// Deliberately smaller than the 2000-byte segment size above
|
||||
let mut storage = [0u8; 1500];
|
||||
let mut metas = [noq_udp::RecvMeta::default()];
|
||||
let mut recv_infos = [RecvInfo::default()];
|
||||
|
||||
let mut progressed = false;
|
||||
// progress does not need to be immediate but within a reasonable number of iterations
|
||||
for _ in 0..10 {
|
||||
let mut bufs = [io::IoSliceMut::new(&mut storage)];
|
||||
match transport.poll_recv(&mut cx, &mut bufs, &mut metas, &mut recv_infos) {
|
||||
Poll::Ready(Ok(_)) | Poll::Pending => {}
|
||||
Poll::Ready(Err(err)) => panic!("poll_recv failed: {err}"),
|
||||
}
|
||||
if transport.pending_item.is_none() {
|
||||
progressed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(progressed, "poll_recv made no progress on batch too large");
|
||||
}
|
||||
}
|
||||
+2030
File diff suppressed because it is too large.
Load diff
Vendored
+576
@@ -0,0 +1,576 @@
|
||||
//! Internal utilities to support testing.
|
||||
use std::{net::Ipv4Addr, sync::Arc};
|
||||
|
||||
use iroh_base::RelayUrl;
|
||||
use iroh_relay::{
|
||||
RelayConfig, RelayMap, RelayQuicConfig,
|
||||
server::{
|
||||
AllowAll, CertConfig, DynAccessControl, QuicConfig, RelayConfig as RelayServerConfig,
|
||||
Server, ServerConfig, SpawnError, TlsConfig,
|
||||
},
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
pub use self::{dns_and_pkarr_servers::DnsPkarrServer, qlog::QlogFileGroup};
|
||||
|
||||
mod qlog;
|
||||
#[cfg(feature = "unstable-custom-transports")]
|
||||
pub mod test_transport;
|
||||
|
||||
/// A drop guard to clean up test infrastructure.
|
||||
///
|
||||
/// After dropping the test infrastructure will asynchronously shutdown and release its
|
||||
/// resources.
|
||||
// Nightly sees the sender as dead code currently, but we only rely on Drop of the
|
||||
// sender.
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct CleanupDropGuard(pub(crate) oneshot::Sender<()>);
|
||||
|
||||
/// Runs a relay server with QUIC enabled suitable for tests.
|
||||
///
|
||||
/// The returned `Url` is the url of the relay server in the returned [`RelayMap`].
|
||||
/// When dropped, the returned [`Server`] does will stop running.
|
||||
pub async fn run_relay_server() -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
|
||||
run_relay_server_with(true).await
|
||||
}
|
||||
|
||||
/// Runs a relay server.
|
||||
///
|
||||
/// If `quic` is set to `true`, it will make the appropriate [`QuicConfig`] from the generated tls certificates and run the quic server at a random free port.
|
||||
///
|
||||
///
|
||||
/// The return value is similar to [`run_relay_server`].
|
||||
pub async fn run_relay_server_with(quic: bool) -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
|
||||
run_relay_server_with_access(quic, Arc::new(AllowAll)).await
|
||||
}
|
||||
|
||||
/// Runs a relay server with a custom access control.
|
||||
///
|
||||
/// See [`run_relay_server_with`] for details on `quic`.
|
||||
pub async fn run_relay_server_with_access(
|
||||
quic: bool,
|
||||
access: Arc<dyn DynAccessControl>,
|
||||
) -> Result<(RelayMap, RelayUrl, Server), SpawnError> {
|
||||
let (_certs, server_config) = iroh_relay::server::testing::self_signed_tls_certs_and_config();
|
||||
|
||||
let tls = TlsConfig::new(
|
||||
(Ipv4Addr::LOCALHOST, 0),
|
||||
CertConfig::Manual { server_config },
|
||||
);
|
||||
|
||||
let mut relay = RelayServerConfig::new((Ipv4Addr::LOCALHOST, 0));
|
||||
relay.tls = Some(tls);
|
||||
relay.key_cache_capacity = Some(1024);
|
||||
relay.access = access;
|
||||
|
||||
let mut config = ServerConfig::default();
|
||||
config.relay = Some(relay);
|
||||
config.quic = quic.then(|| QuicConfig::new((Ipv4Addr::LOCALHOST, 0)));
|
||||
|
||||
let server = Server::spawn(config).await?;
|
||||
let url: RelayUrl = format!("https://{}", server.https_addr().expect("configured"))
|
||||
.parse()
|
||||
.expect("invalid relay url");
|
||||
|
||||
let quic = server
|
||||
.quic_addr()
|
||||
.map(|addr| RelayQuicConfig::new(addr.port()));
|
||||
let n: RelayMap = RelayConfig::new(url.clone(), quic).into();
|
||||
Ok((n, url, server))
|
||||
}
|
||||
|
||||
mod dns_and_pkarr_servers {
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
|
||||
use iroh_base::EndpointId;
|
||||
use url::Url;
|
||||
|
||||
use super::CleanupDropGuard;
|
||||
use crate::{
|
||||
address_lookup::{
|
||||
DnsAddressLookup, DnsAddressLookupBuilder, PkarrPublisher, PkarrPublisherBuilder,
|
||||
},
|
||||
dns::DnsResolver,
|
||||
endpoint::presets::Preset,
|
||||
test_utils::{
|
||||
dns_server::run_dns_server, pkarr_dns_state::State, pkarr_relay::run_pkarr_relay,
|
||||
},
|
||||
};
|
||||
|
||||
/// Handle and drop guard for test DNS and Pkarr servers.
|
||||
///
|
||||
/// Once the struct is dropped the servers will shut down.
|
||||
#[derive(Debug)]
|
||||
pub struct DnsPkarrServer {
|
||||
/// The endpoint origin domain.
|
||||
endpoint_origin: String,
|
||||
/// The shared state of the DNS and Pkarr servers.
|
||||
state: State,
|
||||
/// The socket address of the DNS server.
|
||||
nameserver: SocketAddr,
|
||||
/// The HTTP URL of the Pkarr server.
|
||||
pkarr_url: Url,
|
||||
_dns_drop_guard: CleanupDropGuard,
|
||||
_pkarr_drop_guard: CleanupDropGuard,
|
||||
}
|
||||
|
||||
impl DnsPkarrServer {
|
||||
/// Run DNS and Pkarr servers on localhost.
|
||||
pub async fn run() -> std::io::Result<Self> {
|
||||
Self::run_with_origin("dns.iroh.test".to_string()).await
|
||||
}
|
||||
|
||||
/// Run DNS and Pkarr servers on localhost with the specified `endpoint_origin` domain.
|
||||
pub async fn run_with_origin(endpoint_origin: String) -> std::io::Result<Self> {
|
||||
let state = State::new(endpoint_origin.clone());
|
||||
let (nameserver, dns_drop_guard) = run_dns_server(state.clone()).await?;
|
||||
let (pkarr_url, pkarr_drop_guard) = run_pkarr_relay(state.clone()).await?;
|
||||
Ok(Self {
|
||||
endpoint_origin,
|
||||
nameserver,
|
||||
pkarr_url,
|
||||
state,
|
||||
_dns_drop_guard: dns_drop_guard,
|
||||
_pkarr_drop_guard: pkarr_drop_guard,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a [`Preset`] to apply the DNS address lookup and Pkarr Publisher to an endpoint.
|
||||
pub fn preset(&self) -> impl Preset {
|
||||
struct DnsPkarrPreset {
|
||||
dns_address_lookup: DnsAddressLookupBuilder,
|
||||
pkarr_address_publisher: PkarrPublisherBuilder,
|
||||
dns_resolver: DnsResolver,
|
||||
}
|
||||
|
||||
let preset = DnsPkarrPreset {
|
||||
dns_address_lookup: DnsAddressLookup::builder(self.endpoint_origin.clone()),
|
||||
pkarr_address_publisher: PkarrPublisher::builder(self.pkarr_url.clone()),
|
||||
dns_resolver: self.dns_resolver(),
|
||||
};
|
||||
impl Preset for DnsPkarrPreset {
|
||||
fn apply(self, builder: crate::endpoint::Builder) -> crate::endpoint::Builder {
|
||||
builder
|
||||
.addr_filter(crate::address_lookup::AddrFilter::relay_only())
|
||||
.address_lookup(self.dns_address_lookup)
|
||||
.address_lookup(self.pkarr_address_publisher)
|
||||
.dns_resolver(self.dns_resolver)
|
||||
}
|
||||
}
|
||||
preset
|
||||
}
|
||||
|
||||
/// Create a [`DnsResolver`] configured to use the test DNS server.
|
||||
pub fn dns_resolver(&self) -> DnsResolver {
|
||||
DnsResolver::with_nameserver(self.nameserver)
|
||||
}
|
||||
|
||||
/// Returns the PKARR server HTTP URL.
|
||||
pub fn pkarr_url(&self) -> &Url {
|
||||
&self.pkarr_url
|
||||
}
|
||||
|
||||
/// Wait until a Pkarr announce for an endpoint is published to the server.
|
||||
///
|
||||
/// If `timeout` elapses an error is returned.
|
||||
pub async fn on_endpoint(
|
||||
&self,
|
||||
endpoint_id: &EndpointId,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<()> {
|
||||
self.state.on_endpoint(endpoint_id, timeout).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod dns_server {
|
||||
use std::{
|
||||
future::Future,
|
||||
net::{Ipv4Addr, SocketAddr},
|
||||
};
|
||||
|
||||
use n0_future::future::Boxed as BoxFuture;
|
||||
use simple_dns::{Packet, PacketFlag};
|
||||
use tokio::{net::UdpSocket, sync::oneshot};
|
||||
use tracing::{debug, error, warn};
|
||||
|
||||
use super::CleanupDropGuard;
|
||||
|
||||
/// Trait used by [`run_dns_server`] for answering DNS queries.
|
||||
pub(crate) trait QueryHandler: Send + Sync + 'static {
|
||||
fn resolve(
|
||||
&self,
|
||||
query: &Packet<'_>,
|
||||
reply: &mut Packet<'static>,
|
||||
) -> impl Future<Output = std::io::Result<()>> + Send;
|
||||
}
|
||||
|
||||
pub(crate) type QueryHandlerFunction = Box<
|
||||
dyn Fn(&Packet<'_>, &mut Packet<'static>) -> BoxFuture<std::io::Result<()>>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
>;
|
||||
|
||||
impl QueryHandler for QueryHandlerFunction {
|
||||
fn resolve(
|
||||
&self,
|
||||
query: &Packet<'_>,
|
||||
reply: &mut Packet<'static>,
|
||||
) -> impl Future<Output = std::io::Result<()>> + Send {
|
||||
(self)(query, reply)
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a DNS server.
|
||||
///
|
||||
/// Must pass a [`QueryHandler`] that answers queries.
|
||||
pub(crate) async fn run_dns_server(
|
||||
resolver: impl QueryHandler,
|
||||
) -> std::io::Result<(SocketAddr, CleanupDropGuard)> {
|
||||
let bind_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
|
||||
let socket = UdpSocket::bind(bind_addr).await?;
|
||||
let bound_addr = socket.local_addr()?;
|
||||
let s = TestDnsServer { socket, resolver };
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
tokio::task::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = &mut rx => {
|
||||
debug!("shutting down dns server");
|
||||
}
|
||||
res = s.run() => {
|
||||
if let Err(e) = res {
|
||||
error!("error running dns server {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok((bound_addr, CleanupDropGuard(tx)))
|
||||
}
|
||||
|
||||
struct TestDnsServer<R> {
|
||||
resolver: R,
|
||||
socket: UdpSocket,
|
||||
}
|
||||
|
||||
impl<R: QueryHandler> TestDnsServer<R> {
|
||||
async fn run(self) -> std::io::Result<()> {
|
||||
let mut buf = [0; 1450];
|
||||
loop {
|
||||
let res = self.socket.recv_from(&mut buf).await;
|
||||
let (len, from) = res?;
|
||||
if let Err(err) = self.handle_datagram(from, &buf[..len]).await {
|
||||
warn!(?err, %from, "failed to handle incoming datagram");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_datagram(
|
||||
&self,
|
||||
from: SocketAddr,
|
||||
buf: &[u8],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
let packet = Packet::parse(buf).map_err(std::io::Error::other)?;
|
||||
debug!(questions = ?packet.questions, %from, "received query");
|
||||
let mut reply = Packet::new_reply(packet.id());
|
||||
reply.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE);
|
||||
// Echo the question section, as a real resolver does. The client
|
||||
// validates that the response question matches its query.
|
||||
reply.questions = packet
|
||||
.questions
|
||||
.iter()
|
||||
.map(|q| q.clone().into_owned())
|
||||
.collect();
|
||||
self.resolver.resolve(&packet, &mut reply).await?;
|
||||
debug!(?reply, %from, "send reply");
|
||||
let buf = reply.build_bytes_vec().map_err(std::io::Error::other)?;
|
||||
let len = self.socket.send_to(&buf, from).await?;
|
||||
assert_eq!(len, buf.len(), "failed to send complete packet");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod pkarr_relay {
|
||||
use std::{
|
||||
future::IntoFuture,
|
||||
net::{Ipv4Addr, SocketAddr},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{Path, State},
|
||||
response::IntoResponse,
|
||||
routing::put,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use iroh_base::EndpointId;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::{debug, error, warn};
|
||||
use url::Url;
|
||||
|
||||
use super::CleanupDropGuard;
|
||||
use crate::test_utils::pkarr_dns_state::State as AppState;
|
||||
|
||||
pub(crate) async fn run_pkarr_relay(
|
||||
state: AppState,
|
||||
) -> std::io::Result<(Url, CleanupDropGuard)> {
|
||||
let bind_addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 0));
|
||||
let app = Router::new()
|
||||
.route("/pkarr/{key}", put(pkarr_put))
|
||||
.with_state(state);
|
||||
let listener = tokio::net::TcpListener::bind(bind_addr).await?;
|
||||
let bound_addr = listener.local_addr()?;
|
||||
let url: Url = format!("http://{bound_addr}/pkarr")
|
||||
.parse()
|
||||
.expect("valid url");
|
||||
|
||||
let (tx, mut rx) = oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let serve = axum::serve(listener, app);
|
||||
tokio::select! {
|
||||
_ = &mut rx => {
|
||||
debug!("shutting down pkarr server");
|
||||
}
|
||||
res = serve.into_future() => {
|
||||
if let Err(e) = res {
|
||||
error!("pkarr server error: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok((url, CleanupDropGuard(tx)))
|
||||
}
|
||||
|
||||
async fn pkarr_put(
|
||||
State(state): State<AppState>,
|
||||
Path(key): Path<String>,
|
||||
body: Bytes,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let key = EndpointId::from_z32(&key).map_err(std::io::Error::other)?;
|
||||
let signed_packet = iroh_dns::pkarr::SignedPacket::from_relay_payload(&key, &body)
|
||||
.map_err(std::io::Error::other)?;
|
||||
let _updated = state.upsert(signed_packet)?;
|
||||
Ok(http::StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AppError(std::io::Error);
|
||||
impl<T: Into<std::io::Error>> From<T> for AppError {
|
||||
fn from(value: T) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
}
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
warn!(err = ?self, "request failed");
|
||||
(http::StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod pkarr_dns_state {
|
||||
use std::{
|
||||
collections::{HashMap, hash_map},
|
||||
future::Future,
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use iroh_base::EndpointId;
|
||||
use iroh_dns::{IROH_TXT_NAME, endpoint_info::EndpointInfo, pkarr::SignedPacket};
|
||||
use simple_dns::{
|
||||
CLASS, Name, Packet, ResourceRecord,
|
||||
rdata::{RData, TXT},
|
||||
};
|
||||
use tracing::debug;
|
||||
|
||||
use crate::test_utils::dns_server::QueryHandler;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct State {
|
||||
packets: Arc<Mutex<HashMap<EndpointId, SignedPacket>>>,
|
||||
origin: String,
|
||||
notify: Arc<tokio::sync::Notify>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub(crate) fn new(origin: String) -> Self {
|
||||
Self {
|
||||
packets: Default::default(),
|
||||
origin,
|
||||
notify: Arc::new(tokio::sync::Notify::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_update(&self) -> tokio::sync::futures::Notified<'_> {
|
||||
self.notify.notified()
|
||||
}
|
||||
|
||||
pub(crate) async fn on_endpoint(
|
||||
&self,
|
||||
endpoint: &EndpointId,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<()> {
|
||||
let timeout = tokio::time::sleep(timeout);
|
||||
tokio::pin!(timeout);
|
||||
while self.get(endpoint, |p| {
|
||||
let endpoint_info = p
|
||||
.as_ref()
|
||||
.and_then(|p| EndpointInfo::from_pkarr_signed_packet(p).ok());
|
||||
debug!("got info {:#?}", endpoint_info);
|
||||
// Wait until we have endpoint info with actual addressing data,
|
||||
// not just an empty initial publish.
|
||||
endpoint_info
|
||||
.as_ref()
|
||||
.is_none_or(|info| info.data.addrs().next().is_none())
|
||||
}) {
|
||||
tokio::select! {
|
||||
_ = &mut timeout => return Err(std::io::Error::other("timeout")),
|
||||
_ = self.on_update() => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn upsert(&self, signed_packet: SignedPacket) -> std::io::Result<bool> {
|
||||
let endpoint_id = signed_packet.public_key();
|
||||
let mut map = self.packets.lock().expect("poisoned");
|
||||
let updated = match map.entry(endpoint_id) {
|
||||
hash_map::Entry::Vacant(e) => {
|
||||
e.insert(signed_packet);
|
||||
true
|
||||
}
|
||||
hash_map::Entry::Occupied(mut e) => {
|
||||
if signed_packet.more_recent_than(e.get()) {
|
||||
e.insert(signed_packet);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
if updated {
|
||||
self.notify.notify_waiters();
|
||||
}
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
/// Returns a mutex guard, do not hold over await points
|
||||
pub(crate) fn get<F, T>(&self, endpoint_id: &EndpointId, cb: F) -> T
|
||||
where
|
||||
F: FnOnce(Option<&mut SignedPacket>) -> T,
|
||||
{
|
||||
let mut map = self.packets.lock().expect("poisoned");
|
||||
let packet = map.get_mut(endpoint_id);
|
||||
cb(packet)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_dns(
|
||||
&self,
|
||||
query: &Packet<'_>,
|
||||
reply: &mut Packet<'static>,
|
||||
ttl: u32,
|
||||
) -> std::io::Result<()> {
|
||||
for question in &query.questions {
|
||||
let domain_name = question.qname.to_string();
|
||||
let Some(endpoint_id) = endpoint_id_from_domain_name(&domain_name) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
self.get(&endpoint_id, |packet| {
|
||||
if let Some(packet) = packet {
|
||||
let endpoint_info = EndpointInfo::from_pkarr_signed_packet(packet)
|
||||
.map_err(std::io::Error::other)?;
|
||||
for record in
|
||||
endpoint_info_to_dns_records(&endpoint_info, &self.origin, ttl)
|
||||
{
|
||||
reply.answers.push(record);
|
||||
}
|
||||
}
|
||||
Ok::<_, std::io::Error>(())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl QueryHandler for State {
|
||||
fn resolve(
|
||||
&self,
|
||||
query: &Packet<'_>,
|
||||
reply: &mut Packet<'static>,
|
||||
) -> impl Future<Output = std::io::Result<()>> + Send {
|
||||
const TTL: u32 = 30;
|
||||
let res = self.resolve_dns(query, reply, TTL);
|
||||
std::future::ready(res)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a [`EndpointId`] from a DNS domain name.
|
||||
///
|
||||
/// Splits the domain name into labels on each dot. Expects the first label to be
|
||||
/// [`IROH_TXT_NAME`] and the second label to be a z32 encoded [`EndpointId`]. Ignores
|
||||
/// subsequent labels.
|
||||
///
|
||||
/// Returns a [`EndpointId`] if parsed successfully, otherwise `None`.
|
||||
fn endpoint_id_from_domain_name(name: &str) -> Option<EndpointId> {
|
||||
let mut labels = name.split(".");
|
||||
let label = labels.next()?;
|
||||
if label != IROH_TXT_NAME {
|
||||
return None;
|
||||
}
|
||||
let label = labels.next()?;
|
||||
let endpoint_id = EndpointId::from_z32(label).ok()?;
|
||||
Some(endpoint_id)
|
||||
}
|
||||
|
||||
/// Converts an [`EndpointInfo`] into simple-dns [`ResourceRecord`]s.
|
||||
fn endpoint_info_to_dns_records(
|
||||
endpoint_info: &EndpointInfo,
|
||||
origin: &str,
|
||||
ttl: u32,
|
||||
) -> Vec<ResourceRecord<'static>> {
|
||||
let txt_strings = endpoint_info.to_txt_strings();
|
||||
to_dns_records(txt_strings, endpoint_info.endpoint_id, origin, ttl)
|
||||
}
|
||||
|
||||
/// Converts TXT strings to simple-dns [`ResourceRecord`]s.
|
||||
fn to_dns_records(
|
||||
txt_strings: Vec<String>,
|
||||
endpoint_id: EndpointId,
|
||||
origin: &str,
|
||||
ttl: u32,
|
||||
) -> Vec<ResourceRecord<'static>> {
|
||||
let name = format!("{IROH_TXT_NAME}.{}.{origin}", endpoint_id.to_z32());
|
||||
let name = Name::new(&name).expect("invalid name").into_owned();
|
||||
txt_strings
|
||||
.into_iter()
|
||||
.map(move |s| {
|
||||
let txt = TXT::new()
|
||||
.with_string(&s)
|
||||
.expect("invalid TXT string")
|
||||
.into_owned();
|
||||
let rdata = RData::TXT(txt);
|
||||
ResourceRecord::new(name.clone(), CLASS::IN, ttl, rdata)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use iroh_base::EndpointId;
|
||||
use n0_error::Result;
|
||||
|
||||
#[test]
|
||||
fn test_endpoint_id_from_domain_name() -> Result {
|
||||
let name = "_iroh.dgjpkxyn3zyrk3zfads5duwdgbqpkwbjxfj4yt7rezidr3fijccy.dns.iroh.link.";
|
||||
let endpoint_id = super::endpoint_id_from_domain_name(name);
|
||||
let expected: EndpointId =
|
||||
"1992d53c02cdc04566e5c0edb1ce83305cd550297953a047a445ea3264b54b18".parse()?;
|
||||
assert_eq!(endpoint_id, Some(expected));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
//! Utils for emitting qlog files from iroh endpoint.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
#[cfg(feature = "qlog")]
|
||||
use std::sync::Arc;
|
||||
|
||||
use n0_error::Result;
|
||||
#[cfg(feature = "qlog")]
|
||||
use n0_future::time::Instant;
|
||||
|
||||
#[cfg(feature = "qlog")]
|
||||
use crate::endpoint::QlogFileFactory;
|
||||
use crate::endpoint::QuicTransportConfig;
|
||||
|
||||
/// Builder to create one or more related qlog configs.
|
||||
///
|
||||
/// This struct is available independently of feature flags, but if the "qlog" feature is not enabled
|
||||
/// it does not do anything.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct QlogFileGroup {
|
||||
#[cfg(feature = "qlog")]
|
||||
directory: PathBuf,
|
||||
#[cfg(feature = "qlog")]
|
||||
title: String,
|
||||
#[cfg(feature = "qlog")]
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
impl QlogFileGroup {
|
||||
/// Creates a new [`QlogFileGroup`] that is only enabled if feature flags and environment variables match.
|
||||
///
|
||||
/// The qlog files will be written to `CARGO_MANIFEST_DIR/qlog`.
|
||||
///
|
||||
/// The [`QlogFileGroup`] can be used independent of feature flags, but it will only emit qlog files
|
||||
/// if the "qlog" feature is enabled and the environment variable IROH_TEST_QLOG is set to 1.
|
||||
pub fn from_env(title: impl ToString) -> Self {
|
||||
let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("qlog");
|
||||
Self::new(directory, title)
|
||||
}
|
||||
|
||||
/// Creates a new [`QlogFileGroup`] that writes qlog files to the specified directory.
|
||||
///
|
||||
/// The [`QlogFileGroup`] can be used independent of feature flags, but it will only emit qlog files
|
||||
/// if the "qlog" feature is enabled and the environment variable IROH_TEST_QLOG is set to 1.
|
||||
pub fn new(directory: impl AsRef<Path>, title: impl ToString) -> Self {
|
||||
#[cfg(not(feature = "qlog"))]
|
||||
let this = {
|
||||
let _ = (directory, title);
|
||||
Self {}
|
||||
};
|
||||
|
||||
#[cfg(feature = "qlog")]
|
||||
let this = Self {
|
||||
title: title.to_string(),
|
||||
directory: directory.as_ref().to_owned(),
|
||||
start: Instant::now(),
|
||||
};
|
||||
|
||||
this
|
||||
}
|
||||
|
||||
/// Creates a [`QuicTransportConfig`] that emits qlog files, if enabled.
|
||||
///
|
||||
/// If the "qlog" feature is enabled, and the environment variable IROH_TEST_QLOG is set,
|
||||
/// this returns a transport config that writes qlog configs to the configured output directory.
|
||||
/// Otherwise, a default transport config is returned.
|
||||
pub fn create(&self, name: impl ToString) -> Result<QuicTransportConfig> {
|
||||
#[cfg(not(feature = "qlog"))]
|
||||
{
|
||||
let _name = name;
|
||||
Ok(QuicTransportConfig::default())
|
||||
}
|
||||
#[cfg(feature = "qlog")]
|
||||
{
|
||||
let mut builder = QuicTransportConfig::builder();
|
||||
|
||||
if std::env::var("IROH_TEST_QLOG").is_ok() {
|
||||
let prefix = format!("{}.{}", self.title, name.to_string());
|
||||
let factory = QlogFileFactory::new(self.directory.clone())
|
||||
.with_prefix(prefix)
|
||||
.with_start_instant(self.start.into());
|
||||
builder = builder.qlog_factory(Arc::new(factory));
|
||||
}
|
||||
Ok(builder.build())
|
||||
}
|
||||
}
|
||||
}
|
||||
+744
@@ -0,0 +1,744 @@
|
||||
//! In-memory test transport for testing.
|
||||
//!
|
||||
//! This module provides [`TestNetwork`] and [`TestTransport`] for testing
|
||||
//! using in-memory channels instead of real network transports.
|
||||
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
io,
|
||||
sync::{Arc, Mutex},
|
||||
task::Poll,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh_base::{CustomAddr, EndpointId, TransportAddr};
|
||||
use tokio::sync::mpsc::{self, error::TrySendError};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
address_lookup::{AddressLookup, EndpointData, EndpointInfo, Item},
|
||||
endpoint::{
|
||||
Builder,
|
||||
presets::Preset,
|
||||
transports::{CustomEndpoint, CustomSender, CustomTransport, RecvInfo, Transmit},
|
||||
},
|
||||
};
|
||||
|
||||
/// The transport ID used by [`TestNetwork`].
|
||||
///
|
||||
/// See `TRANSPORTS.md` for the registry of transport IDs.
|
||||
pub const TEST_TRANSPORT_ID: u64 = 0x20;
|
||||
|
||||
/// An outgoing packet that can be sent across channels.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Packet {
|
||||
pub(crate) data: Bytes,
|
||||
pub(crate) from: CustomAddr,
|
||||
}
|
||||
|
||||
/// A test transport for use with [`TestNetwork`].
|
||||
///
|
||||
/// Implements [`CustomTransport`] and [`CustomEndpoint`] for testing.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TestTransport {
|
||||
id: EndpointId,
|
||||
id_watchable: n0_watcher::Watchable<Vec<CustomAddr>>,
|
||||
network: TestNetwork,
|
||||
}
|
||||
|
||||
impl Preset for Arc<TestTransport> {
|
||||
/// Configures the builder with this transport and the network's address lookup.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// let network = TestNetwork::new();
|
||||
/// let transport = network.create_transport(secret_key.public())?;
|
||||
/// let ep = Endpoint::builder()
|
||||
/// .secret_key(secret_key)
|
||||
/// .preset(transport)
|
||||
/// .bind()
|
||||
/// .await?;
|
||||
/// ```
|
||||
fn apply(self, builder: Builder) -> Builder {
|
||||
builder
|
||||
.add_custom_transport(self.clone())
|
||||
.address_lookup(self.network.address_lookup())
|
||||
}
|
||||
}
|
||||
|
||||
/// A simulated network for testing custom transports.
|
||||
///
|
||||
/// This allows creating multiple [`TestTransport`] instances that can communicate
|
||||
/// with each other through in-memory channels.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// use iroh::test_utils::custom_transport::TestNetwork;
|
||||
///
|
||||
/// let network = TestNetwork::new();
|
||||
/// let transport1 = network.create_transport(endpoint_id1)?;
|
||||
/// let transport2 = network.create_transport(endpoint_id2)?;
|
||||
/// // transport1 and transport2 can now communicate via the network
|
||||
/// ```
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TestNetwork {
|
||||
inner: Arc<Mutex<TestNetworkInner>>,
|
||||
}
|
||||
|
||||
impl TestNetwork {
|
||||
/// Creates a new empty test network.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Creates an address lookup service for this network.
|
||||
pub fn address_lookup(&self) -> impl AddressLookup {
|
||||
TestAddrLookup {
|
||||
network: self.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new test transport for the given endpoint ID.
|
||||
///
|
||||
/// Returns an error if the ID already exists in the network.
|
||||
pub fn create_transport(&self, id: EndpointId) -> io::Result<Arc<TestTransport>> {
|
||||
let id_custom = to_custom_addr(id);
|
||||
let mut guard = self.inner.lock().expect("poisoned");
|
||||
if guard.channels.contains_key(&id) {
|
||||
return Err(io::Error::other("endpoint ID already exists in network"));
|
||||
}
|
||||
guard.channels.insert(id, mpsc::channel(256));
|
||||
drop(guard);
|
||||
Ok(Arc::new(TestTransport {
|
||||
id_watchable: n0_watcher::Watchable::new(vec![id_custom]),
|
||||
network: self.clone(),
|
||||
id,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestAddrLookup {
|
||||
network: TestNetwork,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct TestNetworkInner {
|
||||
channels: BTreeMap<EndpointId, (mpsc::Sender<Packet>, mpsc::Receiver<Packet>)>,
|
||||
}
|
||||
|
||||
impl AddressLookup for TestAddrLookup {
|
||||
fn publish(&self, _data: &EndpointData) {}
|
||||
|
||||
fn resolve(
|
||||
&self,
|
||||
endpoint_id: EndpointId,
|
||||
) -> Option<n0_future::stream::Boxed<Result<Item, crate::address_lookup::Error>>> {
|
||||
if self
|
||||
.network
|
||||
.inner
|
||||
.lock()
|
||||
.expect("poisoned")
|
||||
.channels
|
||||
.contains_key(&endpoint_id)
|
||||
{
|
||||
Some(Box::pin(n0_future::stream::once(Ok(Item::new(
|
||||
EndpointInfo {
|
||||
endpoint_id,
|
||||
data: EndpointData::from_iter([TransportAddr::Custom(CustomAddr::from_parts(
|
||||
TEST_TRANSPORT_ID,
|
||||
endpoint_id.as_bytes(),
|
||||
))]),
|
||||
},
|
||||
"test discovery",
|
||||
None,
|
||||
)))))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TestSender {
|
||||
id: EndpointId,
|
||||
network: TestNetwork,
|
||||
}
|
||||
|
||||
/// Converts an endpoint ID to a custom address for this test transport.
|
||||
pub fn to_custom_addr(endpoint: EndpointId) -> CustomAddr {
|
||||
CustomAddr::from((TEST_TRANSPORT_ID, &endpoint.as_bytes()[..]))
|
||||
}
|
||||
|
||||
fn try_parse_custom_addr(addr: &CustomAddr) -> io::Result<EndpointId> {
|
||||
if addr.id() != TEST_TRANSPORT_ID {
|
||||
return Err(io::Error::other("unexpected transport id"));
|
||||
}
|
||||
let key_bytes: &[u8; 32] = addr
|
||||
.data()
|
||||
.try_into()
|
||||
.map_err(|_| io::Error::other("wrong key length"))?;
|
||||
EndpointId::from_bytes(key_bytes).map_err(|_| io::Error::other("KeyParseError"))
|
||||
}
|
||||
|
||||
impl TestSender {
|
||||
fn send_sync(&self, dst: &CustomAddr, packets: Vec<Packet>) -> io::Result<()> {
|
||||
let to_id = try_parse_custom_addr(dst)?;
|
||||
let guard = self.network.inner.lock().expect("poisoned");
|
||||
let (s, _) = guard
|
||||
.channels
|
||||
.get(&to_id)
|
||||
.ok_or_else(|| io::Error::other("Unknown endpoint"))?;
|
||||
for packet in packets {
|
||||
let len = packet.data.len();
|
||||
match s.try_send(packet) {
|
||||
Ok(_) => info!(
|
||||
"send {} -> {}: sent {} bytes",
|
||||
self.id.fmt_short(),
|
||||
to_id.fmt_short(),
|
||||
len
|
||||
),
|
||||
Err(TrySendError::Full(_)) => info!(
|
||||
"send {} -> {}: dropped {} bytes",
|
||||
self.id.fmt_short(),
|
||||
to_id.fmt_short(),
|
||||
len
|
||||
),
|
||||
Err(TrySendError::Closed(_)) => return Err(io::Error::other("channel closed")),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn split(&self, transmit: &Transmit) -> impl Iterator<Item = Packet> {
|
||||
let from = to_custom_addr(self.id);
|
||||
let segment_size = transmit.segment_size.unwrap_or(transmit.contents.len());
|
||||
transmit
|
||||
.contents
|
||||
.chunks(segment_size)
|
||||
.map(move |slice| Packet {
|
||||
from: from.clone(),
|
||||
data: Bytes::copy_from_slice(slice),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomSender for TestSender {
|
||||
fn is_valid_send_addr(&self, addr: &CustomAddr) -> bool {
|
||||
addr.id() == TEST_TRANSPORT_ID
|
||||
}
|
||||
|
||||
fn poll_send(
|
||||
&self,
|
||||
_cx: &mut std::task::Context,
|
||||
dst: &CustomAddr,
|
||||
_src: Option<&CustomAddr>,
|
||||
transmit: &Transmit<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let packets = self.split(transmit).collect();
|
||||
Poll::Ready(self.send_sync(dst, packets))
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomTransport for TestTransport {
|
||||
fn bind(&self) -> io::Result<Box<dyn CustomEndpoint>> {
|
||||
Ok(Box::new(self.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomEndpoint for TestTransport {
|
||||
fn watch_local_addrs(&self) -> n0_watcher::Direct<Vec<CustomAddr>> {
|
||||
self.id_watchable.watch()
|
||||
}
|
||||
|
||||
fn create_sender(&self) -> Arc<dyn CustomSender> {
|
||||
Arc::new(TestSender {
|
||||
id: self.id,
|
||||
network: self.network.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn poll_recv(
|
||||
&mut self,
|
||||
cx: &mut std::task::Context,
|
||||
bufs: &mut [io::IoSliceMut<'_>],
|
||||
metas: &mut [noq_udp::RecvMeta],
|
||||
recv_infos: &mut [RecvInfo],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
|
||||
assert_eq!(
|
||||
bufs.len(),
|
||||
recv_infos.len(),
|
||||
"non matching bufs & recv_infos"
|
||||
);
|
||||
let n = bufs.len();
|
||||
if n == 0 {
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
let mut guard = self.network.inner.lock().expect("poisoned");
|
||||
let Some((_, r)) = guard.channels.get_mut(&self.id) else {
|
||||
info!("me: {} not found in channels", self.id.fmt_short());
|
||||
return Poll::Ready(Ok(0));
|
||||
};
|
||||
let mut packets = Vec::new();
|
||||
match r.poll_recv_many(cx, &mut packets, n) {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
Poll::Ready(0) => return Poll::Ready(Err(io::Error::other("channel closed"))),
|
||||
Poll::Ready(n) => n,
|
||||
};
|
||||
let mut count = 0;
|
||||
for (i, packet) in packets.into_iter().enumerate() {
|
||||
let meta = &mut metas[i];
|
||||
let buf = &mut bufs[i];
|
||||
let recv_info = &mut recv_infos[i];
|
||||
if buf.len() < packet.data.len() {
|
||||
break;
|
||||
}
|
||||
let from = try_parse_custom_addr(&packet.from).expect("valid custom addr");
|
||||
info!(
|
||||
"recv {} -> {}: copying {} bytes",
|
||||
from.fmt_short(),
|
||||
self.id.fmt_short(),
|
||||
packet.data.len()
|
||||
);
|
||||
buf[..packet.data.len()].copy_from_slice(&packet.data);
|
||||
*recv_info = RecvInfo::new(packet.from, Some(to_custom_addr(self.id)));
|
||||
meta.len = packet.data.len();
|
||||
meta.stride = packet.data.len();
|
||||
count += 1;
|
||||
}
|
||||
if count > 0 {
|
||||
info!("recv {}: filled {count} slots", self.id.fmt_short());
|
||||
Poll::Ready(Ok(count))
|
||||
} else {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
use iroh_relay::RelayMap;
|
||||
use n0_error::{Result, StdResultExt};
|
||||
use n0_tracing_test::traced_test;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
Endpoint, EndpointAddr, RelayMode, SecretKey, TransportAddr,
|
||||
endpoint::{Builder, Connection, presets, transports::AddrKind},
|
||||
protocol::{AcceptError, ProtocolHandler, Router},
|
||||
socket::biased_rtt_path_selector::{BiasedRttPathSelector, TransportBias},
|
||||
test_utils::run_relay_server,
|
||||
};
|
||||
|
||||
const ECHO_ALPN: &[u8] = b"test/echo";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Echo;
|
||||
|
||||
impl ProtocolHandler for Echo {
|
||||
async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
|
||||
let (mut send, mut recv) = connection.accept_bi().await?;
|
||||
tokio::io::copy(&mut recv, &mut send).await?;
|
||||
send.finish()?;
|
||||
connection.closed().await;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for endpoint builder.
|
||||
#[derive(Clone, Default)]
|
||||
struct EndpointConfig {
|
||||
custom_bias: Option<TransportBias>,
|
||||
keep_ip: bool,
|
||||
relay_map: Option<RelayMap>,
|
||||
}
|
||||
|
||||
impl EndpointConfig {
|
||||
fn with_custom_bias(mut self, bias: TransportBias) -> Self {
|
||||
self.custom_bias = Some(bias);
|
||||
self
|
||||
}
|
||||
|
||||
fn with_ip(mut self) -> Self {
|
||||
self.keep_ip = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn with_relay(mut self, relay_map: RelayMap) -> Self {
|
||||
self.relay_map = Some(relay_map);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a basic endpoint builder with the given secret key and custom transport.
|
||||
fn endpoint_builder(
|
||||
secret_key: SecretKey,
|
||||
transport: Arc<TestTransport>,
|
||||
config: EndpointConfig,
|
||||
) -> Builder {
|
||||
let relay_mode = match config.relay_map {
|
||||
Some(map) => RelayMode::Custom(map),
|
||||
None => RelayMode::Disabled,
|
||||
};
|
||||
let mut builder = Endpoint::builder(presets::N0)
|
||||
.secret_key(secret_key)
|
||||
.relay_mode(relay_mode)
|
||||
.ca_tls_config(crate::tls::CaTlsConfig::insecure_skip_verify())
|
||||
.add_custom_transport(transport);
|
||||
if let Some(bias) = config.custom_bias {
|
||||
builder = builder.path_selector(Arc::new(
|
||||
BiasedRttPathSelector::default()
|
||||
.with_bias(AddrKind::Custom(TEST_TRANSPORT_ID), bias),
|
||||
));
|
||||
}
|
||||
if !config.keep_ip {
|
||||
builder = builder.clear_ip_transports();
|
||||
}
|
||||
builder
|
||||
}
|
||||
|
||||
/// Creates an address with both IP (from endpoint) and custom transport addresses.
|
||||
fn mixed_addr(ep: &Endpoint, endpoint_id: EndpointId) -> EndpointAddr {
|
||||
let ep_addr = ep.addr();
|
||||
let custom_addr = to_custom_addr(endpoint_id);
|
||||
EndpointAddr::from_parts(
|
||||
endpoint_id,
|
||||
ep_addr
|
||||
.addrs
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(std::iter::once(TransportAddr::Custom(custom_addr))),
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates an address with only the custom transport address.
|
||||
fn custom_only_addr(endpoint_id: EndpointId) -> EndpointAddr {
|
||||
EndpointAddr::from_parts(
|
||||
endpoint_id,
|
||||
std::iter::once(TransportAddr::Custom(to_custom_addr(endpoint_id))),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns true if the selected path is the custom transport.
|
||||
fn is_custom_selected(conn: &crate::endpoint::Connection) -> bool {
|
||||
let paths = conn.paths();
|
||||
paths.iter().find(|p| p.is_selected()).is_some_and(
|
||||
|p| matches!(p.remote_addr(), TransportAddr::Custom(a) if a.id() == TEST_TRANSPORT_ID),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns true if either
|
||||
/// - we have both IP and custom paths, and the selected path is IP.
|
||||
/// - we only have one path
|
||||
fn is_ip_selected_from_ip_and_custom(conn: &crate::endpoint::Connection) -> bool {
|
||||
let paths = conn.paths();
|
||||
let has_ip = paths.iter().any(|p| p.remote_addr().is_ip());
|
||||
let has_custom = paths.iter().any(|p| p.remote_addr().is_custom());
|
||||
if !has_ip || !has_custom {
|
||||
return true;
|
||||
}
|
||||
paths
|
||||
.iter()
|
||||
.any(|p| p.is_selected() && p.remote_addr().is_ip())
|
||||
}
|
||||
|
||||
/// Returns true if the selected path is a relay transport.
|
||||
fn is_relay_selected(conn: &crate::endpoint::Connection) -> bool {
|
||||
let paths = conn.paths();
|
||||
paths
|
||||
.iter()
|
||||
.find(|p| p.is_selected())
|
||||
.is_some_and(|p| p.is_relay())
|
||||
}
|
||||
|
||||
/// Verifies echo works over the connection.
|
||||
async fn verify_echo(conn: &crate::endpoint::Connection, msg: &[u8]) -> Result<()> {
|
||||
let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
|
||||
send.write_all(msg).await.anyerr()?;
|
||||
send.finish().anyerr()?;
|
||||
let response = recv.read_to_end(100).await.anyerr()?;
|
||||
assert_eq!(response, msg);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test custom transport only - no IP, no relay, dial by custom address.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_custom_transport_only() -> Result<()> {
|
||||
let network = TestNetwork::new();
|
||||
let s1 = SecretKey::generate();
|
||||
let s2 = SecretKey::generate();
|
||||
|
||||
let t1 = network.create_transport(s1.public())?;
|
||||
let t2 = network.create_transport(s2.public())?;
|
||||
|
||||
let ep1 = endpoint_builder(s1, t1, EndpointConfig::default())
|
||||
.bind()
|
||||
.await?;
|
||||
let ep2 = endpoint_builder(s2.clone(), t2, EndpointConfig::default())
|
||||
.bind()
|
||||
.await?;
|
||||
let router = Router::builder(ep2).accept(ECHO_ALPN, Echo).spawn();
|
||||
|
||||
let conn = ep1
|
||||
.connect(custom_only_addr(s2.public()), ECHO_ALPN)
|
||||
.await?;
|
||||
|
||||
// Verify exactly one path exists and it's the custom transport
|
||||
let paths = conn.paths();
|
||||
assert_eq!(paths.len(), 1, "Expected exactly one path");
|
||||
assert!(
|
||||
is_custom_selected(&conn),
|
||||
"Custom transport should be selected"
|
||||
);
|
||||
|
||||
verify_echo(&conn, b"custom only").await?;
|
||||
conn.close(0u32.into(), b"done");
|
||||
router.shutdown().await.anyerr()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test that custom transports can surface a local address per incoming packet.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_custom_transport_local_addr() -> Result<()> {
|
||||
use crate::endpoint::LocalTransportAddr;
|
||||
|
||||
let network = TestNetwork::new();
|
||||
let s1 = SecretKey::generate();
|
||||
let s2 = SecretKey::generate();
|
||||
|
||||
let t1 = network.create_transport(s1.public())?;
|
||||
let t2 = network.create_transport(s2.public())?;
|
||||
|
||||
let ep1 = endpoint_builder(s1, t1, EndpointConfig::default())
|
||||
.bind()
|
||||
.await?;
|
||||
let ep2 = endpoint_builder(s2.clone(), t2, EndpointConfig::default())
|
||||
.alpns(vec![ECHO_ALPN.to_vec()])
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
let connect = tokio::spawn({
|
||||
let ep1 = ep1.clone();
|
||||
let dst = custom_only_addr(s2.public());
|
||||
async move { ep1.connect(dst, ECHO_ALPN).await }
|
||||
});
|
||||
|
||||
let incoming = ep2.accept().await.expect("incoming");
|
||||
assert_eq!(
|
||||
incoming.local_addr(),
|
||||
LocalTransportAddr::Custom(Some(to_custom_addr(s2.public()))),
|
||||
);
|
||||
let _conn = incoming.accept().anyerr()?.await.anyerr()?;
|
||||
|
||||
connect.await.anyerr()??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test that custom transport is selected over IP when given an RTT advantage.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_custom_transport_wins_over_ip() -> Result<()> {
|
||||
let network = TestNetwork::new();
|
||||
let s1 = SecretKey::generate();
|
||||
let s2 = SecretKey::generate();
|
||||
|
||||
let t1 = network.create_transport(s1.public())?;
|
||||
let t2 = network.create_transport(s2.public())?;
|
||||
|
||||
// Strong RTT advantage for custom transport
|
||||
let custom_bias = TransportBias::primary().with_rtt_advantage(Duration::from_secs(10));
|
||||
let config = EndpointConfig::default()
|
||||
.with_ip()
|
||||
.with_custom_bias(custom_bias);
|
||||
|
||||
let ep1 = endpoint_builder(s1, t1, config.clone()).bind().await?;
|
||||
let ep2 = endpoint_builder(s2.clone(), t2, config).bind().await?;
|
||||
let router = Router::builder(ep2.clone()).accept(ECHO_ALPN, Echo).spawn();
|
||||
|
||||
let conn = ep1
|
||||
.connect(mixed_addr(&ep2, s2.public()), ECHO_ALPN)
|
||||
.await?;
|
||||
|
||||
// Wait for paths to settle
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
|
||||
assert!(
|
||||
is_custom_selected(&conn),
|
||||
"Custom transport should be selected with RTT advantage"
|
||||
);
|
||||
|
||||
verify_echo(&conn, b"custom wins").await?;
|
||||
conn.close(0u32.into(), b"done");
|
||||
router.shutdown().await.anyerr()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test that IP is selected over custom transport when custom has an RTT disadvantage.
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_ip_wins_over_custom() -> Result<()> {
|
||||
let network = TestNetwork::new();
|
||||
let s1 = SecretKey::generate();
|
||||
let s2 = SecretKey::generate();
|
||||
|
||||
let t1 = network.create_transport(s1.public())?;
|
||||
let t2 = network.create_transport(s2.public())?;
|
||||
|
||||
// Strong RTT disadvantage for custom transport
|
||||
let custom_bias = TransportBias::primary().with_rtt_disadvantage(Duration::from_secs(10));
|
||||
let config = EndpointConfig::default()
|
||||
.with_ip()
|
||||
.with_custom_bias(custom_bias);
|
||||
|
||||
let ep1 = endpoint_builder(s1, t1, config.clone()).bind().await?;
|
||||
let ep2 = endpoint_builder(s2.clone(), t2, config).bind().await?;
|
||||
let router = Router::builder(ep2.clone()).accept(ECHO_ALPN, Echo).spawn();
|
||||
|
||||
let conn = ep1
|
||||
.connect(mixed_addr(&ep2, s2.public()), ECHO_ALPN)
|
||||
.await?;
|
||||
|
||||
// Wait for paths to settle
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
assert!(
|
||||
is_ip_selected_from_ip_and_custom(&conn),
|
||||
"IP transport should be selected when custom has RTT disadvantage"
|
||||
);
|
||||
|
||||
verify_echo(&conn, b"ip wins").await?;
|
||||
conn.close(0u32.into(), b"done");
|
||||
router.shutdown().await.anyerr()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test that custom transport (primary) is selected over relay (backup).
|
||||
///
|
||||
/// This test first connects using only the relay address, then reconnects with
|
||||
/// both relay and custom addresses to verify the custom transport (primary) wins
|
||||
/// over the relay (backup).
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_custom_transport_wins_over_relay() -> Result<()> {
|
||||
let (relay_map, _relay_url, _guard) = run_relay_server().await?;
|
||||
let network = TestNetwork::new();
|
||||
let s1 = SecretKey::generate();
|
||||
let s2 = SecretKey::generate();
|
||||
|
||||
let t1 = network.create_transport(s1.public())?;
|
||||
let t2 = network.create_transport(s2.public())?;
|
||||
|
||||
// Custom transport is primary by default, relay is backup
|
||||
let config = EndpointConfig::default().with_relay(relay_map.clone());
|
||||
|
||||
let ep1 = endpoint_builder(s1, t1, config.clone()).bind().await?;
|
||||
let ep2 = endpoint_builder(s2.clone(), t2, config).bind().await?;
|
||||
|
||||
// Wait for relay connection to be established
|
||||
ep1.online().await;
|
||||
ep2.online().await;
|
||||
|
||||
let router = Router::builder(ep2.clone()).accept(ECHO_ALPN, Echo).spawn();
|
||||
|
||||
// Get all addresses including relay and custom
|
||||
let ep2_addr = ep2.addr();
|
||||
let custom_addr = to_custom_addr(s2.public());
|
||||
|
||||
// Debug: print ep2 address to see what's available
|
||||
eprintln!("ep2 address: {:?}", ep2_addr);
|
||||
|
||||
// Create address with both relay and custom
|
||||
let all_addrs = EndpointAddr::from_parts(
|
||||
s2.public(),
|
||||
ep2_addr
|
||||
.addrs
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(std::iter::once(TransportAddr::Custom(custom_addr))),
|
||||
);
|
||||
eprintln!("Connecting with all addresses: {:?}", all_addrs);
|
||||
|
||||
// First, connect with relay-only to verify relay works
|
||||
let relay_addrs: Vec<_> = ep2_addr
|
||||
.addrs
|
||||
.iter()
|
||||
.filter(|a| matches!(a, TransportAddr::Relay(_)))
|
||||
.cloned()
|
||||
.collect();
|
||||
eprintln!("Relay addresses in ep2_addr: {:?}", relay_addrs);
|
||||
|
||||
// If there are no relay addresses, skip the relay-first test
|
||||
if relay_addrs.is_empty() {
|
||||
eprintln!(
|
||||
"WARNING: No relay addresses found in ep2_addr, skipping relay-first connection test"
|
||||
);
|
||||
} else {
|
||||
// Connect with relay-only address first to verify relay works
|
||||
let relay_only_addr = EndpointAddr::from_parts(s2.public(), relay_addrs.into_iter());
|
||||
eprintln!("Connecting with relay-only address: {:?}", relay_only_addr);
|
||||
|
||||
let conn = ep1.connect(relay_only_addr, ECHO_ALPN).await?;
|
||||
|
||||
// Wait for relay path to be established
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
// Debug: print paths after relay-only connect
|
||||
let paths = conn.paths();
|
||||
eprintln!("Paths after relay-only connect:");
|
||||
for path in paths.iter() {
|
||||
eprintln!(
|
||||
" {} selected={} rtt={:?}",
|
||||
path.remote_addr(),
|
||||
path.is_selected(),
|
||||
path.rtt()
|
||||
);
|
||||
}
|
||||
|
||||
// Verify relay is currently selected
|
||||
assert!(
|
||||
is_relay_selected(&conn),
|
||||
"Relay should be selected after connecting with relay-only address"
|
||||
);
|
||||
|
||||
verify_echo(&conn, b"relay test").await?;
|
||||
conn.close(0u32.into(), b"done with relay test");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
// Now connect with all addresses (relay + custom)
|
||||
let conn = ep1.connect(all_addrs, ECHO_ALPN).await?;
|
||||
|
||||
// Wait for paths to settle
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
|
||||
// Debug: print all paths
|
||||
let paths = conn.paths();
|
||||
eprintln!("Paths after connecting with all addresses:");
|
||||
for path in paths.iter() {
|
||||
eprintln!(
|
||||
" {} selected={} rtt={:?}",
|
||||
path.remote_addr(),
|
||||
path.is_selected(),
|
||||
path.rtt()
|
||||
);
|
||||
}
|
||||
|
||||
// Custom (primary) should win over relay (backup)
|
||||
assert!(
|
||||
is_custom_selected(&conn),
|
||||
"Custom transport (primary) should be selected over relay (backup)"
|
||||
);
|
||||
|
||||
verify_echo(&conn, b"custom wins over relay").await?;
|
||||
conn.close(0u32.into(), b"done");
|
||||
router.shutdown().await.anyerr()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
//! TLS configuration for iroh.
|
||||
//!
|
||||
//! Currently there is one mechanism available:
|
||||
//! - Raw Public Keys, using the TLS extension described in [RFC 7250]
|
||||
//!
|
||||
//! [RFC 7250]: https://datatracker.ietf.org/doc/html/rfc7250
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use iroh_base::SecretKey;
|
||||
use noq::crypto::rustls::{QuicClientConfig, QuicServerConfig};
|
||||
use tracing::warn;
|
||||
|
||||
use self::resolver::ResolveRawPublicKeyCert;
|
||||
|
||||
pub(crate) mod misc;
|
||||
pub(crate) mod name;
|
||||
mod resolver;
|
||||
mod verifier;
|
||||
|
||||
#[allow(deprecated)] // Re-export of backwards-compatibility item
|
||||
pub use iroh_relay::tls::CaRootsConfig;
|
||||
pub use iroh_relay::tls::CaTlsConfig;
|
||||
#[cfg(with_crypto_provider)]
|
||||
pub use iroh_relay::tls::default_provider;
|
||||
|
||||
/// Maximum amount of TLS tickets we will cache (by default) for 0-RTT connection
|
||||
/// establishment.
|
||||
///
|
||||
/// 8 tickets per remote endpoint, 32 different endpoints would max out the required storage:
|
||||
/// ~200 bytes per session + certificates (which are ~387 bytes)
|
||||
/// So 8 * 32 * (200 + 387) = 150.272 bytes, assuming pointers to certificates
|
||||
/// are never aliased pointers (they're Arc'ed).
|
||||
/// I think 150KB is an acceptable default upper limit for such a cache.
|
||||
pub(crate) const DEFAULT_MAX_TLS_TICKETS: usize = 8 * 32;
|
||||
|
||||
/// Configuration for TLS.
|
||||
///
|
||||
/// The main point of this struct is to keep state that should be kept the same
|
||||
/// over multiple TLS sessions the same.
|
||||
/// E.g. the `server_verifier` and `client_verifier` Arc pointers are checked to be
|
||||
/// the same between different TLS session calls with 0-RTT data in rustls.
|
||||
/// This makes sure that's the case.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TlsConfig {
|
||||
pub(crate) secret_key: SecretKey,
|
||||
cert_resolver: Arc<ResolveRawPublicKeyCert>,
|
||||
server_verifier: Arc<verifier::ServerCertificateVerifier>,
|
||||
client_verifier: Arc<verifier::ClientCertificateVerifier>,
|
||||
session_store: Arc<dyn rustls::client::ClientSessionStore>,
|
||||
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
}
|
||||
|
||||
impl TlsConfig {
|
||||
pub(crate) fn new(
|
||||
secret_key: SecretKey,
|
||||
max_tls_tickets: usize,
|
||||
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cert_resolver: Arc::new(ResolveRawPublicKeyCert::new(&secret_key)),
|
||||
server_verifier: Arc::new(verifier::ServerCertificateVerifier),
|
||||
client_verifier: Arc::new(verifier::ClientCertificateVerifier),
|
||||
session_store: Arc::new(rustls::client::ClientSessionMemoryCache::new(
|
||||
max_tls_tickets,
|
||||
)),
|
||||
crypto_provider,
|
||||
secret_key,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a TLS client configuration.
|
||||
///
|
||||
/// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
|
||||
/// `SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for
|
||||
/// debugging purposes.
|
||||
pub(crate) fn make_client_config(
|
||||
&self,
|
||||
keylog: bool,
|
||||
) -> Result<QuicClientConfig, TlsConfigError> {
|
||||
let mut crypto = rustls::ClientConfig::builder_with_provider(self.crypto_provider.clone())
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(self.server_verifier.clone())
|
||||
.with_client_cert_resolver(self.cert_resolver.clone());
|
||||
|
||||
// TODO: enable/disable 0-RTT/storing tickets
|
||||
crypto.resumption = rustls::client::Resumption::store(self.session_store.clone());
|
||||
crypto.enable_early_data = true;
|
||||
|
||||
// The synthetic server name is used locally to select the expected endpoint ID
|
||||
// and to partition the session cache. Iroh servers do not use SNI, so do not
|
||||
// disclose the endpoint ID in the ClientHello.
|
||||
crypto.enable_sni = false;
|
||||
|
||||
if keylog {
|
||||
warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
|
||||
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
}
|
||||
|
||||
let quic = QuicClientConfig::try_from(crypto)?;
|
||||
Ok(quic)
|
||||
}
|
||||
|
||||
/// Create a TLS server configuration.
|
||||
///
|
||||
/// If *keylog* is `true` this will enable logging of the pre-master key to the file in the
|
||||
/// `SSLKEYLOGFILE` environment variable. This can be used to inspect the traffic for
|
||||
/// debugging purposes.
|
||||
pub(crate) fn make_server_config(
|
||||
&self,
|
||||
keylog: bool,
|
||||
) -> Result<QuicServerConfig, TlsConfigError> {
|
||||
let mut crypto = rustls::ServerConfig::builder_with_provider(self.crypto_provider.clone())
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
|
||||
.with_client_cert_verifier(self.client_verifier.clone())
|
||||
.with_cert_resolver(self.cert_resolver.clone());
|
||||
if keylog {
|
||||
warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
|
||||
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
}
|
||||
|
||||
// must be u32::MAX or 0 (the default). Any other value panics with QUIC
|
||||
// This is specified in RFC 9001: https://www.rfc-editor.org/rfc/rfc9001#section-4.6.1
|
||||
crypto.max_early_data_size = u32::MAX;
|
||||
let quic = QuicServerConfig::try_from(crypto)?;
|
||||
Ok(quic)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[n0_error::stack_error(derive, add_meta, from_sources)]
|
||||
#[non_exhaustive]
|
||||
pub enum TlsConfigError {
|
||||
#[error(
|
||||
"The configured crypto provider is missing support for TLS13_AES_128_GCM_SHA256, which is required for QUIC initial packets."
|
||||
)]
|
||||
CryptoProviderNoInitialCipherSuite {
|
||||
#[error(std_err)]
|
||||
source: noq::crypto::rustls::NoInitialCipherSuite,
|
||||
},
|
||||
#[error("The configured crypto provider is incompatible with iroh and QUIC encryption")]
|
||||
CryptoProviderIncompatible {
|
||||
#[error(std_err)]
|
||||
source: rustls::Error,
|
||||
},
|
||||
}
|
||||
Vendored
+125
@@ -0,0 +1,125 @@
|
||||
use ctutils::CtEq;
|
||||
use noq_proto::crypto;
|
||||
use rand::RngExt;
|
||||
use rustls::crypto::cipher::{
|
||||
AeadKey, InboundOpaqueMessage, Iv, NONCE_LEN, OutboundPlainMessage, Tls13AeadAlgorithm,
|
||||
};
|
||||
|
||||
/// Implements [`crypto::HandshakeTokenKey`] using a [`Tls13AeadAlgorithm`].
|
||||
///
|
||||
/// This can be obtained from looking through available ciphers from a
|
||||
/// [`rustls::crypto::CryptoProvider`].
|
||||
pub(crate) struct RustlsTokenKey {
|
||||
key: [u8; 32],
|
||||
aead: &'static dyn Tls13AeadAlgorithm,
|
||||
}
|
||||
|
||||
impl RustlsTokenKey {
|
||||
/// Constructs [`crypto::HandshakeTokenKey`] from a [`rustls::crypto::CryptoProvider`].
|
||||
///
|
||||
/// Tries to find a suitable TLS 1.3 cipher suite from the provided crypto provider,
|
||||
/// then uses it to extract an AEAD to use as the token key encryption method.
|
||||
///
|
||||
/// Then generates a random master key to use.
|
||||
///
|
||||
/// Returns `None` when this can't find a suitable TLS cipher suite in the given crypto
|
||||
/// provider.
|
||||
pub(crate) fn new(
|
||||
rng: &mut impl rand::CryptoRng,
|
||||
crypto_provider: &rustls::crypto::CryptoProvider,
|
||||
) -> Option<Self> {
|
||||
let suite = crypto_provider
|
||||
.cipher_suites
|
||||
.iter()
|
||||
.filter_map(|suite| suite.tls13())
|
||||
.next()?;
|
||||
let aead = suite.aead_alg;
|
||||
Some(Self {
|
||||
key: rng.random(),
|
||||
aead,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl crypto::HandshakeTokenKey for RustlsTokenKey {
|
||||
fn seal(&self, token_nonce: u128, data: &mut Vec<u8>) -> Result<(), crypto::CryptoError> {
|
||||
let key = AeadKey::from(self.key);
|
||||
let nonce: [u8; NONCE_LEN] = *token_nonce
|
||||
.to_le_bytes()
|
||||
.first_chunk()
|
||||
.expect("expected u128 > 96 bit");
|
||||
let iv = Iv::from(nonce);
|
||||
let msg = OutboundPlainMessage {
|
||||
typ: rustls::ContentType::ApplicationData,
|
||||
version: rustls::ProtocolVersion::TLSv1_3,
|
||||
payload: rustls::crypto::cipher::OutboundChunks::Single(&*data),
|
||||
};
|
||||
let out = self
|
||||
.aead
|
||||
.encrypter(key, iv)
|
||||
.encrypt(msg, 0)
|
||||
.map_err(|_| crypto::CryptoError)?;
|
||||
|
||||
data.clear();
|
||||
data.extend(out.payload.as_ref());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open<'a>(
|
||||
&self,
|
||||
token_nonce: u128,
|
||||
data: &'a mut [u8],
|
||||
) -> Result<&'a [u8], crypto::CryptoError> {
|
||||
let key = AeadKey::from(self.key);
|
||||
let nonce: [u8; NONCE_LEN] = *token_nonce
|
||||
.to_le_bytes()
|
||||
.first_chunk()
|
||||
.expect("expected u128 > 96 bit");
|
||||
let iv = Iv::from(nonce);
|
||||
|
||||
let msg = InboundOpaqueMessage::new(
|
||||
rustls::ContentType::ApplicationData,
|
||||
rustls::ProtocolVersion::TLSv1_3,
|
||||
data,
|
||||
);
|
||||
let plain = self
|
||||
.aead
|
||||
.decrypter(key, iv)
|
||||
.decrypt(msg, 0)
|
||||
.map_err(|_| crypto::CryptoError)?;
|
||||
|
||||
Ok(plain.payload)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Blake3HmacKey([u8; 32]);
|
||||
|
||||
impl Blake3HmacKey {
|
||||
pub(crate) fn new(rng: &mut impl rand::CryptoRng) -> Self {
|
||||
let mut key = [0u8; 32];
|
||||
rng.fill_bytes(&mut key);
|
||||
Self(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl crypto::HmacKey for Blake3HmacKey {
|
||||
fn sign(&self, data: &[u8], signature_out: &mut [u8]) {
|
||||
signature_out.copy_from_slice(blake3::keyed_hash(&self.0, data).as_slice());
|
||||
}
|
||||
|
||||
fn signature_len(&self) -> usize {
|
||||
blake3::OUT_LEN // 32 bytes
|
||||
}
|
||||
|
||||
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), crypto::CryptoError> {
|
||||
let reference = blake3::keyed_hash(&self.0, data);
|
||||
// to_bool is fine here, because it's the last thing we do to
|
||||
// distinguish success or failure (see to_bool documentation)
|
||||
if signature.ct_eq(reference.as_slice()).to_bool() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(crypto::CryptoError)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
//! Implementation of encoding iroh EndpointIds as domain names.
|
||||
//!
|
||||
//! We used to send this name via SNI up until iroh version 1.0.3, but stopped doing so in
|
||||
//! versions after that. It is now used only locally by the `ServerCertificateVerifier` and
|
||||
//! to separate the buckets for 0-RTT session tickets.
|
||||
//!
|
||||
//! We used to use a constant "localhost" for the TLS server name - however, that affects
|
||||
//! 0-RTT and would put all of the TLS session tickets we receive into the same bucket in
|
||||
//! the TLS session ticket cache.
|
||||
//! So we choose something that'd dependent on the EndpointId.
|
||||
//! We cannot use hex to encode the EndpointId, as that'd encode to 64 characters, but we only
|
||||
//! have 63 maximum per DNS subdomain. Base32 is the next best alternative.
|
||||
//! We use the `.invalid` TLD, as that's specified (in RFC 2606) to never actually resolve
|
||||
//! "for real", unlike `.localhost` which is allowed to resolve to `127.0.0.1`.
|
||||
//! We also add "iroh" as a subdomain, although those 5 bytes might not be necessary.
|
||||
//! We *could* decide to remove that indicator in the future likely without breakage.
|
||||
|
||||
use data_encoding::BASE32_DNSSEC;
|
||||
use iroh_base::EndpointId;
|
||||
|
||||
pub(crate) fn encode(endpoint_id: EndpointId) -> String {
|
||||
format!(
|
||||
"{}.iroh.invalid",
|
||||
BASE32_DNSSEC.encode(endpoint_id.as_bytes())
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn decode(name: &str) -> Option<EndpointId> {
|
||||
let [base32_endpoint_id, "iroh", "invalid"] = name.split(".").collect::<Vec<_>>()[..] else {
|
||||
return None;
|
||||
};
|
||||
EndpointId::from_bytes(
|
||||
&BASE32_DNSSEC
|
||||
.decode(base32_endpoint_id.as_bytes())
|
||||
.ok()?
|
||||
.try_into()
|
||||
.ok()?,
|
||||
)
|
||||
.ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use iroh_base::SecretKey;
|
||||
use rand::{RngExt, SeedableRng};
|
||||
|
||||
#[test]
|
||||
fn test_roundtrip() {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
|
||||
let key = SecretKey::from_bytes(&rng.random());
|
||||
let endpoint_id = key.public();
|
||||
println!("{}", super::encode(endpoint_id));
|
||||
assert_eq!(
|
||||
Some(endpoint_id),
|
||||
super::decode(&super::encode(endpoint_id))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_snapshot() {
|
||||
let key = SecretKey::from_bytes(&[0; 32]);
|
||||
assert_eq!(
|
||||
super::encode(key.public()),
|
||||
"7dl2ff6emqi2qol3l382krodedij45bn3nh479hqo14a32qpr8kg.iroh.invalid",
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use iroh_base::SecretKey;
|
||||
use webpki_types::CertificateDer;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ResolveRawPublicKeyCert {
|
||||
key: Arc<rustls::sign::CertifiedKey>,
|
||||
}
|
||||
|
||||
impl ResolveRawPublicKeyCert {
|
||||
pub(super) fn new(secret_key: &SecretKey) -> Self {
|
||||
let client_private_key = Arc::new(IrohSecretKey::from(secret_key.clone()));
|
||||
let client_public_key = client_private_key.spki_public_key();
|
||||
let client_public_key_as_cert = CertificateDer::from(client_public_key.to_vec());
|
||||
|
||||
let certified_key =
|
||||
rustls::sign::CertifiedKey::new(vec![client_public_key_as_cert], client_private_key);
|
||||
|
||||
let key = Arc::new(certified_key);
|
||||
|
||||
Self { key }
|
||||
}
|
||||
}
|
||||
|
||||
impl rustls::client::ResolvesClientCert for ResolveRawPublicKeyCert {
|
||||
fn resolve(
|
||||
&self,
|
||||
_root_hint_subjects: &[&[u8]],
|
||||
_sigschemes: &[rustls::SignatureScheme],
|
||||
) -> Option<Arc<rustls::sign::CertifiedKey>> {
|
||||
Some(Arc::clone(&self.key))
|
||||
}
|
||||
|
||||
fn only_raw_public_keys(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn has_certs(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl rustls::server::ResolvesServerCert for ResolveRawPublicKeyCert {
|
||||
fn resolve(
|
||||
&self,
|
||||
_client_hello: rustls::server::ClientHello<'_>,
|
||||
) -> Option<Arc<rustls::sign::CertifiedKey>> {
|
||||
Some(Arc::clone(&self.key))
|
||||
}
|
||||
|
||||
fn only_raw_public_keys(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, derive_more::From)]
|
||||
struct IrohSecretKey {
|
||||
#[from]
|
||||
key: SecretKey,
|
||||
}
|
||||
|
||||
impl IrohSecretKey {
|
||||
fn spki_public_key(&self) -> webpki_types::SubjectPublicKeyInfoDer<'static> {
|
||||
rustls::sign::public_key_to_spki(
|
||||
&webpki_types::alg_id::ED25519,
|
||||
self.key.public().as_bytes(),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl rustls::sign::SigningKey for IrohSecretKey {
|
||||
fn choose_scheme(
|
||||
&self,
|
||||
offered: &[rustls::SignatureScheme],
|
||||
) -> Option<Box<dyn rustls::sign::Signer>> {
|
||||
if offered.contains(&rustls::SignatureScheme::ED25519) {
|
||||
Some(Box::new(self.clone()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn algorithm(&self) -> rustls::SignatureAlgorithm {
|
||||
rustls::SignatureAlgorithm::ED25519
|
||||
}
|
||||
|
||||
fn public_key(&self) -> Option<webpki_types::SubjectPublicKeyInfoDer<'_>> {
|
||||
Some(self.spki_public_key())
|
||||
}
|
||||
}
|
||||
|
||||
impl rustls::sign::Signer for IrohSecretKey {
|
||||
fn sign(&self, message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
|
||||
Ok(self.key.sign(message).to_bytes().to_vec())
|
||||
}
|
||||
|
||||
fn scheme(&self) -> rustls::SignatureScheme {
|
||||
rustls::SignatureScheme::ED25519
|
||||
}
|
||||
}
|
||||
Vendored
+211
@@ -0,0 +1,211 @@
|
||||
//! TLS 1.3 certificates and handshakes handling.
|
||||
//!
|
||||
//! This module handles a verification of a client/server certificate chain
|
||||
//! and signatures allegedly by the given certificates, or using raw public keys.
|
||||
|
||||
use iroh_base::{PublicKey, Signature};
|
||||
use rustls::{
|
||||
CertificateError, DigitallySignedStruct, DistinguishedName, SignatureScheme,
|
||||
SupportedProtocolVersion,
|
||||
client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
|
||||
crypto::{WebPkiSupportedAlgorithms, verify_tls13_signature_with_raw_key},
|
||||
pki_types::CertificateDer as Certificate,
|
||||
server::danger::{ClientCertVerified, ClientCertVerifier},
|
||||
};
|
||||
use webpki_types::SubjectPublicKeyInfoDer;
|
||||
|
||||
/// The only TLS version we support is 1.3
|
||||
pub(super) const PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13];
|
||||
|
||||
const ED25519_DALEK: Ed25519Dalek = Ed25519Dalek;
|
||||
const SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
|
||||
all: &[&ED25519_DALEK],
|
||||
mapping: &[(SignatureScheme::ED25519, &[&ED25519_DALEK])],
|
||||
};
|
||||
|
||||
/// Implementation of the `rustls` certificate verification traits
|
||||
///
|
||||
/// Only TLS 1.3 is supported. TLS 1.2 should be disabled in the configuration of `rustls`.
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct ServerCertificateVerifier;
|
||||
|
||||
impl ServerCertVerifier for ServerCertificateVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
end_entity: &Certificate,
|
||||
intermediates: &[Certificate],
|
||||
server_name: &rustls::pki_types::ServerName,
|
||||
_ocsp_response: &[u8],
|
||||
_now: rustls::pki_types::UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
let rustls::pki_types::ServerName::DnsName(dns_name) = server_name else {
|
||||
return Err(rustls::Error::UnsupportedNameType);
|
||||
};
|
||||
let Some(remote_peer_id) = super::name::decode(dns_name.as_ref()) else {
|
||||
return Err(rustls::Error::InvalidCertificate(
|
||||
CertificateError::NotValidForName,
|
||||
));
|
||||
};
|
||||
|
||||
if !intermediates.is_empty() {
|
||||
return Err(rustls::Error::InvalidCertificate(
|
||||
CertificateError::UnknownIssuer,
|
||||
));
|
||||
}
|
||||
|
||||
let end_entity_as_spki = SubjectPublicKeyInfoDer::from(end_entity.as_ref());
|
||||
let remote_public_spki = rustls::sign::public_key_to_spki(
|
||||
&webpki_types::alg_id::ED25519,
|
||||
remote_peer_id.as_bytes(),
|
||||
);
|
||||
|
||||
// This effectively checks that the `end_entity_as_spki` bytes have the expected
|
||||
// (constant) 12 byte prefix (consisting of the Ed25519 public key ASN.1 object
|
||||
// identifier, some ASN.1 DER encoding bytes signaling that this is a SPKI and
|
||||
// consists of the object identifier and a bit sequence, a zero byte indicating
|
||||
// that the bit sequence is padded with 0 additional bits) matches, as well as
|
||||
// the public key bytes match the `remote_peer_id` public key bytes.
|
||||
if remote_public_spki != end_entity_as_spki {
|
||||
return Err(rustls::Error::InvalidCertificate(
|
||||
CertificateError::UnknownIssuer,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &Certificate,
|
||||
_dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Err(rustls::Error::PeerIncompatible(
|
||||
rustls::PeerIncompatible::Tls12NotOffered,
|
||||
))
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &Certificate,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls13_signature_with_raw_key(
|
||||
message,
|
||||
&SubjectPublicKeyInfoDer::from(cert.as_ref()),
|
||||
dss,
|
||||
&SUPPORTED_SIG_ALGS,
|
||||
)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
SUPPORTED_SIG_ALGS.supported_schemes()
|
||||
}
|
||||
|
||||
fn requires_raw_public_keys(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation of the `rustls` certificate verification traits.
|
||||
///
|
||||
/// Only TLS 1.3 is supported. TLS 1.2 should be disabled in the configuration of `rustls`.
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct ClientCertificateVerifier;
|
||||
|
||||
/// We require one of the following client certificate configurations:
|
||||
///
|
||||
/// - a valid raw public key configuration
|
||||
impl ClientCertVerifier for ClientCertificateVerifier {
|
||||
fn offer_client_auth(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn verify_client_cert(
|
||||
&self,
|
||||
_end_entity: &Certificate,
|
||||
intermediates: &[Certificate],
|
||||
_now: rustls::pki_types::UnixTime,
|
||||
) -> Result<ClientCertVerified, rustls::Error> {
|
||||
if !intermediates.is_empty() {
|
||||
return Err(rustls::Error::InvalidCertificate(
|
||||
CertificateError::UnknownIssuer,
|
||||
));
|
||||
}
|
||||
|
||||
// Beyond checking for no intermediates, we don't check the client certificate.
|
||||
// The actual signatures are already verified - this ensures authentication.
|
||||
|
||||
Ok(ClientCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &Certificate,
|
||||
_dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
Err(rustls::Error::PeerIncompatible(
|
||||
rustls::PeerIncompatible::Tls12NotOffered,
|
||||
))
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &Certificate,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls13_signature_with_raw_key(
|
||||
message,
|
||||
&SubjectPublicKeyInfoDer::from(cert.as_ref()),
|
||||
dss,
|
||||
&SUPPORTED_SIG_ALGS,
|
||||
)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
SUPPORTED_SIG_ALGS.supported_schemes()
|
||||
}
|
||||
|
||||
fn root_hint_subjects(&self) -> &[DistinguishedName] {
|
||||
&[][..]
|
||||
}
|
||||
|
||||
fn requires_raw_public_keys(&self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Ed25519Dalek;
|
||||
|
||||
impl webpki_types::SignatureVerificationAlgorithm for Ed25519Dalek {
|
||||
fn verify_signature(
|
||||
&self,
|
||||
public_key: &[u8],
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> Result<(), webpki_types::InvalidSignature> {
|
||||
let public_key =
|
||||
PublicKey::try_from(public_key).map_err(|_| webpki_types::InvalidSignature)?;
|
||||
let signature =
|
||||
Signature::try_from(signature).map_err(|_| webpki_types::InvalidSignature)?;
|
||||
public_key
|
||||
.verify(message, &signature)
|
||||
.map_err(|_| webpki_types::InvalidSignature)
|
||||
}
|
||||
|
||||
fn public_key_alg_id(&self) -> webpki_types::AlgorithmIdentifier {
|
||||
webpki_types::alg_id::ED25519
|
||||
}
|
||||
|
||||
fn signature_alg_id(&self) -> webpki_types::AlgorithmIdentifier {
|
||||
webpki_types::alg_id::ED25519
|
||||
}
|
||||
|
||||
fn fips(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
//! Utilities used in [`iroh`](crate).
|
||||
|
||||
/// Creates a [`reqwest::ClientBuilder`] from a [`rustls::ClientConfig`] and our [`DnsResolver`].
|
||||
///
|
||||
/// In a browser context these options are not supported, so this function takes no arguments
|
||||
/// if `wasm_browser` is enabled.
|
||||
///
|
||||
/// [`DnsResolver`]: crate::dns::DnsResolver
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub(crate) fn reqwest_client_builder(
|
||||
tls_client_config: rustls::ClientConfig,
|
||||
dns_resolver: crate::dns::DnsResolver,
|
||||
) -> reqwest::ClientBuilder {
|
||||
use self::reqwest_dns_resolver::ReqwestDnsResolver;
|
||||
|
||||
reqwest::Client::builder()
|
||||
.tls_backend_preconfigured(tls_client_config)
|
||||
.dns_resolver(ReqwestDnsResolver(dns_resolver))
|
||||
}
|
||||
|
||||
#[cfg(wasm_browser)]
|
||||
pub(crate) fn reqwest_client_builder() -> reqwest::ClientBuilder {
|
||||
reqwest::Client::builder()
|
||||
}
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
mod reqwest_dns_resolver {
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use iroh_dns::dns::{DNS_TIMEOUT, DnsResolver};
|
||||
|
||||
use crate::address_lookup::DNS_STAGGERING_MS;
|
||||
|
||||
/// Implementation of [`reqwest::dns::Resolve`] for [`DnsResolver`].
|
||||
///
|
||||
/// Wrapped in a newtype to not expose this in the public iroh API.
|
||||
pub(super) struct ReqwestDnsResolver(pub(super) DnsResolver);
|
||||
|
||||
impl reqwest::dns::Resolve for ReqwestDnsResolver {
|
||||
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
|
||||
let this = self.0.clone();
|
||||
let name = name.as_str().to_string();
|
||||
Box::pin(async move {
|
||||
// Staggered so that a single unresponsive DNS server does not stall the
|
||||
// request for the full timeout. Ideally this resolves **both** IPv4 and
|
||||
// IPv6 rather than racing them, but our resolver has no function for that
|
||||
// yet.
|
||||
let res = this
|
||||
.lookup_ipv4_ipv6_staggered(name, DNS_TIMEOUT, DNS_STAGGERING_MS)
|
||||
.await
|
||||
// Collected eagerly: the returned iterator borrows the resolver, which
|
||||
// does not outlive this future.
|
||||
.map(|addrs| {
|
||||
addrs
|
||||
.map(|addr| SocketAddr::new(addr, 0))
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
match res {
|
||||
Ok(addrs) => {
|
||||
let addrs: reqwest::dns::Addrs = Box::new(addrs.into_iter());
|
||||
Ok(addrs)
|
||||
}
|
||||
Err(err) => {
|
||||
let err: Box<dyn std::error::Error + Send + Sync> = Box::new(err);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user