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
+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(())
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user