iroh/net_report/
reportgen.rs

1//! The reportgen actor is responsible for generating a single net_report report.
2//!
3//! It is implemented as an actor with [`Client`] as handle.
4//!
5//! The actor starts generating the report as soon as it is created, it does not receive any
6//! messages from the client.  It follows roughly these steps:
7//!
8//! - Determines host IPv6 support.
9//! - Creates portmapper future.
10//! - Creates captive portal detection future.
11//! - Creates Probe Set futures.
12//!   - These send messages to the reportgen actor.
13//! - Loops driving the futures and handling actor messages:
14//!   - Disables futures as they are completed or aborted.
15//!   - Stop if there are no outstanding tasks/futures, or on timeout.
16//! - Sends the completed report to the net_report actor.
17
18#[cfg(not(wasm_browser))]
19use std::net::{SocketAddrV4, SocketAddrV6};
20use std::{
21    collections::BTreeSet,
22    net::{IpAddr, SocketAddr},
23    sync::Arc,
24};
25
26use http::StatusCode;
27use iroh_base::RelayUrl;
28#[cfg(not(wasm_browser))]
29use iroh_dns::dns::{DnsError, DnsResolver, StaggeredError};
30#[cfg(not(wasm_browser))]
31use iroh_relay::quic::QuicClient;
32use iroh_relay::{
33    RelayConfig, RelayMap, defaults::DEFAULT_RELAY_QUIC_PORT, http::RELAY_PROBE_RELATIVE_PATH,
34};
35use n0_error::{e, stack_error};
36#[cfg(wasm_browser)]
37use n0_future::future::Pending;
38use n0_future::{
39    StreamExt as _,
40    task::{self, AbortOnDropHandle, JoinSet},
41    time::{self, Duration, Instant},
42};
43use rand::seq::IteratorRandom;
44use tokio::sync::mpsc;
45use tokio_util::sync::CancellationToken;
46use tracing::{Instrument, debug, error, info_span, trace, warn};
47#[cfg(not(wasm_browser))]
48use url::Url;
49
50#[cfg(not(wasm_browser))]
51use super::defaults::timeouts::DNS_TIMEOUT;
52use super::{
53    Report,
54    probes::{Probe, ProbePlan},
55};
56#[cfg(not(wasm_browser))]
57use crate::address_lookup::DNS_STAGGERING_MS;
58use crate::{
59    net_report::defaults::timeouts::{
60        CAPTIVE_PORTAL_DELAY, CAPTIVE_PORTAL_TIMEOUT, OVERALL_REPORT_TIMEOUT, PROBES_TIMEOUT,
61    },
62    util::reqwest_client_builder,
63};
64
65/// Holds the state for a single report generation.
66///
67/// Dropping this will cancel the actor and stop the report generation.
68#[derive(Debug)]
69pub(super) struct Client {
70    _drop_guard: AbortOnDropHandle<()>,
71}
72
73/// Some details required from the interface state of the device.
74#[derive(Debug, Clone, Default)]
75pub(crate) struct IfStateDetails {
76    /// Do we have IPv4 capbilities
77    pub(crate) have_v4: bool,
78    /// Do we have IPv6 capbilities
79    pub(crate) have_v6: bool,
80}
81
82impl IfStateDetails {
83    #[cfg(test)]
84    pub(super) fn fake() -> Self {
85        IfStateDetails {
86            have_v4: true,
87            have_v6: true,
88        }
89    }
90}
91
92impl From<netwatch::netmon::State> for IfStateDetails {
93    fn from(value: netwatch::netmon::State) -> Self {
94        IfStateDetails {
95            have_v4: value.have_v4,
96            have_v6: value.have_v6,
97        }
98    }
99}
100
101/// Any state that depends on sockets being available in the current environment.
102///
103/// Factored out so it can be disabled easily in browsers.
104#[cfg(not(wasm_browser))]
105#[derive(Debug, Clone)]
106pub(super) struct SocketState {
107    /// QUIC client to do QUIC address Discovery
108    pub(super) quic_client: Option<QuicClient>,
109    /// The DNS resolver to use for probes that need to resolve DNS records.
110    pub(super) dns_resolver: DnsResolver,
111    /// The proxy to send the HTTP(S) based probes through, if any.
112    pub(super) proxy_url: Option<Url>,
113}
114
115impl Client {
116    /// Creates a new actor generating a single report.
117    ///
118    /// The actor starts running immediately and only generates a single report, after which
119    /// it shuts down.  Dropping this handle will abort the actor.
120    #[allow(clippy::too_many_arguments)]
121    pub(super) fn new(
122        last_report: Option<Report>,
123        relay_map: RelayMap,
124        protocols: BTreeSet<Probe>,
125        captive_portal_check: bool,
126        if_state: IfStateDetails,
127        shutdown_token: CancellationToken,
128        #[cfg(not(wasm_browser))] socket_state: SocketState,
129        #[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
130    ) -> (Self, mpsc::Receiver<ProbeFinished>) {
131        let (msg_tx, msg_rx) = mpsc::channel(32);
132        let actor = Actor {
133            msg_tx,
134            last_report,
135            relay_map,
136            protocols,
137            captive_portal_check,
138            #[cfg(not(wasm_browser))]
139            socket_state,
140            #[cfg(not(wasm_browser))]
141            tls_config,
142            if_state,
143        };
144        let task = task::spawn(
145            actor
146                .run(shutdown_token)
147                .instrument(info_span!("reportgen-actor")),
148        );
149        (
150            Self {
151                _drop_guard: AbortOnDropHandle::new(task),
152            },
153            msg_rx,
154        )
155    }
156}
157
158/// The reportstate actor.
159///
160/// This actor starts, generates a single report and exits.
161#[derive(Debug)]
162struct Actor {
163    msg_tx: mpsc::Sender<ProbeFinished>,
164
165    // Provided state
166    /// The previous report, if it exists.
167    last_report: Option<Report>,
168    /// The relay configuration.
169    relay_map: RelayMap,
170
171    // Internal state.
172    /// Protocols we should attempt to create probes for, if we have the correct
173    /// configuration for that protocol.
174    protocols: BTreeSet<Probe>,
175
176    /// Whether to check for captive portals.
177    captive_portal_check: bool,
178
179    /// Any socket-related state that doesn't exist/work in browsers
180    #[cfg(not(wasm_browser))]
181    socket_state: SocketState,
182    #[cfg(not(wasm_browser))]
183    tls_config: rustls::ClientConfig,
184    if_state: IfStateDetails,
185}
186
187#[allow(missing_docs)]
188#[stack_error(derive, add_meta)]
189#[non_exhaustive]
190pub(super) enum ProbesError {
191    #[error("Probe failed")]
192    ProbeFailure { source: ProbeError },
193    #[error("All probes failed")]
194    AllProbesFailed,
195    #[error("Probe cancelled")]
196    Cancelled,
197    #[error("Probe timed out")]
198    Timeout,
199}
200
201#[derive(Debug)]
202pub(super) enum ProbeFinished {
203    Regular(Result<ProbeReport, ProbesError>),
204    #[cfg(not(wasm_browser))]
205    CaptivePortal(Option<bool>),
206}
207
208impl Actor {
209    async fn run(self, shutdown_token: CancellationToken) {
210        shutdown_token
211            .run_until_cancelled_owned(async {
212                match time::timeout(OVERALL_REPORT_TIMEOUT, self.run_inner()).await {
213                    Ok(()) => trace!("reportgen actor finished"),
214                    Err(time::Elapsed { .. }) => {
215                        debug!("reportgen timed out");
216                    }
217                }
218            })
219            .await;
220    }
221
222    /// Runs the main reportgen actor logic.
223    ///
224    /// This actor runs by:
225    ///
226    /// - Creates a captive portal future.
227    /// - Creates ProbeSet futures in a group of futures.
228    /// - Runs a main loop:
229    ///   - Drives all the above futures.
230    ///   - Receives actor messages (sent by those futures).
231    ///   - Updates the report, cancels unneeded futures.
232    /// - Sends the report to the net_report actor.
233    async fn run_inner(self) {
234        trace!("reportgen actor starting");
235
236        let mut probes = JoinSet::default();
237
238        let _probes_token = self.spawn_probes_task(self.if_state.clone(), &mut probes);
239        let mut num_probes = probes.len();
240
241        let captive_token = self.prepare_captive_portal_task(&mut probes);
242
243        // any reports of working UDP/QUIC?
244        let mut have_udp = false;
245
246        // Check for probes finishing.
247        while let Some(probe_result) = probes.join_next().await {
248            trace!(?probe_result, num_probes, "processing finished probe");
249            match probe_result {
250                Ok(report) => {
251                    #[cfg_attr(wasm_browser, allow(irrefutable_let_patterns))]
252                    if let ProbeFinished::Regular(report) = &report {
253                        have_udp |= report.as_ref().map(|r| r.is_udp()).unwrap_or_default();
254                        num_probes -= 1;
255
256                        // If all probes are done & we have_udp cancel captive
257                        if num_probes == 0 {
258                            trace!("all regular probes done");
259                            debug_assert!(probes.len() <= 1, "{} probes", probes.len());
260
261                            if have_udp {
262                                captive_token.cancel();
263                            }
264                        }
265                    }
266                    self.msg_tx.send(report).await.ok();
267                }
268                Err(e) => {
269                    if e.is_panic() {
270                        error!("Task panicked {:?}", e);
271                        break;
272                    }
273                    warn!("probes task join error: {:?}", e);
274                }
275            }
276        }
277    }
278
279    /// Creates the future which will perform the captive portal check.
280    fn prepare_captive_portal_task(&self, tasks: &mut JoinSet<ProbeFinished>) -> CancellationToken {
281        let token = CancellationToken::new();
282
283        // If we're doing a full probe, also check for a captive portal. We
284        // delay by a bit to wait for UDP QAD to finish, to avoid the probe if
285        // it's unnecessary.
286        #[cfg(not(wasm_browser))]
287        if self.captive_portal_check && self.last_report.is_none() {
288            // Even if we're doing a non-incremental update, we may want to try our
289            // preferred relay for captive portal detection.
290            let preferred_relay = self
291                .last_report
292                .as_ref()
293                .and_then(|l| l.preferred_relay.clone());
294
295            let dns_resolver = self.socket_state.dns_resolver.clone();
296            let proxy_url = self.socket_state.proxy_url.clone();
297            let dm = self.relay_map.clone();
298            let token = token.clone();
299            #[cfg(not(wasm_browser))]
300            let tls_config = self.tls_config.clone();
301            tasks.spawn(
302                async move {
303                    let res = token
304                        .run_until_cancelled_owned(async move {
305                            time::sleep(CAPTIVE_PORTAL_DELAY).await;
306                            trace!("check started after {CAPTIVE_PORTAL_DELAY:?}");
307                            time::timeout(
308                                CAPTIVE_PORTAL_TIMEOUT,
309                                check_captive_portal(
310                                    &dns_resolver,
311                                    &dm,
312                                    preferred_relay,
313                                    tls_config,
314                                    proxy_url.as_ref(),
315                                ),
316                            )
317                            .await
318                        })
319                        .await;
320                    let res = match res {
321                        Some(Ok(Ok(found))) => Some(found),
322                        Some(Ok(Err(err))) => {
323                            match err {
324                                CaptivePortalError::CreateReqwestClient { source, .. }
325                                | CaptivePortalError::HttpRequest { source, .. }
326                                    if source.is_connect() =>
327                                {
328                                    debug!("check_captive_portal failed: {source:#}");
329                                }
330                                err => debug!("check_captive_portal error: {err:#}"),
331                            }
332                            None
333                        }
334                        Some(Err(time::Elapsed { .. })) => {
335                            debug!("probe timed out");
336                            None
337                        }
338                        None => {
339                            trace!("probe cancelled");
340                            None
341                        }
342                    };
343                    ProbeFinished::CaptivePortal(res)
344                }
345                .instrument(info_span!("captive-portal")),
346            );
347        }
348        token
349    }
350
351    /// Prepares the future which will run all the probes as per generated ProbePlan.
352    ///
353    /// Probes operate like the following:
354    ///
355    /// - A future is created for each probe in all probe sets.
356    /// - All probes in a set are grouped in [`JoinSet`].
357    /// - All those probe sets are grouped in one overall [`JoinSet`].
358    ///   - This future is polled by the main actor loop to make progress.
359    /// - Once a probe future is polled:
360    ///   - Many probes start with a delay, they sleep during this time.
361    ///   - When a probe starts it first asks the reportgen [`Actor`] if it is still useful
362    ///     to run.  If not it aborts the entire probe set.
363    ///   - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor.
364    /// - Probes get aborted in several ways:
365    ///   - A running it can fail and abort the entire probe set if it deems the
366    ///     failure permanent.  Probes in a probe set are essentially retries.
367    ///   - Once there are [`ProbeReport`]s from enough relays, all remaining probes are
368    ///     aborted.  That is, the main actor loop stops polling them.
369    fn spawn_probes_task(
370        &self,
371        if_state: IfStateDetails,
372        probes: &mut JoinSet<ProbeFinished>,
373    ) -> CancellationToken {
374        trace!(?if_state, "local interface details");
375        let plan = match self.last_report {
376            Some(ref report) => {
377                ProbePlan::with_last_report(&self.relay_map, report, &self.protocols)
378            }
379            None => ProbePlan::initial(&self.relay_map, &self.protocols),
380        };
381        trace!(%plan, "probe plan");
382
383        let token = CancellationToken::new();
384
385        for probe_set in plan.iter() {
386            let set_token = token.child_token();
387            let proto = probe_set.proto();
388            for (delay, relay) in probe_set.params() {
389                let probe_token = set_token.child_token();
390
391                let fut = probe_token.run_until_cancelled_owned(time::timeout(
392                    PROBES_TIMEOUT,
393                    proto.run(
394                        *delay,
395                        relay.clone(),
396                        #[cfg(not(wasm_browser))]
397                        self.socket_state.clone(),
398                        #[cfg(not(wasm_browser))]
399                        self.tls_config.clone(),
400                    ),
401                ));
402                probes.spawn(
403                    async move {
404                        let res = fut.await;
405                        let res = match res {
406                            Some(Ok(Ok(report))) => Ok(report),
407                            Some(Ok(Err(err))) => {
408                                debug!("probe failed: {:#}", err);
409                                Err(e!(ProbesError::ProbeFailure, err))
410                            }
411                            Some(Err(time::Elapsed { .. })) => Err(e!(ProbesError::Timeout)),
412                            None => Err(e!(ProbesError::Cancelled)),
413                        };
414                        ProbeFinished::Regular(res)
415                    }
416                    .instrument(info_span!(
417                        "run-probe",
418                        ?proto,
419                        ?delay,
420                        relay=%relay.url,
421                    )),
422                );
423            }
424        }
425
426        token
427    }
428}
429
430/// The result of running a probe.
431#[derive(Debug, Clone)]
432pub(super) enum ProbeReport {
433    #[cfg(not(wasm_browser))]
434    QadIpv4(QadProbeReport),
435    #[cfg(not(wasm_browser))]
436    QadIpv6(QadProbeReport),
437    Https(HttpsProbeReport),
438}
439
440impl ProbeReport {
441    #[cfg(not(wasm_browser))]
442    pub(super) fn is_udp(&self) -> bool {
443        matches!(self, Self::QadIpv4(_) | Self::QadIpv6(_))
444    }
445
446    #[cfg(wasm_browser)]
447    pub(super) fn is_udp(&self) -> bool {
448        false
449    }
450}
451
452#[cfg(not(wasm_browser))]
453#[derive(Debug, Clone, PartialEq, Eq)]
454pub(super) struct QadProbeReport {
455    /// The relay that was probed
456    pub(super) relay: RelayUrl,
457    /// The latency to the relay.
458    pub(super) latency: Duration,
459    /// The discovered public address.
460    pub(super) addr: SocketAddr,
461}
462
463#[derive(Debug, Clone)]
464pub(super) struct HttpsProbeReport {
465    /// The relay that was probed
466    pub(super) relay: RelayUrl,
467    /// The latency to the relay.
468    pub(super) latency: Duration,
469}
470
471#[allow(missing_docs)]
472#[stack_error(derive, add_meta)]
473#[non_exhaustive]
474pub(super) enum ProbeError {
475    #[error("Client is gone")]
476    ClientGone,
477    #[error("Probe is no longer useful")]
478    NotUseful,
479    #[error("Failed to run HTTPS probe")]
480    Https { source: MeasureHttpsLatencyError },
481}
482
483#[allow(missing_docs)]
484#[stack_error(derive, add_meta)]
485#[non_exhaustive]
486pub(super) enum QuicError {
487    #[error("No relay available")]
488    NoRelay,
489    #[error("URL must have 'host' to use QUIC address discovery probes")]
490    InvalidUrl,
491}
492
493/// Pieces needed to do QUIC address discovery.
494#[derive(derive_more::Debug, Clone)]
495pub(crate) struct QuicConfig {
496    /// A QUIC Endpoint
497    #[debug("noq::Endpoint")]
498    pub(crate) ep: noq::Endpoint,
499    /// A client config.
500    pub(crate) client_config: rustls::ClientConfig,
501    /// Enable ipv4 QUIC address discovery probes
502    pub(crate) ipv4: bool,
503    /// Enable ipv6 QUIC address discovery probes
504    pub(crate) ipv6: bool,
505}
506
507impl Probe {
508    /// Executes this particular [`Probe`], including using a delayed start if needed.
509    async fn run(
510        self,
511        delay: Duration,
512        relay: Arc<RelayConfig>,
513        #[cfg(not(wasm_browser))] socket_state: SocketState,
514        #[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
515    ) -> Result<ProbeReport, ProbeError> {
516        if !delay.is_zero() {
517            trace!("delaying probe");
518            time::sleep(delay).await;
519        }
520        trace!("starting probe");
521
522        let report = match self {
523            Probe::Https => {
524                match run_https_probe(
525                    #[cfg(not(wasm_browser))]
526                    &socket_state.dns_resolver,
527                    relay.url.clone(),
528                    #[cfg(not(wasm_browser))]
529                    tls_config,
530                    #[cfg(not(wasm_browser))]
531                    socket_state.proxy_url.as_ref(),
532                )
533                .await
534                {
535                    Ok(report) => Ok(ProbeReport::Https(report)),
536                    Err(err) => Err(e!(ProbeError::Https, err)),
537                }
538            }
539            #[cfg(not(wasm_browser))]
540            Probe::QadIpv4 | Probe::QadIpv6 => unreachable!("must not be used"),
541        };
542        debug!(?report, "probe finished");
543        report
544    }
545}
546
547#[cfg(not(wasm_browser))]
548#[stack_error(derive, add_meta)]
549#[non_exhaustive]
550enum CaptivePortalError {
551    #[error(transparent)]
552    DnsLookup {
553        #[error(from)]
554        source: StaggeredError<DnsError>,
555    },
556    #[error("Creating HTTP client failed")]
557    CreateReqwestClient {
558        #[error(std_err)]
559        source: reqwest::Error,
560    },
561    #[error("HTTP request failed")]
562    HttpRequest {
563        #[error(std_err)]
564        source: reqwest::Error,
565    },
566}
567
568/// Reports whether or not we think the system is behind a
569/// captive portal, detected by making a request to a URL that we know should
570/// return a "204 No Content" response and checking if that's what we get.
571///
572/// The boolean return is whether we think we have a captive portal.
573#[cfg(not(wasm_browser))]
574async fn check_captive_portal(
575    dns_resolver: &DnsResolver,
576    dm: &RelayMap,
577    preferred_relay: Option<RelayUrl>,
578    tls_config: rustls::ClientConfig,
579    proxy_url: Option<&Url>,
580) -> Result<bool, CaptivePortalError> {
581    // If we have a preferred relay and we can use it for non-QAD requests, try that;
582    // otherwise, pick a random one suitable for non-STUN requests.
583
584    use crate::util::reqwest_client_builder;
585
586    let preferred_relay = preferred_relay.and_then(|url| dm.get(&url).map(|_| url));
587
588    let url = match preferred_relay {
589        Some(url) => url,
590        None => {
591            let urls: Vec<_> = dm.urls();
592            if urls.is_empty() {
593                trace!("No suitable relay for captive portal check");
594                return Ok(false);
595            }
596
597            let i = (0..urls.len()).choose(&mut rand::rng()).unwrap_or_default();
598            urls[i].clone()
599        }
600    };
601
602    let mut builder = reqwest_client_builder(tls_config, dns_resolver.clone())
603        .redirect(reqwest::redirect::Policy::none());
604    if let Some(proxy_url) = proxy_url {
605        let proxy = reqwest::Proxy::all(proxy_url.clone())
606            .map_err(|err| e!(CaptivePortalError::CreateReqwestClient, err))?;
607        builder = builder.proxy(proxy);
608    } else {
609        // Like the relay connection, ignore any proxy the environment names.
610        builder = builder.no_proxy();
611    }
612
613    let client = builder
614        .build()
615        .map_err(|err| e!(CaptivePortalError::CreateReqwestClient, err))?;
616
617    // Note: the set of valid characters in a challenge and the total
618    // length is limited; see is_challenge_char in bin/iroh-relay for more
619    // details.
620
621    let host_name = url.host_str().unwrap_or_default();
622    let challenge = format!("ts_{host_name}");
623    let portal_url = format!("http://{host_name}/generate_204");
624    let res = client
625        .request(reqwest::Method::GET, portal_url)
626        .header("X-Iroh-Challenge", &challenge)
627        .send()
628        .await
629        .map_err(|err| e!(CaptivePortalError::HttpRequest, err))?;
630
631    let expected_response = format!("response {challenge}");
632    let is_valid_response = res
633        .headers()
634        .get("X-Iroh-Response")
635        .map(|s| s.to_str().unwrap_or_default())
636        == Some(&expected_response);
637
638    trace!(
639        "check_captive_portal url={} status_code={} valid_response={}",
640        res.url(),
641        res.status(),
642        is_valid_response,
643    );
644    let has_captive = res.status() != 204 || !is_valid_response;
645
646    Ok(has_captive)
647}
648
649/// Returns the proper port based on the protocol of the probe.
650#[cfg(not(wasm_browser))]
651fn get_quic_port(relay: &RelayConfig) -> Option<u16> {
652    if let Some(ref quic) = relay.quic {
653        if quic.port == 0 {
654            Some(DEFAULT_RELAY_QUIC_PORT)
655        } else {
656            Some(quic.port)
657        }
658    } else {
659        None
660    }
661}
662
663#[cfg(not(wasm_browser))]
664#[stack_error(derive, add_meta)]
665#[non_exhaustive]
666pub(super) enum GetRelayAddrError {
667    #[error("No valid hostname in the relay URL")]
668    InvalidHostname,
669    #[error("No suitable relay address found for {url} ({addr_type})")]
670    NoAddrFound {
671        url: RelayUrl,
672        addr_type: &'static str,
673    },
674    #[error("DNS lookup failed")]
675    DnsLookup { source: StaggeredError<DnsError> },
676    #[error("Relay is not suitable")]
677    UnsupportedRelay,
678    #[error("HTTPS probes are not implemented")]
679    UnsupportedHttps,
680    #[error("No port available for this protocol")]
681    MissingPort,
682}
683
684/// Returns the IP address to use to communicate to this relay for quic.
685#[cfg(not(wasm_browser))]
686pub(super) async fn get_relay_addr_ipv4(
687    dns_resolver: &DnsResolver,
688    relay: &RelayConfig,
689) -> Result<SocketAddrV4, GetRelayAddrError> {
690    let port = get_quic_port(relay).ok_or_else(|| e!(GetRelayAddrError::MissingPort))?;
691    relay_lookup_ipv4_staggered(dns_resolver, relay, port).await
692}
693
694#[cfg(not(wasm_browser))]
695pub(super) async fn get_relay_addr_ipv6(
696    dns_resolver: &DnsResolver,
697    relay: &RelayConfig,
698) -> Result<SocketAddrV6, GetRelayAddrError> {
699    let port = get_quic_port(relay).ok_or_else(|| e!(GetRelayAddrError::MissingPort))?;
700    relay_lookup_ipv6_staggered(dns_resolver, relay, port).await
701}
702
703/// Do a staggared ipv4 DNS lookup based on [`RelayConfig`]
704///
705/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`]
706#[cfg(not(wasm_browser))]
707async fn relay_lookup_ipv4_staggered(
708    dns_resolver: &DnsResolver,
709    relay: &RelayConfig,
710    port: u16,
711) -> Result<SocketAddrV4, GetRelayAddrError> {
712    match relay.url.host() {
713        Some(url::Host::Domain(hostname)) => {
714            trace!(%hostname, "Performing DNS A lookup for relay addr");
715            match dns_resolver
716                .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS)
717                .await
718            {
719                Ok(mut addrs) => addrs
720                    .next()
721                    .map(|ip| ip.to_canonical())
722                    .map(|addr| match addr {
723                        IpAddr::V4(ip) => SocketAddrV4::new(ip, port),
724                        IpAddr::V6(_) => unreachable!("bad DNS lookup: {:?}", addr),
725                    })
726                    .ok_or_else(|| {
727                        e!(GetRelayAddrError::NoAddrFound {
728                            url: relay.url.clone(),
729                            addr_type: "A",
730                        })
731                    }),
732                Err(err) => Err(e!(GetRelayAddrError::DnsLookup, err)),
733            }
734        }
735        Some(url::Host::Ipv4(addr)) => Ok(SocketAddrV4::new(addr, port)),
736        Some(url::Host::Ipv6(_addr)) => Err(e!(GetRelayAddrError::NoAddrFound {
737            url: relay.url.clone(),
738            addr_type: "A",
739        })),
740        None => Err(e!(GetRelayAddrError::InvalidHostname)),
741    }
742}
743
744/// Do a staggared ipv6 DNS lookup based on [`RelayConfig`]
745///
746/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`]
747#[cfg(not(wasm_browser))]
748async fn relay_lookup_ipv6_staggered(
749    dns_resolver: &DnsResolver,
750    relay: &RelayConfig,
751    port: u16,
752) -> Result<SocketAddrV6, GetRelayAddrError> {
753    match relay.url.host() {
754        Some(url::Host::Domain(hostname)) => {
755            trace!(%hostname, "Performing DNS AAAA lookup for relay addr");
756            match dns_resolver
757                .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS)
758                .await
759            {
760                Ok(mut addrs) => addrs
761                    .next()
762                    .map(|addr| match addr {
763                        IpAddr::V4(_) => unreachable!("bad DNS lookup: {:?}", addr),
764                        IpAddr::V6(ip) => SocketAddrV6::new(ip, port, 0, 0),
765                    })
766                    .ok_or_else(|| {
767                        e!(GetRelayAddrError::NoAddrFound {
768                            url: relay.url.clone(),
769                            addr_type: "AAAA",
770                        })
771                    }),
772                Err(err) => Err(e!(GetRelayAddrError::DnsLookup, err)),
773            }
774        }
775        Some(url::Host::Ipv4(_addr)) => Err(e!(GetRelayAddrError::NoAddrFound {
776            url: relay.url.clone(),
777            addr_type: "AAAA",
778        })),
779        Some(url::Host::Ipv6(addr)) => Ok(SocketAddrV6::new(addr, port, 0, 0)),
780        None => Err(e!(GetRelayAddrError::InvalidHostname)),
781    }
782}
783
784#[stack_error(derive, add_meta)]
785#[non_exhaustive]
786pub(super) enum MeasureHttpsLatencyError {
787    #[error(transparent)]
788    InvalidUrl {
789        #[error(std_err, from)]
790        source: url::ParseError,
791    },
792    #[cfg(not(wasm_browser))]
793    #[error(transparent)]
794    DnsLookup {
795        #[error(from)]
796        source: StaggeredError<DnsError>,
797    },
798    #[error("Creating HTTP client failed")]
799    CreateReqwestClient {
800        #[error(std_err)]
801        source: reqwest::Error,
802    },
803    #[error("HTTP request failed")]
804    HttpRequest {
805        #[error(std_err)]
806        source: reqwest::Error,
807    },
808    #[error("Error response from server {status}: {:?}", status.canonical_reason())]
809    InvalidResponse { status: StatusCode },
810}
811
812/// Executes an HTTPS probe.
813///
814/// If `certs` is provided they will be added to the trusted root certificates, allowing the
815/// use of self-signed certificates for servers.  Currently this is used for testing.
816#[allow(clippy::unused_async)]
817async fn run_https_probe(
818    #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver,
819    relay: RelayUrl,
820    #[cfg(not(wasm_browser))] tls_config: rustls::ClientConfig,
821    #[cfg(not(wasm_browser))] proxy_url: Option<&Url>,
822) -> Result<HttpsProbeReport, MeasureHttpsLatencyError> {
823    trace!("HTTPS probe start");
824    let url = relay.join(RELAY_PROBE_RELATIVE_PATH)?;
825
826    // This should also use same connection establishment as relay client itself, which
827    // needs to be more configurable so users can do more crazy things:
828    // https://github.com/n0-computer/iroh/issues/2901
829    #[cfg(not(wasm_browser))]
830    let mut builder = reqwest_client_builder(tls_config, dns_resolver.clone())
831        .redirect(reqwest::redirect::Policy::none());
832    #[cfg(wasm_browser)]
833    let builder = reqwest_client_builder();
834
835    #[cfg(not(wasm_browser))]
836    if let Some(proxy_url) = proxy_url {
837        let proxy = reqwest::Proxy::all(proxy_url.clone())
838            .map_err(|err| e!(MeasureHttpsLatencyError::CreateReqwestClient, err))?;
839        builder = builder.proxy(proxy);
840    } else {
841        // Like the relay connection, ignore any proxy the environment names.
842        builder = builder.no_proxy();
843    }
844
845    let client = builder
846        .build()
847        .map_err(|err| e!(MeasureHttpsLatencyError::CreateReqwestClient, err))?;
848
849    let start = Instant::now();
850    let response = client
851        .request(reqwest::Method::GET, url)
852        .send()
853        .await
854        .map_err(|err| e!(MeasureHttpsLatencyError::HttpRequest, err))?;
855    let latency = start.elapsed();
856    if response.status().is_success() {
857        // Drain the response body to be nice to the server, up to a limit.
858        const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB
859        let mut body_size = 0;
860        let mut stream = response.bytes_stream();
861        // ignore failing frames
862        while let Some(Ok(chunk)) = stream.next().await {
863            body_size += chunk.len();
864            if body_size >= MAX_BODY_SIZE {
865                break;
866            }
867        }
868
869        Ok(HttpsProbeReport { relay, latency })
870    } else {
871        Err(e!(MeasureHttpsLatencyError::InvalidResponse {
872            status: response.status()
873        }))
874    }
875}
876
877#[cfg(all(test, with_crypto_provider))]
878mod tests {
879    use std::net::Ipv4Addr;
880
881    use iroh_dns::dns::DnsResolver;
882    use iroh_relay::tls::{CaTlsConfig, default_provider};
883    use n0_error::{Result, StdResultExt};
884    use n0_tracing_test::traced_test;
885    use tokio::{io::AsyncReadExt, sync::oneshot};
886
887    use super::{super::test_utils, *};
888
889    #[tokio::test]
890    async fn test_measure_https_latency() -> Result {
891        let (_server, relay) = test_utils::relay().await;
892        let dns_resolver = DnsResolver::new();
893        tracing::info!(relay_url = ?relay.url , "RELAY_URL");
894        let report = run_https_probe(
895            &dns_resolver,
896            relay.url,
897            CaTlsConfig::insecure_skip_verify()
898                .client_config(default_provider())
899                .expect("infallible"),
900            None,
901        )
902        .await?;
903
904        assert!(report.latency > Duration::ZERO);
905
906        Ok(())
907    }
908
909    /// Spawns a fake HTTP proxy which captures the request line of the first connection
910    /// it receives and then hangs up.
911    ///
912    /// Returns the URL to configure as proxy and a receiver for the captured request line.
913    async fn capturing_proxy() -> Result<(Url, oneshot::Receiver<String>)> {
914        let listener = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
915            .await
916            .anyerr()?;
917        let url: Url = format!("http://{}", listener.local_addr().anyerr()?)
918            .parse()
919            .anyerr()?;
920        let (tx, rx) = oneshot::channel();
921        task::spawn(async move {
922            let Ok((mut stream, _)) = listener.accept().await else {
923                return;
924            };
925            let mut line = Vec::new();
926            let mut byte = [0u8; 1];
927            while let Ok(1) = stream.read(&mut byte).await {
928                if byte[0] == b'\n' {
929                    break;
930                }
931                line.push(byte[0]);
932            }
933            tx.send(String::from_utf8_lossy(&line).trim().to_string())
934                .ok();
935        });
936        Ok((url, rx))
937    }
938
939    #[tokio::test]
940    #[traced_test]
941    async fn test_measure_https_latency_via_proxy() -> Result {
942        let (_server, relay) = test_utils::relay().await;
943        let dns_resolver = DnsResolver::new();
944        let (proxy_url, request_line) = capturing_proxy().await?;
945        let target = format!(
946            "{}:{}",
947            relay.url.host_str().expect("relay url has a host"),
948            relay.url.port().expect("relay url has a port")
949        );
950
951        // The probe cannot succeed: the fake proxy never completes the CONNECT tunnel.
952        // What matters is that the probe was attempted via the proxy rather than
953        // connecting to the relay directly.
954        let res = run_https_probe(
955            &dns_resolver,
956            relay.url,
957            CaTlsConfig::insecure_skip_verify()
958                .client_config(default_provider())
959                .expect("infallible"),
960            Some(&proxy_url),
961        )
962        .await;
963        assert!(
964            res.is_err(),
965            "probe must not succeed through a proxy that refuses to tunnel, got {res:?}"
966        );
967
968        let request_line = time::timeout(Duration::from_secs(10), request_line)
969            .await
970            .expect("proxy did not receive a request, the probe bypassed it")
971            .anyerr()?;
972        assert!(
973            request_line.starts_with(&format!("CONNECT {target} ")),
974            "expected the probe to tunnel to {target}, proxy received: {request_line}"
975        );
976
977        Ok(())
978    }
979
980    /// Tests that without a configured proxy the probes ignore the proxy variables in the
981    /// environment, like the relay connection does.
982    ///
983    /// The environment is shared by the whole process, so the probes run in a child
984    /// process of this test binary that starts with the variables set.
985    #[tokio::test]
986    #[traced_test]
987    async fn test_probes_ignore_env_proxy() -> Result {
988        const CHILD_VAR: &str = "IROH_TEST_PROBES_IGNORE_ENV_PROXY";
989        if std::env::var_os(CHILD_VAR).is_some() {
990            let (_server, relay) = test_utils::relay().await;
991            let relay_map = RelayMap::from_iter([relay.clone()]);
992            let dns_resolver = DnsResolver::new();
993            let tls_config = CaTlsConfig::insecure_skip_verify()
994                .client_config(default_provider())
995                .expect("infallible");
996            // Nothing serves the captive portal check here, only where it connects matters.
997            time::timeout(
998                Duration::from_secs(5),
999                check_captive_portal(&dns_resolver, &relay_map, None, tls_config.clone(), None),
1000            )
1001            .await
1002            .ok();
1003            time::timeout(
1004                Duration::from_secs(5),
1005                run_https_probe(&dns_resolver, relay.url, tls_config, None),
1006            )
1007            .await
1008            .anyerr()??;
1009            return Ok(());
1010        }
1011
1012        // The proxy never accepts, so a connection to it stays queued for the check below.
1013        let proxy = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).anyerr()?;
1014        let proxy_url = format!("http://{}", proxy.local_addr().anyerr()?);
1015        // The test harness names tests by their path without the crate.
1016        let (_crate, module) = module_path!().split_once("::").expect("in a crate");
1017        let test_name = format!("{module}::test_probes_ignore_env_proxy");
1018        let mut child = std::process::Command::new(std::env::current_exe().anyerr()?);
1019        child
1020            .args(["--exact", &test_name])
1021            .env(CHILD_VAR, "1")
1022            .env("HTTP_PROXY", &proxy_url)
1023            .env("HTTPS_PROXY", &proxy_url)
1024            .env("ALL_PROXY", &proxy_url)
1025            // Any of these would keep reqwest from using the variables and hide a regression.
1026            .env_remove("NO_PROXY")
1027            .env_remove("no_proxy")
1028            .env_remove("REQUEST_METHOD");
1029        let output = tokio::task::spawn_blocking(move || child.output())
1030            .await
1031            .anyerr()?
1032            .anyerr()?;
1033        let stdout = String::from_utf8_lossy(&output.stdout);
1034        let stderr = String::from_utf8_lossy(&output.stderr);
1035        // A filter that matches no test also exits successfully.
1036        assert!(
1037            output.status.success() && stdout.contains("test result: ok. 1 passed;"),
1038            "the probes failed in the child process:\n{stdout}\n{stderr}"
1039        );
1040
1041        proxy.set_nonblocking(true).anyerr()?;
1042        let accepted = proxy.accept();
1043        assert!(
1044            matches!(&accepted, Err(err) if err.kind() == std::io::ErrorKind::WouldBlock),
1045            "a probe connected to the proxy from the environment: {accepted:?}"
1046        );
1047
1048        Ok(())
1049    }
1050
1051    #[tokio::test]
1052    #[traced_test]
1053    async fn test_qad_probe_v4() -> Result {
1054        let (server, relay) = test_utils::relay().await;
1055        let relay = Arc::new(relay);
1056        let client_config = iroh_relay::tls::make_dangerous_client_config();
1057        let ep = noq::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).anyerr()?;
1058        let client_addr = ep.local_addr().anyerr()?;
1059
1060        let quic_client = iroh_relay::quic::QuicClient::new(ep.clone(), client_config);
1061        let dns_resolver = DnsResolver::default();
1062
1063        let (report, conn) =
1064            super::super::run_probe_v4(relay, quic_client, dns_resolver, CancellationToken::new())
1065                .await
1066                .unwrap();
1067
1068        assert_eq!(report.addr, client_addr);
1069        drop(conn);
1070        ep.wait_idle().await;
1071        server.shutdown().await?;
1072        Ok(())
1073    }
1074}