From 647f28ed11d19c46b60e89db2e70ca80b48948e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=BCdiger=20Klaehn?= Date: Thu, 12 Mar 2026 11:32:23 +0100 Subject: [PATCH] deps: Feature gate portmapper, and allow disabling portmapper by default. (#4011) ## Description Iroh on esp32 is over 4 MiB out of the box, which means that it won't run on the majority of the esp32 devices out there. There are a number of deps we can get rid of without affecting core functionality. Portmapper is the easiest to feature gate since it is already disabled for wasm. Portmapper and its dep idg-next are big enough that when disabling it it barely fits on esp32 4 MiB devices. Implements https://github.com/n0-computer/iroh/issues/3811 ## Breaking Changes Builds that use no-default-features won't have the portmapper. This does not change APIs, but will change functionality. ## Notes & open questions In general, if a feature is disabled, should we stub the public API to just report 0/noops, or hide it? E.g. if you were to stub portmapper metrics you would not need to enable portmapper for our bench project. ## Change checklist - [ ] Self-review. - [ ] Documentation updates following the [style guide](https://rust-lang.github.io/rfcs/1574-more-api-documentation-conventions.html#appendix-a-full-conventions-text), if relevant. - [ ] Tests if relevant. - [ ] All breaking changes documented. - [ ] List all breaking changes in the above "Breaking Changes" section. - [ ] Open an issue or PR on any number0 repos that are affected by this breaking change. Give guidance on how the updates should be handled or do the actual updates themselves. The major ones are: - [ ] [`quic-rpc`](https://github.com/n0-computer/quic-rpc) - [ ] [`iroh-gossip`](https://github.com/n0-computer/iroh-gossip) - [ ] [`iroh-blobs`](https://github.com/n0-computer/iroh-blobs) - [ ] [`dumbpipe`](https://github.com/n0-computer/dumbpipe) - [ ] [`sendme`](https://github.com/n0-computer/sendme) --- .github/workflows/ci.yml | 19 +++++ Cargo.lock | 1 - iroh/Cargo.toml | 8 +- iroh/src/endpoint.rs | 12 +++ iroh/src/lib.rs | 1 + iroh/src/metrics.rs | 8 +- iroh/src/net_report.rs | 19 ----- iroh/src/net_report/reportgen.rs | 2 - iroh/src/portmapper.rs | 135 +++++++++++++++++++++++++++++++ iroh/src/socket.rs | 84 ++++++++----------- 10 files changed, 209 insertions(+), 80 deletions(-) create mode 100644 iroh/src/portmapper.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53b2175cf0..4489694ed8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -308,6 +308,25 @@ jobs: - name: clippy check (default features) run: cargo clippy --workspace --all-targets --lib --bins --tests --benches --examples + check_optional_deps: + timeout-minutes: 10 + name: Check optional deps are absent without features + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: dtolnay/rust-toolchain@stable + - name: Verify optional deps are absent without features + run: | + tree=$(cargo tree -p iroh --no-default-features --edges normal) + fail=0 + for dep in portmapper igd-next swarm-discovery; do + if echo "$tree" | grep -q "$dep"; then + echo "ERROR: $dep should not be in the dependency tree without its feature" + fail=1 + fi + done + exit $fail + msrv: if: "github.event_name != 'pull_request' || ! contains(github.event.pull_request.labels.*.name, 'flaky-test')" timeout-minutes: 30 diff --git a/Cargo.lock b/Cargo.lock index c9307cd72a..8a3944936a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2103,7 +2103,6 @@ dependencies = [ "getrandom 0.3.4", "hickory-resolver", "http", - "igd-next", "indicatif", "iroh-base", "iroh-metrics", diff --git a/iroh/Cargo.toml b/iroh/Cargo.toml index ec725d7e46..e692655826 100644 --- a/iroh/Cargo.toml +++ b/iroh/Cargo.toml @@ -79,9 +79,8 @@ sync_wrapper = { version = "1.0.2", features = ["futures"] } # non-wasm-in-browser dependencies [target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies] hickory-resolver = "0.25.1" -igd-next = { version = "0.16", features = ["aio_tokio"] } netdev = { version = "0.40.0" } -portmapper = { version = "0.15", default-features = false } +portmapper = { version = "0.15", optional = true, default-features = false } noq = { version = "0.17.0", default-features = false, features = ["runtime-tokio", "rustls-ring"] } tokio = { version = "1", features = [ "io-util", @@ -144,8 +143,9 @@ wasm-bindgen-test = "0.3.62" cfg_aliases = { version = "0.2.1" } [features] -default = ["metrics", "fast-apple-datapath"] -metrics = ["iroh-metrics/metrics", "iroh-relay/metrics", "portmapper/metrics"] +default = ["metrics", "fast-apple-datapath", "portmapper"] +portmapper = ["dep:portmapper"] +metrics = ["iroh-metrics/metrics", "iroh-relay/metrics", "portmapper?/metrics"] test-utils = ["iroh-relay/test-utils", "iroh-relay/server", "dep:axum"] address-lookup-mdns = ["dep:swarm-discovery"] address-lookup-pkarr-dht = ["pkarr/dht", "pkarr/relays"] diff --git a/iroh/src/endpoint.rs b/iroh/src/endpoint.rs index 644a67020b..f360e9df3c 100644 --- a/iroh/src/endpoint.rs +++ b/iroh/src/endpoint.rs @@ -98,6 +98,7 @@ pub use self::{ VarIntBoundsExceeded, WriteError, Written, }, }; +pub use crate::portmapper::PortmapperConfig; #[cfg(not(wasm_browser))] use crate::socket::transports::IpConfig; use crate::socket::transports::TransportConfig; @@ -124,6 +125,7 @@ pub struct Builder { max_tls_tickets: usize, hooks: EndpointHooksList, transport_bias: socket::transports::TransportBiasMap, + portmapper_config: PortmapperConfig, } impl From for Option { @@ -189,6 +191,7 @@ impl Builder { transports, hooks: Default::default(), transport_bias: Default::default(), + portmapper_config: Default::default(), } } @@ -234,6 +237,7 @@ impl Builder { metrics, hooks: self.hooks, transport_bias: self.transport_bias, + portmapper_config: self.portmapper_config, static_config, }; @@ -666,6 +670,14 @@ impl Builder { self } + /// Configures the portmapper service (UPnP, PCP, NAT-PMP). + /// + /// Defaults to [`PortmapperConfig::Enabled`]. + pub fn portmapper_config(mut self, config: PortmapperConfig) -> Self { + self.portmapper_config = config; + self + } + /// Adds a custom transport #[cfg(feature = "unstable-custom-transports")] pub fn add_custom_transport(mut self, factory: Arc) -> Self { diff --git a/iroh/src/lib.rs b/iroh/src/lib.rs index 66310ac0ae..9eaf5e0aa7 100644 --- a/iroh/src/lib.rs +++ b/iroh/src/lib.rs @@ -256,6 +256,7 @@ mod socket; pub mod tls; +pub(crate) mod portmapper; pub(crate) mod runtime; pub(crate) mod util; diff --git a/iroh/src/metrics.rs b/iroh/src/metrics.rs index 679c3a976b..01e67f1a16 100644 --- a/iroh/src/metrics.rs +++ b/iroh/src/metrics.rs @@ -4,11 +4,12 @@ use std::sync::Arc; use iroh_metrics::MetricsGroupSet; #[cfg(feature = "test-utils")] pub use iroh_relay::server::Metrics as RelayMetrics; -#[cfg(not(wasm_browser))] -pub use portmapper::Metrics as PortmapMetrics; use serde::{Deserialize, Serialize}; -pub use crate::{net_report::Metrics as NetReportMetrics, socket::Metrics as SocketMetrics}; +pub use crate::{ + net_report::Metrics as NetReportMetrics, portmapper::Metrics as PortmapMetrics, + socket::Metrics as SocketMetrics, +}; /// Metrics collected by an [`crate::endpoint::Endpoint`]. /// @@ -22,7 +23,6 @@ pub struct EndpointMetrics { /// Metrics collected by net reports. pub net_report: Arc, /// Metrics collected by the portmapper service. - #[cfg(not(wasm_browser))] pub portmapper: Arc, } diff --git a/iroh/src/net_report.rs b/iroh/src/net_report.rs index 47fb5fc610..f46c3dfbfd 100644 --- a/iroh/src/net_report.rs +++ b/iroh/src/net_report.rs @@ -58,25 +58,6 @@ mod reportgen; mod options; -/// We "vendor" what we need of the library in browsers for simplicity. -/// -/// We could consider making `portmapper` compile to wasm in the future, -/// but what we need is so little it's likely not worth it. -#[cfg(wasm_browser)] -pub(crate) mod portmapper { - /// Output of a port mapping probe. - #[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)] - #[display("portmap={{ UPnP: {upnp}, PMP: {nat_pmp}, PCP: {pcp} }}")] - pub struct ProbeOutput { - /// If UPnP can be considered available. - pub upnp: bool, - /// If PCP can be considered available. - pub pcp: bool, - /// If PMP can be considered available. - pub nat_pmp: bool, - } -} - pub(crate) use self::reportgen::IfStateDetails; #[cfg(not(wasm_browser))] #[allow(missing_docs)] diff --git a/iroh/src/net_report/reportgen.rs b/iroh/src/net_report/reportgen.rs index b268f55dc1..9c8b016488 100644 --- a/iroh/src/net_report/reportgen.rs +++ b/iroh/src/net_report/reportgen.rs @@ -49,8 +49,6 @@ use url::Host; #[cfg(not(wasm_browser))] use super::defaults::timeouts::DNS_TIMEOUT; -#[cfg(wasm_browser)] -use super::portmapper; // We stub the library use super::{ Report, probes::{Probe, ProbePlan}, diff --git a/iroh/src/portmapper.rs b/iroh/src/portmapper.rs new file mode 100644 index 0000000000..475ef45293 --- /dev/null +++ b/iroh/src/portmapper.rs @@ -0,0 +1,135 @@ +//! Portmapper integration. +//! +//! Re-exports the real [`portmapper`] crate when the `portmapper` feature is enabled, +//! or provides a no-op stub otherwise. + +use std::net::SocketAddrV4; + +#[cfg(all(not(wasm_browser), feature = "portmapper"))] +pub use ::portmapper::Metrics; +#[cfg(not(all(not(wasm_browser), feature = "portmapper")))] +pub use stub::Metrics; +use tokio::sync::watch; + +/// Configuration for the portmapper service (UPnP, PCP, NAT-PMP). +/// +/// 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. + Disabled, +} + +impl Default for PortmapperConfig { + fn default() -> Self { + PortmapperConfig::Enabled {} + } +} + +pub(crate) fn create_client( + metrics: &crate::metrics::EndpointMetrics, + config: &PortmapperConfig, +) -> Client { + match config { + #[cfg(all(not(wasm_browser), feature = "portmapper"))] + PortmapperConfig::Enabled {} => Client::Enabled(::portmapper::Client::with_metrics( + Default::default(), + metrics.portmapper.clone(), + )), + _ => { + let _ = metrics; + 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>, + rx: watch::Receiver>, + }, +} + +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> { + match self { + #[cfg(all(not(wasm_browser), feature = "portmapper"))] + Client::Enabled(c) => c.watch_external_address(), + Client::Disabled { rx, .. } => rx.clone(), + } + } +} + +#[allow(dead_code)] +mod stub { + use iroh_metrics::{Counter, MetricsGroup}; + use serde::{Deserialize, Serialize}; + + /// Stub portmapper metrics used when the `portmapper` feature is disabled. + #[derive(Debug, Default, MetricsGroup, Serialize, Deserialize)] + #[metrics(name = "portmap")] + pub struct Metrics { + /// Number of probing tasks started. + pub probes_started: Counter, + /// Number of updates to the local port. + pub local_port_updates: Counter, + /// Number of mapping tasks started. + pub mapping_attempts: Counter, + /// Number of failed mapping tasks. + pub mapping_failures: Counter, + /// Number of times the external address obtained via port mapping was updated. + pub external_address_updated: Counter, + /// Number of UPnP probes executed. + pub upnp_probes: Counter, + /// Number of failed UPnP probes. + pub upnp_probes_failed: Counter, + /// Number of UPnP probes that found it available. + pub upnp_available: Counter, + /// Number of UPnP probes that resulted in a gateway different to the previous one. + pub upnp_gateway_updated: Counter, + /// Number of PCP probes executed. + pub pcp_probes: Counter, + /// Number of PCP probes that found it available. + pub pcp_available: Counter, + } +} diff --git a/iroh/src/socket.rs b/iroh/src/socket.rs index 7f21666f68..becf33a7fb 100644 --- a/iroh/src/socket.rs +++ b/iroh/src/socket.rs @@ -63,6 +63,7 @@ use crate::{ endpoint::{hooks::EndpointHooksList, quic::QuicTransportConfig}, metrics::EndpointMetrics, net_report::{self, IfStateDetails, Report}, + portmapper, runtime::Runtime, socket::{ concurrent_read_map::ReadOnlyMap, @@ -148,6 +149,7 @@ pub(crate) struct Options { pub(crate) metrics: EndpointMetrics, pub(crate) hooks: EndpointHooksList, pub(crate) transport_bias: TransportBiasMap, + pub(crate) portmapper_config: portmapper::PortmapperConfig, /// Static configuration for the endpoint. pub(crate) static_config: StaticConfig, @@ -600,7 +602,6 @@ struct DirectAddrUpdateState { /// If set, start a new update as soon as the current one is finished. want_update: Option, sock: Arc, - #[cfg(not(wasm_browser))] port_mapper: portmapper::Client, /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. net_reporter: Arc>, @@ -630,7 +631,7 @@ impl UpdateReason { impl DirectAddrUpdateState { fn new( sock: Arc, - #[cfg(not(wasm_browser))] port_mapper: portmapper::Client, + port_mapper: portmapper::Client, net_reporter: Arc>, relay_map: RelayMap, run_done: mpsc::Sender<()>, @@ -638,7 +639,6 @@ impl DirectAddrUpdateState { ) -> Self { DirectAddrUpdateState { want_update: Default::default(), - #[cfg(not(wasm_browser))] port_mapper, net_reporter, sock, @@ -688,7 +688,6 @@ impl DirectAddrUpdateState { if self.shutdown_token.is_cancelled() { debug!("skipping net_report, socket is shutting down"); // deactivate portmapper - #[cfg(not(wasm_browser))] self.port_mapper.deactivate(); return; } @@ -698,7 +697,6 @@ impl DirectAddrUpdateState { return; } - #[cfg(not(wasm_browser))] self.port_mapper.procure_mapping(); debug!("requesting net_report report"); @@ -778,13 +776,12 @@ impl EndpointInner { metrics, hooks, transport_bias, + portmapper_config, static_config, } = opts; let address_lookup = address_lookup::ConcurrentAddressLookup::default(); - #[cfg(not(wasm_browser))] - let port_mapper = - portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); + let port_mapper = portmapper::create_client(&metrics, &portmapper_config); let relay_transport_configs: Vec<_> = transport_configs .iter() @@ -833,22 +830,19 @@ impl EndpointInner { ) .map_err(|err| e!(BindError::Sockets, err))?; - #[cfg(not(wasm_browser))] - { - if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { - if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { - Some(addr.port()) - } else { - None - } - }) { - // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails - match v4_port.try_into() { - Ok(non_zero_port) => { - port_mapper.update_local_port(non_zero_port); - } - Err(_zero_port) => debug!("Skipping port mapping with zero local port"), + if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| { + if let transports::Addr::Ip(SocketAddr::V4(addr)) = t { + Some(addr.port()) + } else { + None + } + }) { + // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails + match v4_port.try_into() { + Ok(non_zero_port) => { + port_mapper.update_local_port(non_zero_port); } + Err(_zero_port) => debug!("Skipping port mapping with zero local port"), } } @@ -954,7 +948,6 @@ impl EndpointInner { let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); let direct_addr_update_state = DirectAddrUpdateState::new( sock.clone(), - #[cfg(not(wasm_browser))] port_mapper, Arc::new(AsyncMutex::new(net_reporter)), relay_map, @@ -1278,14 +1271,12 @@ impl Actor { // Setup network monitoring let mut current_netmon_state = self.local_interfaces_watcher.get(); - #[cfg(not(wasm_browser))] let mut portmap_watcher = self .direct_addr_update_state .port_mapper .watch_external_address(); let mut receiver_closed = false; - #[cfg_attr(wasm_browser, allow(unused_mut))] let mut portmap_watcher_closed = false; let mut net_report_watcher = self.sock.net_report.watch(); @@ -1295,10 +1286,7 @@ impl Actor { while !shutdown_token.is_cancelled() { self.sock.metrics.socket.actor_tick_main.inc(); - #[cfg(not(wasm_browser))] let portmap_watcher_changed = portmap_watcher.changed(); - #[cfg(wasm_browser)] - let portmap_watcher_changed = n0_future::future::pending(); tokio::select! { _ = shutdown_token.cancelled() => { @@ -1363,24 +1351,19 @@ impl Actor { } } change = portmap_watcher_changed, if !portmap_watcher_closed => { - #[cfg(not(wasm_browser))] - { - if change.is_err() { - trace!("tick: portmap watcher closed"); - self.sock.metrics.socket.actor_tick_other.inc(); + if change.is_err() { + trace!("tick: portmap watcher closed"); + self.sock.metrics.socket.actor_tick_other.inc(); - portmap_watcher_closed = true; - continue; - } - - trace!("tick: portmap changed"); - self.sock.metrics.socket.actor_tick_portmap_changed.inc(); - let new_external_address = *portmap_watcher.borrow(); - debug!("external address updated: {new_external_address:?}"); - self.re_stun(UpdateReason::PortmapUpdated); + portmap_watcher_closed = true; + continue; } - #[cfg(wasm_browser)] - let _unused_in_browsers = change; + + trace!("tick: portmap changed"); + self.sock.metrics.socket.actor_tick_portmap_changed.inc(); + let new_external_address = *portmap_watcher.borrow(); + debug!("external address updated: {new_external_address:?}"); + self.re_stun(UpdateReason::PortmapUpdated); }, state = self.local_interfaces_watcher.updated() => { let Ok(state) = state else { @@ -1482,17 +1465,16 @@ impl Actor { /// - The local interfaces IP addresses. #[cfg(not(wasm_browser))] fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { - let portmap_watcher = self - .direct_addr_update_state - .port_mapper - .watch_external_address(); - // We only want to have one DirectAddr for each SocketAddr we have. So we store // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a // DirectAddr from each entry. let mut addrs: BTreeMap = BTreeMap::new(); // First add PortMapper provided addresses. + let portmap_watcher = self + .direct_addr_update_state + .port_mapper + .watch_external_address(); let maybe_port_mapped = *portmap_watcher.borrow(); if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { addrs @@ -1796,6 +1778,7 @@ mod tests { metrics: Default::default(), hooks: Default::default(), transport_bias: Default::default(), + portmapper_config: Default::default(), static_config, } } @@ -2194,6 +2177,7 @@ mod tests { metrics: Default::default(), hooks: Default::default(), transport_bias: Default::default(), + portmapper_config: Default::default(), static_config, }; let sock = EndpointInner::bind(opts).await?;