diff --git a/pr/3337/docs/iroh_bench/enum.ConnectionSelector.html b/pr/3337/docs/iroh_bench/enum.ConnectionSelector.html index a215f24900..abe440bc4a 100644 --- a/pr/3337/docs/iroh_bench/enum.ConnectionSelector.html +++ b/pr/3337/docs/iroh_bench/enum.ConnectionSelector.html @@ -1,7 +1,7 @@ ConnectionSelector in iroh_bench - Rust

Enum ConnectionSelector

Source
pub enum ConnectionSelector {
-    Iroh(Connection),
+    Iroh(Connection),
     Quinn(Connection),
-}

Variants§

§

Iroh(Connection)

§

Quinn(Connection)

Implementations§

Source§

impl ConnectionSelector

Source

pub fn stats(&self)

Source

pub fn close(&self, error_code: u32, reason: &[u8])

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +}

Variants§

§

Iroh(Connection)

§

Quinn(Connection)

Implementations§

Source§

impl ConnectionSelector

Source

pub fn stats(&self)

Source

pub fn close(&self, error_code: u32, reason: &[u8])

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3337/docs/iroh_bench/enum.EndpointSelector.html b/pr/3337/docs/iroh_bench/enum.EndpointSelector.html index 20ff2d0644..868e6c46eb 100644 --- a/pr/3337/docs/iroh_bench/enum.EndpointSelector.html +++ b/pr/3337/docs/iroh_bench/enum.EndpointSelector.html @@ -1,7 +1,7 @@ EndpointSelector in iroh_bench - Rust

Enum EndpointSelector

Source
pub enum EndpointSelector {
-    Iroh(Endpoint),
+    Iroh(Endpoint),
     Quinn(Endpoint),
-}

Variants§

§

Iroh(Endpoint)

§

Quinn(Endpoint)

Implementations§

Source§

impl EndpointSelector

Source

pub async fn close(self)

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +}

Variants§

§

Iroh(Endpoint)

§

Quinn(Endpoint)

Implementations§

Source§

impl EndpointSelector

Source

pub async fn close(self)

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3337/docs/iroh_bench/iroh/fn.connect_client.html b/pr/3337/docs/iroh_bench/iroh/fn.connect_client.html index 965ee0bfb7..3fa8e540a4 100644 --- a/pr/3337/docs/iroh_bench/iroh/fn.connect_client.html +++ b/pr/3337/docs/iroh_bench/iroh/fn.connect_client.html @@ -2,5 +2,5 @@ server_addr: NodeAddr, relay_url: Option<RelayUrl>, opt: Opt, -) -> Result<(Endpoint, Connection)>
Expand description

Create a client endpoint and client connection

+) -> Result<(Endpoint, Connection)>
Expand description

Create a client endpoint and client connection

\ No newline at end of file diff --git a/pr/3337/docs/iroh_bench/iroh/fn.handle_client_stream.html b/pr/3337/docs/iroh_bench/iroh/fn.handle_client_stream.html index 87f15a11c3..576ededd45 100644 --- a/pr/3337/docs/iroh_bench/iroh/fn.handle_client_stream.html +++ b/pr/3337/docs/iroh_bench/iroh/fn.handle_client_stream.html @@ -1,5 +1,5 @@ handle_client_stream in iroh_bench::iroh - Rust

Function handle_client_stream

Source
pub async fn handle_client_stream(
-    connection: &Connection,
+    connection: &Connection,
     upload_size: u64,
     read_unordered: bool,
 ) -> Result<(TransferResult, TransferResult)>
\ No newline at end of file diff --git a/pr/3337/docs/iroh_bench/iroh/fn.server.html b/pr/3337/docs/iroh_bench/iroh/fn.server.html index 9f9c0d203c..7c07ad10ea 100644 --- a/pr/3337/docs/iroh_bench/iroh/fn.server.html +++ b/pr/3337/docs/iroh_bench/iroh/fn.server.html @@ -1,2 +1,2 @@ -server in iroh_bench::iroh - Rust

Function server

Source
pub async fn server(endpoint: Endpoint, opt: Opt) -> Result<()>
Expand description

Take the provided endpoint and run the server

+server in iroh_bench::iroh - Rust

Function server

Source
pub async fn server(endpoint: Endpoint, opt: Opt) -> Result<()>
Expand description

Take the provided endpoint and run the server

\ No newline at end of file diff --git a/pr/3337/docs/iroh_bench/iroh/fn.server_endpoint.html b/pr/3337/docs/iroh_bench/iroh/fn.server_endpoint.html index c16afbe326..3957d28992 100644 --- a/pr/3337/docs/iroh_bench/iroh/fn.server_endpoint.html +++ b/pr/3337/docs/iroh_bench/iroh/fn.server_endpoint.html @@ -2,5 +2,5 @@ rt: &Runtime, relay_url: &Option<RelayUrl>, opt: &Opt, -) -> (NodeAddr, Endpoint)
Expand description

Creates a server endpoint which runs on the given runtime

+) -> (NodeAddr, Endpoint)
Expand description

Creates a server endpoint which runs on the given runtime

\ No newline at end of file diff --git a/pr/3337/docs/src/iroh/net_report/reportgen.rs.html b/pr/3337/docs/src/iroh/net_report/reportgen.rs.html index 83a7b6e058..07d5a20a83 100644 --- a/pr/3337/docs/src/iroh/net_report/reportgen.rs.html +++ b/pr/3337/docs/src/iroh/net_report/reportgen.rs.html @@ -1129,810 +1129,808 @@ 1129#[non_exhaustive] 1130enum CaptivePortalError { 1131 #[snafu(transparent)] -1132 DnsLookup { source: DnsError }, -1133 #[snafu(transparent)] -1134 StaggeredDnsLookup { source: StaggeredError<DnsError> }, -1135 #[snafu(display("Creating HTTP client failed"))] -1136 CreateReqwestClient { source: reqwest::Error }, -1137 #[snafu(display("HTTP request failed"))] -1138 HttpRequest { source: reqwest::Error }, -1139} -1140 -1141/// Reports whether or not we think the system is behind a -1142/// captive portal, detected by making a request to a URL that we know should -1143/// return a "204 No Content" response and checking if that's what we get. -1144/// -1145/// The boolean return is whether we think we have a captive portal. -1146#[cfg(not(wasm_browser))] -1147async fn check_captive_portal( -1148 dns_resolver: &DnsResolver, -1149 dm: &RelayMap, -1150 preferred_relay: Option<RelayUrl>, -1151) -> Result<bool, CaptivePortalError> { -1152 // If we have a preferred relay node and we can use it for non-STUN requests, try that; -1153 // otherwise, pick a random one suitable for non-STUN requests. -1154 let preferred_relay = preferred_relay.and_then(|url| match dm.get_node(&url) { -1155 Some(node) if node.stun_only => Some(url), -1156 _ => None, -1157 }); -1158 -1159 let url = match preferred_relay { -1160 Some(url) => url, -1161 None => { -1162 let urls: Vec<_> = dm -1163 .nodes() -1164 .filter(|n| !n.stun_only) -1165 .map(|n| n.url.clone()) -1166 .collect(); -1167 if urls.is_empty() { -1168 debug!("No suitable relay node for captive portal check"); -1169 return Ok(false); -1170 } -1171 -1172 let i = (0..urls.len()) -1173 .choose(&mut rand::thread_rng()) -1174 .unwrap_or_default(); -1175 urls[i].clone() -1176 } -1177 }; +1132 DnsLookup { source: StaggeredError<DnsError> }, +1133 #[snafu(display("Creating HTTP client failed"))] +1134 CreateReqwestClient { source: reqwest::Error }, +1135 #[snafu(display("HTTP request failed"))] +1136 HttpRequest { source: reqwest::Error }, +1137} +1138 +1139/// Reports whether or not we think the system is behind a +1140/// captive portal, detected by making a request to a URL that we know should +1141/// return a "204 No Content" response and checking if that's what we get. +1142/// +1143/// The boolean return is whether we think we have a captive portal. +1144#[cfg(not(wasm_browser))] +1145async fn check_captive_portal( +1146 dns_resolver: &DnsResolver, +1147 dm: &RelayMap, +1148 preferred_relay: Option<RelayUrl>, +1149) -> Result<bool, CaptivePortalError> { +1150 // If we have a preferred relay node and we can use it for non-STUN requests, try that; +1151 // otherwise, pick a random one suitable for non-STUN requests. +1152 let preferred_relay = preferred_relay.and_then(|url| match dm.get_node(&url) { +1153 Some(node) if node.stun_only => Some(url), +1154 _ => None, +1155 }); +1156 +1157 let url = match preferred_relay { +1158 Some(url) => url, +1159 None => { +1160 let urls: Vec<_> = dm +1161 .nodes() +1162 .filter(|n| !n.stun_only) +1163 .map(|n| n.url.clone()) +1164 .collect(); +1165 if urls.is_empty() { +1166 debug!("No suitable relay node for captive portal check"); +1167 return Ok(false); +1168 } +1169 +1170 let i = (0..urls.len()) +1171 .choose(&mut rand::thread_rng()) +1172 .unwrap_or_default(); +1173 urls[i].clone() +1174 } +1175 }; +1176 +1177 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); 1178 -1179 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); -1180 -1181 if let Some(Host::Domain(domain)) = url.host() { -1182 // Use our own resolver rather than getaddrinfo +1179 if let Some(Host::Domain(domain)) = url.host() { +1180 // Use our own resolver rather than getaddrinfo +1181 // +1182 // Be careful, a non-zero port will override the port in the URI. 1183 // -1184 // Be careful, a non-zero port will override the port in the URI. -1185 // -1186 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race -1187 // them. But our resolver doesn't support that yet. -1188 let addrs: Vec<_> = dns_resolver -1189 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -1190 .await? -1191 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -1192 .collect(); -1193 builder = builder.resolve_to_addrs(domain, &addrs); -1194 } -1195 let client = builder -1196 .build() -1197 .context(captive_portal_error::CreateReqwestClientSnafu)?; -1198 -1199 // Note: the set of valid characters in a challenge and the total -1200 // length is limited; see is_challenge_char in bin/iroh-relay for more -1201 // details. -1202 -1203 let host_name = url.host_str().unwrap_or_default(); -1204 let challenge = format!("ts_{}", host_name); -1205 let portal_url = format!("http://{}/generate_204", host_name); -1206 let res = client -1207 .request(reqwest::Method::GET, portal_url) -1208 .header("X-Tailscale-Challenge", &challenge) -1209 .send() -1210 .await -1211 .context(captive_portal_error::HttpRequestSnafu)?; -1212 -1213 let expected_response = format!("response {challenge}"); -1214 let is_valid_response = res -1215 .headers() -1216 .get("X-Tailscale-Response") -1217 .map(|s| s.to_str().unwrap_or_default()) -1218 == Some(&expected_response); -1219 -1220 debug!( -1221 "check_captive_portal url={} status_code={} valid_response={}", -1222 res.url(), -1223 res.status(), -1224 is_valid_response, -1225 ); -1226 let has_captive = res.status() != 204 || !is_valid_response; -1227 -1228 Ok(has_captive) -1229} -1230 -1231/// Returns the proper port based on the protocol of the probe. -1232fn get_port(relay_node: &RelayNode, proto: &ProbeProto) -> Option<u16> { -1233 match proto { -1234 #[cfg(not(wasm_browser))] -1235 ProbeProto::QuicIpv4 | ProbeProto::QuicIpv6 => { -1236 if let Some(ref quic) = relay_node.quic { -1237 if quic.port == 0 { -1238 Some(DEFAULT_RELAY_QUIC_PORT) -1239 } else { -1240 Some(quic.port) -1241 } -1242 } else { -1243 None -1244 } -1245 } -1246 _ => { -1247 if relay_node.stun_port == 0 { -1248 Some(DEFAULT_STUN_PORT) -1249 } else { -1250 Some(relay_node.stun_port) -1251 } -1252 } -1253 } -1254} -1255 -1256#[cfg(not(wasm_browser))] -1257#[derive(Debug, Snafu)] -1258#[snafu(module)] -1259#[non_exhaustive] -1260pub enum GetRelayAddrError { -1261 #[snafu(display("No valid hostname in the relay URL"))] -1262 InvalidHostname, -1263 #[snafu(display("No suitable relay address found"))] -1264 NoAddrFound, -1265 #[snafu(display("DNS lookup failed"))] -1266 DnsLookup { source: StaggeredError<DnsError> }, -1267 #[snafu(display("Relay node is not suitable for non-STUN probes"))] -1268 UnsupportedRelayNode, -1269 #[snafu(display("HTTPS probes are not implemented"))] -1270 UnsupportedHttps, -1271 #[snafu(display("No port available for this protocol"))] -1272 MissingPort, -1273} -1274 -1275/// Returns the IP address to use to communicate to this relay node. -1276/// -1277/// *proto* specifies the protocol of the probe. Depending on the protocol we may return -1278/// different results. Obviously IPv4 vs IPv6 but a [`RelayNode`] may also have disabled -1279/// some protocols. -1280/// -1281/// If the protocol is `QuicIpv4` or `QuicIpv6`, and `IpMappedAddresses` is not `None`, we -1282/// assume that we are running this net report with `iroh`, and need to provide mapped -1283/// addresses to the probe in order for it to function in the specialize iroh-quinn -1284/// endpoint that expects mapped addresses. -1285#[cfg(not(wasm_browser))] -1286async fn get_relay_addr( -1287 dns_resolver: &DnsResolver, -1288 relay_node: &RelayNode, -1289 proto: ProbeProto, -1290) -> Result<SocketAddr, GetRelayAddrError> { -1291 use snafu::OptionExt; -1292 -1293 if relay_node.stun_only && !matches!(proto, ProbeProto::StunIpv4 | ProbeProto::StunIpv6) { -1294 return Err(get_relay_addr_error::UnsupportedRelayNodeSnafu.build()); -1295 } -1296 let port = get_port(relay_node, &proto).context(get_relay_addr_error::MissingPortSnafu)?; -1297 -1298 match proto { -1299 ProbeProto::StunIpv4 | ProbeProto::IcmpV4 | ProbeProto::QuicIpv4 => { -1300 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await -1301 } -1302 -1303 ProbeProto::StunIpv6 | ProbeProto::IcmpV6 | ProbeProto::QuicIpv6 => { -1304 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await -1305 } -1306 -1307 ProbeProto::Https => Err(get_relay_addr_error::UnsupportedHttpsSnafu.build()), -1308 } -1309} -1310 -1311/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] -1312/// -1313/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] -1314#[cfg(not(wasm_browser))] -1315async fn relay_lookup_ipv4_staggered( -1316 dns_resolver: &DnsResolver, -1317 relay: &RelayNode, -1318 port: u16, -1319) -> Result<SocketAddr, GetRelayAddrError> { -1320 match relay.url.host() { -1321 Some(url::Host::Domain(hostname)) => { -1322 debug!(%hostname, "Performing DNS A lookup for relay addr"); -1323 match dns_resolver -1324 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -1325 .await -1326 { -1327 Ok(mut addrs) => addrs -1328 .next() -1329 .map(|ip| ip.to_canonical()) -1330 .map(|addr| SocketAddr::new(addr, port)) -1331 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -1332 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -1333 } -1334 } -1335 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), -1336 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -1337 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -1338 } -1339} -1340 -1341/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] -1342/// -1343/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] -1344#[cfg(not(wasm_browser))] -1345async fn relay_lookup_ipv6_staggered( -1346 dns_resolver: &DnsResolver, -1347 relay: &RelayNode, -1348 port: u16, -1349) -> Result<SocketAddr, GetRelayAddrError> { -1350 match relay.url.host() { -1351 Some(url::Host::Domain(hostname)) => { -1352 debug!(%hostname, "Performing DNS AAAA lookup for relay addr"); -1353 match dns_resolver -1354 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -1355 .await -1356 { -1357 Ok(mut addrs) => addrs -1358 .next() -1359 .map(|ip| ip.to_canonical()) -1360 .map(|addr| SocketAddr::new(addr, port)) -1361 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -1362 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -1363 } -1364 } -1365 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), -1366 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -1367 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -1368 } -1369} -1370 -1371/// Runs an ICMP IPv4 or IPv6 probe. -1372/// -1373/// The `pinger` is passed in so the ping sockets are only bound once -1374/// for the probe set. -1375#[cfg(not(wasm_browser))] -1376async fn run_icmp_probe( -1377 probe: Probe, -1378 relay_addr: SocketAddr, -1379 pinger: Pinger, -1380) -> Result<ProbeReport, ProbeErrorWithProbe> { -1381 match probe.proto() { -1382 ProbeProto::IcmpV4 => debug_assert!(relay_addr.is_ipv4()), -1383 ProbeProto::IcmpV6 => debug_assert!(relay_addr.is_ipv6()), -1384 _ => debug_assert!(false, "wrong probe"), -1385 } -1386 const DATA: &[u8; 15] = b"iroh icmp probe"; -1387 debug!(dst = %relay_addr, len = DATA.len(), "ICMP Ping started"); -1388 let latency = pinger -1389 .send(relay_addr.ip(), DATA) -1390 .await -1391 .map_err(|err| match err { -1392 PingError::CreateClientIpv4 { .. } | PingError::CreateClientIpv6 { .. } => { -1393 ProbeErrorWithProbe::AbortSet(probe_error::IcmpSnafu.into_error(err), probe.clone()) -1394 } -1395 #[cfg(not(wasm_browser))] -1396 PingError::Ping { .. } => { -1397 ProbeErrorWithProbe::Error(probe_error::IcmpSnafu.into_error(err), probe.clone()) -1398 } -1399 })?; -1400 debug!(dst = %relay_addr, len = DATA.len(), ?latency, "ICMP ping done"); -1401 let mut report = ProbeReport::new(probe); -1402 report.latency = Some(latency); -1403 match relay_addr { -1404 SocketAddr::V4(_) => { -1405 report.ipv4_can_send = true; -1406 report.icmpv4 = Some(true); -1407 } -1408 SocketAddr::V6(_) => { -1409 report.ipv6_can_send = true; -1410 report.icmpv6 = Some(true); -1411 } -1412 } -1413 Ok(report) -1414} -1415 -1416#[derive(Debug, Snafu)] -1417#[snafu(module)] -1418#[non_exhaustive] -1419enum MeasureHttpsLatencyError { -1420 #[snafu(transparent)] -1421 InvalidUrl { source: url::ParseError }, -1422 #[cfg(not(wasm_browser))] -1423 #[snafu(transparent)] -1424 DnsLookup { source: StaggeredError<DnsError> }, -1425 #[cfg(not(wasm_browser))] -1426 #[snafu(display("Invalid certificate"))] -1427 InvalidCertificate { source: reqwest::Error }, -1428 #[snafu(display("Creating HTTP client failed"))] -1429 CreateReqwestClient { source: reqwest::Error }, -1430 #[snafu(display("HTTP request failed"))] -1431 HttpRequest { source: reqwest::Error }, -1432 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] -1433 InvalidResponse { status: StatusCode }, -1434} -1435 -1436/// Executes an HTTPS probe. -1437/// -1438/// If `certs` is provided they will be added to the trusted root certificates, allowing the -1439/// use of self-signed certificates for servers. Currently this is used for testing. -1440#[allow(clippy::unused_async)] -1441async fn measure_https_latency( -1442 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, -1443 node: &RelayNode, -1444 certs: Option<Vec<rustls::pki_types::CertificateDer<'static>>>, -1445) -> Result<(Duration, IpAddr), MeasureHttpsLatencyError> { -1446 let url = node.url.join(RELAY_PROBE_PATH)?; -1447 -1448 // This should also use same connection establishment as relay client itself, which -1449 // needs to be more configurable so users can do more crazy things: -1450 // https://github.com/n0-computer/iroh/issues/2901 -1451 let mut builder = reqwest::ClientBuilder::new(); -1452 -1453 #[cfg(not(wasm_browser))] -1454 { -1455 builder = builder.redirect(reqwest::redirect::Policy::none()); -1456 } -1457 -1458 #[cfg(not(wasm_browser))] -1459 if let Some(Host::Domain(domain)) = url.host() { -1460 // Use our own resolver rather than getaddrinfo +1184 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race +1185 // them. But our resolver doesn't support that yet. +1186 let addrs: Vec<_> = dns_resolver +1187 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +1188 .await? +1189 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +1190 .collect(); +1191 builder = builder.resolve_to_addrs(domain, &addrs); +1192 } +1193 let client = builder +1194 .build() +1195 .context(captive_portal_error::CreateReqwestClientSnafu)?; +1196 +1197 // Note: the set of valid characters in a challenge and the total +1198 // length is limited; see is_challenge_char in bin/iroh-relay for more +1199 // details. +1200 +1201 let host_name = url.host_str().unwrap_or_default(); +1202 let challenge = format!("ts_{}", host_name); +1203 let portal_url = format!("http://{}/generate_204", host_name); +1204 let res = client +1205 .request(reqwest::Method::GET, portal_url) +1206 .header("X-Tailscale-Challenge", &challenge) +1207 .send() +1208 .await +1209 .context(captive_portal_error::HttpRequestSnafu)?; +1210 +1211 let expected_response = format!("response {challenge}"); +1212 let is_valid_response = res +1213 .headers() +1214 .get("X-Tailscale-Response") +1215 .map(|s| s.to_str().unwrap_or_default()) +1216 == Some(&expected_response); +1217 +1218 debug!( +1219 "check_captive_portal url={} status_code={} valid_response={}", +1220 res.url(), +1221 res.status(), +1222 is_valid_response, +1223 ); +1224 let has_captive = res.status() != 204 || !is_valid_response; +1225 +1226 Ok(has_captive) +1227} +1228 +1229/// Returns the proper port based on the protocol of the probe. +1230fn get_port(relay_node: &RelayNode, proto: &ProbeProto) -> Option<u16> { +1231 match proto { +1232 #[cfg(not(wasm_browser))] +1233 ProbeProto::QuicIpv4 | ProbeProto::QuicIpv6 => { +1234 if let Some(ref quic) = relay_node.quic { +1235 if quic.port == 0 { +1236 Some(DEFAULT_RELAY_QUIC_PORT) +1237 } else { +1238 Some(quic.port) +1239 } +1240 } else { +1241 None +1242 } +1243 } +1244 _ => { +1245 if relay_node.stun_port == 0 { +1246 Some(DEFAULT_STUN_PORT) +1247 } else { +1248 Some(relay_node.stun_port) +1249 } +1250 } +1251 } +1252} +1253 +1254#[cfg(not(wasm_browser))] +1255#[derive(Debug, Snafu)] +1256#[snafu(module)] +1257#[non_exhaustive] +1258pub enum GetRelayAddrError { +1259 #[snafu(display("No valid hostname in the relay URL"))] +1260 InvalidHostname, +1261 #[snafu(display("No suitable relay address found"))] +1262 NoAddrFound, +1263 #[snafu(display("DNS lookup failed"))] +1264 DnsLookup { source: StaggeredError<DnsError> }, +1265 #[snafu(display("Relay node is not suitable for non-STUN probes"))] +1266 UnsupportedRelayNode, +1267 #[snafu(display("HTTPS probes are not implemented"))] +1268 UnsupportedHttps, +1269 #[snafu(display("No port available for this protocol"))] +1270 MissingPort, +1271} +1272 +1273/// Returns the IP address to use to communicate to this relay node. +1274/// +1275/// *proto* specifies the protocol of the probe. Depending on the protocol we may return +1276/// different results. Obviously IPv4 vs IPv6 but a [`RelayNode`] may also have disabled +1277/// some protocols. +1278/// +1279/// If the protocol is `QuicIpv4` or `QuicIpv6`, and `IpMappedAddresses` is not `None`, we +1280/// assume that we are running this net report with `iroh`, and need to provide mapped +1281/// addresses to the probe in order for it to function in the specialize iroh-quinn +1282/// endpoint that expects mapped addresses. +1283#[cfg(not(wasm_browser))] +1284async fn get_relay_addr( +1285 dns_resolver: &DnsResolver, +1286 relay_node: &RelayNode, +1287 proto: ProbeProto, +1288) -> Result<SocketAddr, GetRelayAddrError> { +1289 use snafu::OptionExt; +1290 +1291 if relay_node.stun_only && !matches!(proto, ProbeProto::StunIpv4 | ProbeProto::StunIpv6) { +1292 return Err(get_relay_addr_error::UnsupportedRelayNodeSnafu.build()); +1293 } +1294 let port = get_port(relay_node, &proto).context(get_relay_addr_error::MissingPortSnafu)?; +1295 +1296 match proto { +1297 ProbeProto::StunIpv4 | ProbeProto::IcmpV4 | ProbeProto::QuicIpv4 => { +1298 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await +1299 } +1300 +1301 ProbeProto::StunIpv6 | ProbeProto::IcmpV6 | ProbeProto::QuicIpv6 => { +1302 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await +1303 } +1304 +1305 ProbeProto::Https => Err(get_relay_addr_error::UnsupportedHttpsSnafu.build()), +1306 } +1307} +1308 +1309/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] +1310/// +1311/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] +1312#[cfg(not(wasm_browser))] +1313async fn relay_lookup_ipv4_staggered( +1314 dns_resolver: &DnsResolver, +1315 relay: &RelayNode, +1316 port: u16, +1317) -> Result<SocketAddr, GetRelayAddrError> { +1318 match relay.url.host() { +1319 Some(url::Host::Domain(hostname)) => { +1320 debug!(%hostname, "Performing DNS A lookup for relay addr"); +1321 match dns_resolver +1322 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +1323 .await +1324 { +1325 Ok(mut addrs) => addrs +1326 .next() +1327 .map(|ip| ip.to_canonical()) +1328 .map(|addr| SocketAddr::new(addr, port)) +1329 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +1330 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +1331 } +1332 } +1333 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), +1334 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +1335 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +1336 } +1337} +1338 +1339/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] +1340/// +1341/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] +1342#[cfg(not(wasm_browser))] +1343async fn relay_lookup_ipv6_staggered( +1344 dns_resolver: &DnsResolver, +1345 relay: &RelayNode, +1346 port: u16, +1347) -> Result<SocketAddr, GetRelayAddrError> { +1348 match relay.url.host() { +1349 Some(url::Host::Domain(hostname)) => { +1350 debug!(%hostname, "Performing DNS AAAA lookup for relay addr"); +1351 match dns_resolver +1352 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +1353 .await +1354 { +1355 Ok(mut addrs) => addrs +1356 .next() +1357 .map(|ip| ip.to_canonical()) +1358 .map(|addr| SocketAddr::new(addr, port)) +1359 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +1360 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +1361 } +1362 } +1363 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), +1364 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +1365 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +1366 } +1367} +1368 +1369/// Runs an ICMP IPv4 or IPv6 probe. +1370/// +1371/// The `pinger` is passed in so the ping sockets are only bound once +1372/// for the probe set. +1373#[cfg(not(wasm_browser))] +1374async fn run_icmp_probe( +1375 probe: Probe, +1376 relay_addr: SocketAddr, +1377 pinger: Pinger, +1378) -> Result<ProbeReport, ProbeErrorWithProbe> { +1379 match probe.proto() { +1380 ProbeProto::IcmpV4 => debug_assert!(relay_addr.is_ipv4()), +1381 ProbeProto::IcmpV6 => debug_assert!(relay_addr.is_ipv6()), +1382 _ => debug_assert!(false, "wrong probe"), +1383 } +1384 const DATA: &[u8; 15] = b"iroh icmp probe"; +1385 debug!(dst = %relay_addr, len = DATA.len(), "ICMP Ping started"); +1386 let latency = pinger +1387 .send(relay_addr.ip(), DATA) +1388 .await +1389 .map_err(|err| match err { +1390 PingError::CreateClientIpv4 { .. } | PingError::CreateClientIpv6 { .. } => { +1391 ProbeErrorWithProbe::AbortSet(probe_error::IcmpSnafu.into_error(err), probe.clone()) +1392 } +1393 #[cfg(not(wasm_browser))] +1394 PingError::Ping { .. } => { +1395 ProbeErrorWithProbe::Error(probe_error::IcmpSnafu.into_error(err), probe.clone()) +1396 } +1397 })?; +1398 debug!(dst = %relay_addr, len = DATA.len(), ?latency, "ICMP ping done"); +1399 let mut report = ProbeReport::new(probe); +1400 report.latency = Some(latency); +1401 match relay_addr { +1402 SocketAddr::V4(_) => { +1403 report.ipv4_can_send = true; +1404 report.icmpv4 = Some(true); +1405 } +1406 SocketAddr::V6(_) => { +1407 report.ipv6_can_send = true; +1408 report.icmpv6 = Some(true); +1409 } +1410 } +1411 Ok(report) +1412} +1413 +1414#[derive(Debug, Snafu)] +1415#[snafu(module)] +1416#[non_exhaustive] +1417enum MeasureHttpsLatencyError { +1418 #[snafu(transparent)] +1419 InvalidUrl { source: url::ParseError }, +1420 #[cfg(not(wasm_browser))] +1421 #[snafu(transparent)] +1422 DnsLookup { source: StaggeredError<DnsError> }, +1423 #[cfg(not(wasm_browser))] +1424 #[snafu(display("Invalid certificate"))] +1425 InvalidCertificate { source: reqwest::Error }, +1426 #[snafu(display("Creating HTTP client failed"))] +1427 CreateReqwestClient { source: reqwest::Error }, +1428 #[snafu(display("HTTP request failed"))] +1429 HttpRequest { source: reqwest::Error }, +1430 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] +1431 InvalidResponse { status: StatusCode }, +1432} +1433 +1434/// Executes an HTTPS probe. +1435/// +1436/// If `certs` is provided they will be added to the trusted root certificates, allowing the +1437/// use of self-signed certificates for servers. Currently this is used for testing. +1438#[allow(clippy::unused_async)] +1439async fn measure_https_latency( +1440 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, +1441 node: &RelayNode, +1442 certs: Option<Vec<rustls::pki_types::CertificateDer<'static>>>, +1443) -> Result<(Duration, IpAddr), MeasureHttpsLatencyError> { +1444 let url = node.url.join(RELAY_PROBE_PATH)?; +1445 +1446 // This should also use same connection establishment as relay client itself, which +1447 // needs to be more configurable so users can do more crazy things: +1448 // https://github.com/n0-computer/iroh/issues/2901 +1449 let mut builder = reqwest::ClientBuilder::new(); +1450 +1451 #[cfg(not(wasm_browser))] +1452 { +1453 builder = builder.redirect(reqwest::redirect::Policy::none()); +1454 } +1455 +1456 #[cfg(not(wasm_browser))] +1457 if let Some(Host::Domain(domain)) = url.host() { +1458 // Use our own resolver rather than getaddrinfo +1459 // +1460 // Be careful, a non-zero port will override the port in the URI. 1461 // -1462 // Be careful, a non-zero port will override the port in the URI. -1463 // -1464 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function -1465 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and -1466 // IPv6 though. But our resolver does not have a function for that yet. -1467 let addrs: Vec<_> = dns_resolver -1468 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -1469 .await? -1470 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -1471 .collect(); -1472 builder = builder.resolve_to_addrs(domain, &addrs); -1473 } -1474 -1475 #[cfg(not(wasm_browser))] -1476 if let Some(certs) = certs { -1477 for cert in certs { -1478 let cert = reqwest::Certificate::from_der(&cert) -1479 .context(measure_https_latency_error::InvalidCertificateSnafu)?; -1480 builder = builder.add_root_certificate(cert); -1481 } -1482 } -1483 let client = builder -1484 .build() -1485 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; -1486 -1487 let start = Instant::now(); -1488 let response = client -1489 .request(reqwest::Method::GET, url) -1490 .send() -1491 .await -1492 .context(measure_https_latency_error::HttpRequestSnafu)?; -1493 let latency = start.elapsed(); -1494 if response.status().is_success() { -1495 // Only `None` if a different hyper HttpConnector in the request. -1496 #[cfg(not(wasm_browser))] -1497 let remote_ip = response -1498 .remote_addr() -1499 .expect("missing HttpInfo from HttpConnector") -1500 .ip(); -1501 #[cfg(wasm_browser)] -1502 let remote_ip = IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED); -1503 -1504 // Drain the response body to be nice to the server, up to a limit. -1505 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB -1506 let mut body_size = 0; -1507 let mut stream = response.bytes_stream(); -1508 // ignore failing frames -1509 while let Some(Ok(chunk)) = stream.next().await { -1510 body_size += chunk.len(); -1511 if body_size >= MAX_BODY_SIZE { -1512 break; -1513 } -1514 } -1515 -1516 Ok((latency, remote_ip)) -1517 } else { -1518 Err(measure_https_latency_error::InvalidResponseSnafu { -1519 status: response.status(), -1520 } -1521 .build()) -1522 } -1523} -1524 -1525/// Updates a net_report [`Report`] with a new [`ProbeReport`]. -1526fn update_report(report: &mut Report, probe_report: ProbeReport) { -1527 let relay_node = probe_report.probe.node(); -1528 if let Some(latency) = probe_report.latency { -1529 report -1530 .relay_latency -1531 .update_relay(relay_node.url.clone(), latency); -1532 -1533 #[cfg(not(wasm_browser))] -1534 if matches!( -1535 probe_report.probe.proto(), -1536 ProbeProto::StunIpv4 -1537 | ProbeProto::StunIpv6 -1538 | ProbeProto::QuicIpv4 -1539 | ProbeProto::QuicIpv6 -1540 ) { -1541 report.udp = true; -1542 -1543 match probe_report.addr { -1544 Some(SocketAddr::V4(ipp)) => { -1545 report.ipv4 = true; -1546 report -1547 .relay_v4_latency -1548 .update_relay(relay_node.url.clone(), latency); -1549 if report.global_v4.is_none() { -1550 report.global_v4 = Some(ipp); -1551 } else if report.global_v4 != Some(ipp) { -1552 report.mapping_varies_by_dest_ip = Some(true); -1553 } else if report.mapping_varies_by_dest_ip.is_none() { -1554 report.mapping_varies_by_dest_ip = Some(false); -1555 } -1556 } -1557 Some(SocketAddr::V6(ipp)) => { -1558 report.ipv6 = true; -1559 report -1560 .relay_v6_latency -1561 .update_relay(relay_node.url.clone(), latency); -1562 if report.global_v6.is_none() { -1563 report.global_v6 = Some(ipp); -1564 } else if report.global_v6 != Some(ipp) { -1565 report.mapping_varies_by_dest_ipv6 = Some(true); -1566 warn!("IPv6 Address detected by STUN varies by destination"); -1567 } else if report.mapping_varies_by_dest_ipv6.is_none() { -1568 report.mapping_varies_by_dest_ipv6 = Some(false); -1569 } -1570 } -1571 None => { -1572 // If we are here we had a relay server latency reported from a STUN probe. -1573 // Thus we must have a reported address. -1574 debug_assert!(probe_report.addr.is_some()); -1575 } -1576 } -1577 } -1578 } -1579 report.ipv4_can_send |= probe_report.ipv4_can_send; -1580 report.ipv6_can_send |= probe_report.ipv6_can_send; -1581 report.icmpv4 = report -1582 .icmpv4 -1583 .map(|val| val || probe_report.icmpv4.unwrap_or_default()) -1584 .or(probe_report.icmpv4); -1585 report.icmpv6 = report -1586 .icmpv6 -1587 .map(|val| val || probe_report.icmpv6.unwrap_or_default()) -1588 .or(probe_report.icmpv6); -1589} -1590 -1591/// Resolves to pending if the inner is `None`. -1592#[derive(Debug)] -1593pub(crate) struct MaybeFuture<T> { -1594 /// Future to be polled. -1595 pub inner: Option<T>, -1596} -1597 -1598// NOTE: explicit implementation to bypass derive unnecessary bounds -1599impl<T> Default for MaybeFuture<T> { -1600 fn default() -> Self { -1601 MaybeFuture { inner: None } -1602 } -1603} -1604 -1605impl<T: Future + Unpin> Future for MaybeFuture<T> { -1606 type Output = T::Output; -1607 -1608 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { -1609 match self.inner { -1610 Some(ref mut t) => Pin::new(t).poll(cx), -1611 None => Poll::Pending, -1612 } -1613 } -1614} -1615 -1616#[cfg(test)] -1617mod tests { -1618 use std::net::{Ipv4Addr, Ipv6Addr}; -1619 -1620 use n0_snafu::{Result, ResultExt}; -1621 use tracing_test::traced_test; -1622 -1623 use super::{super::test_utils, *}; -1624 use crate::net_report::dns; -1625 -1626 #[tokio::test] -1627 #[traced_test] -1628 async fn test_update_report_stun_working() { -1629 let (_server_a, relay_a) = test_utils::relay().await; -1630 let (_server_b, relay_b) = test_utils::relay().await; -1631 -1632 let mut report = Report::default(); -1633 let relay_a = Arc::new(relay_a); -1634 let relay_b = Arc::new(relay_b); -1635 -1636 // A STUN IPv4 probe from the the first relay server. -1637 let probe_report_a = ProbeReport { -1638 ipv4_can_send: true, -1639 ipv6_can_send: false, -1640 icmpv4: None, -1641 icmpv6: None, -1642 latency: Some(Duration::from_millis(5)), -1643 probe: Probe::StunIpv4 { -1644 delay: Duration::ZERO, -1645 node: relay_a.clone(), -1646 }, -1647 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1648 }; -1649 update_report(&mut report, probe_report_a.clone()); -1650 -1651 assert!(report.udp); -1652 assert_eq!( -1653 report.relay_latency.get(&relay_a.url).unwrap(), -1654 Duration::from_millis(5) -1655 ); -1656 assert_eq!( -1657 report.relay_v4_latency.get(&relay_a.url).unwrap(), -1658 Duration::from_millis(5) -1659 ); -1660 assert!(report.ipv4_can_send); -1661 assert!(!report.ipv6_can_send); -1662 -1663 // A second STUN IPv4 probe, same external IP detected but slower. -1664 let probe_report_b = ProbeReport { -1665 latency: Some(Duration::from_millis(8)), -1666 probe: Probe::StunIpv4 { -1667 delay: Duration::ZERO, -1668 node: relay_b.clone(), -1669 }, -1670 ..probe_report_a -1671 }; -1672 update_report(&mut report, probe_report_b); -1673 -1674 assert!(report.udp); -1675 assert_eq!( -1676 report.relay_latency.get(&relay_a.url).unwrap(), -1677 Duration::from_millis(5) -1678 ); -1679 assert_eq!( -1680 report.relay_v4_latency.get(&relay_a.url).unwrap(), -1681 Duration::from_millis(5) -1682 ); -1683 assert!(report.ipv4_can_send); -1684 assert!(!report.ipv6_can_send); -1685 -1686 // A STUN IPv6 probe, this one is faster. -1687 let probe_report_a_ipv6 = ProbeReport { -1688 ipv4_can_send: false, -1689 ipv6_can_send: true, -1690 icmpv4: None, -1691 icmpv6: None, -1692 latency: Some(Duration::from_millis(4)), -1693 probe: Probe::StunIpv6 { -1694 delay: Duration::ZERO, -1695 node: relay_a.clone(), -1696 }, -1697 addr: Some((Ipv6Addr::new(2001, 0xdb8, 0, 0, 0, 0, 0, 1), 1234).into()), -1698 }; -1699 update_report(&mut report, probe_report_a_ipv6); -1700 -1701 assert!(report.udp); -1702 assert_eq!( -1703 report.relay_latency.get(&relay_a.url).unwrap(), -1704 Duration::from_millis(4) -1705 ); -1706 assert_eq!( -1707 report.relay_v6_latency.get(&relay_a.url).unwrap(), -1708 Duration::from_millis(4) -1709 ); -1710 assert!(report.ipv4_can_send); -1711 assert!(report.ipv6_can_send); -1712 } -1713 -1714 #[tokio::test] -1715 #[traced_test] -1716 async fn test_update_report_icmp() { -1717 let (_server_a, relay_a) = test_utils::relay().await; -1718 let (_server_b, relay_b) = test_utils::relay().await; -1719 let relay_a = Arc::new(relay_a); -1720 let relay_b = Arc::new(relay_b); +1462 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function +1463 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and +1464 // IPv6 though. But our resolver does not have a function for that yet. +1465 let addrs: Vec<_> = dns_resolver +1466 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +1467 .await? +1468 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +1469 .collect(); +1470 builder = builder.resolve_to_addrs(domain, &addrs); +1471 } +1472 +1473 #[cfg(not(wasm_browser))] +1474 if let Some(certs) = certs { +1475 for cert in certs { +1476 let cert = reqwest::Certificate::from_der(&cert) +1477 .context(measure_https_latency_error::InvalidCertificateSnafu)?; +1478 builder = builder.add_root_certificate(cert); +1479 } +1480 } +1481 let client = builder +1482 .build() +1483 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; +1484 +1485 let start = Instant::now(); +1486 let response = client +1487 .request(reqwest::Method::GET, url) +1488 .send() +1489 .await +1490 .context(measure_https_latency_error::HttpRequestSnafu)?; +1491 let latency = start.elapsed(); +1492 if response.status().is_success() { +1493 // Only `None` if a different hyper HttpConnector in the request. +1494 #[cfg(not(wasm_browser))] +1495 let remote_ip = response +1496 .remote_addr() +1497 .expect("missing HttpInfo from HttpConnector") +1498 .ip(); +1499 #[cfg(wasm_browser)] +1500 let remote_ip = IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED); +1501 +1502 // Drain the response body to be nice to the server, up to a limit. +1503 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB +1504 let mut body_size = 0; +1505 let mut stream = response.bytes_stream(); +1506 // ignore failing frames +1507 while let Some(Ok(chunk)) = stream.next().await { +1508 body_size += chunk.len(); +1509 if body_size >= MAX_BODY_SIZE { +1510 break; +1511 } +1512 } +1513 +1514 Ok((latency, remote_ip)) +1515 } else { +1516 Err(measure_https_latency_error::InvalidResponseSnafu { +1517 status: response.status(), +1518 } +1519 .build()) +1520 } +1521} +1522 +1523/// Updates a net_report [`Report`] with a new [`ProbeReport`]. +1524fn update_report(report: &mut Report, probe_report: ProbeReport) { +1525 let relay_node = probe_report.probe.node(); +1526 if let Some(latency) = probe_report.latency { +1527 report +1528 .relay_latency +1529 .update_relay(relay_node.url.clone(), latency); +1530 +1531 #[cfg(not(wasm_browser))] +1532 if matches!( +1533 probe_report.probe.proto(), +1534 ProbeProto::StunIpv4 +1535 | ProbeProto::StunIpv6 +1536 | ProbeProto::QuicIpv4 +1537 | ProbeProto::QuicIpv6 +1538 ) { +1539 report.udp = true; +1540 +1541 match probe_report.addr { +1542 Some(SocketAddr::V4(ipp)) => { +1543 report.ipv4 = true; +1544 report +1545 .relay_v4_latency +1546 .update_relay(relay_node.url.clone(), latency); +1547 if report.global_v4.is_none() { +1548 report.global_v4 = Some(ipp); +1549 } else if report.global_v4 != Some(ipp) { +1550 report.mapping_varies_by_dest_ip = Some(true); +1551 } else if report.mapping_varies_by_dest_ip.is_none() { +1552 report.mapping_varies_by_dest_ip = Some(false); +1553 } +1554 } +1555 Some(SocketAddr::V6(ipp)) => { +1556 report.ipv6 = true; +1557 report +1558 .relay_v6_latency +1559 .update_relay(relay_node.url.clone(), latency); +1560 if report.global_v6.is_none() { +1561 report.global_v6 = Some(ipp); +1562 } else if report.global_v6 != Some(ipp) { +1563 report.mapping_varies_by_dest_ipv6 = Some(true); +1564 warn!("IPv6 Address detected by STUN varies by destination"); +1565 } else if report.mapping_varies_by_dest_ipv6.is_none() { +1566 report.mapping_varies_by_dest_ipv6 = Some(false); +1567 } +1568 } +1569 None => { +1570 // If we are here we had a relay server latency reported from a STUN probe. +1571 // Thus we must have a reported address. +1572 debug_assert!(probe_report.addr.is_some()); +1573 } +1574 } +1575 } +1576 } +1577 report.ipv4_can_send |= probe_report.ipv4_can_send; +1578 report.ipv6_can_send |= probe_report.ipv6_can_send; +1579 report.icmpv4 = report +1580 .icmpv4 +1581 .map(|val| val || probe_report.icmpv4.unwrap_or_default()) +1582 .or(probe_report.icmpv4); +1583 report.icmpv6 = report +1584 .icmpv6 +1585 .map(|val| val || probe_report.icmpv6.unwrap_or_default()) +1586 .or(probe_report.icmpv6); +1587} +1588 +1589/// Resolves to pending if the inner is `None`. +1590#[derive(Debug)] +1591pub(crate) struct MaybeFuture<T> { +1592 /// Future to be polled. +1593 pub inner: Option<T>, +1594} +1595 +1596// NOTE: explicit implementation to bypass derive unnecessary bounds +1597impl<T> Default for MaybeFuture<T> { +1598 fn default() -> Self { +1599 MaybeFuture { inner: None } +1600 } +1601} +1602 +1603impl<T: Future + Unpin> Future for MaybeFuture<T> { +1604 type Output = T::Output; +1605 +1606 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { +1607 match self.inner { +1608 Some(ref mut t) => Pin::new(t).poll(cx), +1609 None => Poll::Pending, +1610 } +1611 } +1612} +1613 +1614#[cfg(test)] +1615mod tests { +1616 use std::net::{Ipv4Addr, Ipv6Addr}; +1617 +1618 use n0_snafu::{Result, ResultExt}; +1619 use tracing_test::traced_test; +1620 +1621 use super::{super::test_utils, *}; +1622 use crate::net_report::dns; +1623 +1624 #[tokio::test] +1625 #[traced_test] +1626 async fn test_update_report_stun_working() { +1627 let (_server_a, relay_a) = test_utils::relay().await; +1628 let (_server_b, relay_b) = test_utils::relay().await; +1629 +1630 let mut report = Report::default(); +1631 let relay_a = Arc::new(relay_a); +1632 let relay_b = Arc::new(relay_b); +1633 +1634 // A STUN IPv4 probe from the the first relay server. +1635 let probe_report_a = ProbeReport { +1636 ipv4_can_send: true, +1637 ipv6_can_send: false, +1638 icmpv4: None, +1639 icmpv6: None, +1640 latency: Some(Duration::from_millis(5)), +1641 probe: Probe::StunIpv4 { +1642 delay: Duration::ZERO, +1643 node: relay_a.clone(), +1644 }, +1645 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1646 }; +1647 update_report(&mut report, probe_report_a.clone()); +1648 +1649 assert!(report.udp); +1650 assert_eq!( +1651 report.relay_latency.get(&relay_a.url).unwrap(), +1652 Duration::from_millis(5) +1653 ); +1654 assert_eq!( +1655 report.relay_v4_latency.get(&relay_a.url).unwrap(), +1656 Duration::from_millis(5) +1657 ); +1658 assert!(report.ipv4_can_send); +1659 assert!(!report.ipv6_can_send); +1660 +1661 // A second STUN IPv4 probe, same external IP detected but slower. +1662 let probe_report_b = ProbeReport { +1663 latency: Some(Duration::from_millis(8)), +1664 probe: Probe::StunIpv4 { +1665 delay: Duration::ZERO, +1666 node: relay_b.clone(), +1667 }, +1668 ..probe_report_a +1669 }; +1670 update_report(&mut report, probe_report_b); +1671 +1672 assert!(report.udp); +1673 assert_eq!( +1674 report.relay_latency.get(&relay_a.url).unwrap(), +1675 Duration::from_millis(5) +1676 ); +1677 assert_eq!( +1678 report.relay_v4_latency.get(&relay_a.url).unwrap(), +1679 Duration::from_millis(5) +1680 ); +1681 assert!(report.ipv4_can_send); +1682 assert!(!report.ipv6_can_send); +1683 +1684 // A STUN IPv6 probe, this one is faster. +1685 let probe_report_a_ipv6 = ProbeReport { +1686 ipv4_can_send: false, +1687 ipv6_can_send: true, +1688 icmpv4: None, +1689 icmpv6: None, +1690 latency: Some(Duration::from_millis(4)), +1691 probe: Probe::StunIpv6 { +1692 delay: Duration::ZERO, +1693 node: relay_a.clone(), +1694 }, +1695 addr: Some((Ipv6Addr::new(2001, 0xdb8, 0, 0, 0, 0, 0, 1), 1234).into()), +1696 }; +1697 update_report(&mut report, probe_report_a_ipv6); +1698 +1699 assert!(report.udp); +1700 assert_eq!( +1701 report.relay_latency.get(&relay_a.url).unwrap(), +1702 Duration::from_millis(4) +1703 ); +1704 assert_eq!( +1705 report.relay_v6_latency.get(&relay_a.url).unwrap(), +1706 Duration::from_millis(4) +1707 ); +1708 assert!(report.ipv4_can_send); +1709 assert!(report.ipv6_can_send); +1710 } +1711 +1712 #[tokio::test] +1713 #[traced_test] +1714 async fn test_update_report_icmp() { +1715 let (_server_a, relay_a) = test_utils::relay().await; +1716 let (_server_b, relay_b) = test_utils::relay().await; +1717 let relay_a = Arc::new(relay_a); +1718 let relay_b = Arc::new(relay_b); +1719 +1720 let mut report = Report::default(); 1721 -1722 let mut report = Report::default(); -1723 -1724 // An ICMPv4 probe from the EU relay server. -1725 let probe_report_eu = ProbeReport { -1726 ipv4_can_send: true, -1727 ipv6_can_send: false, -1728 icmpv4: Some(true), -1729 icmpv6: None, -1730 latency: Some(Duration::from_millis(5)), -1731 probe: Probe::IcmpV4 { -1732 delay: Duration::ZERO, -1733 node: relay_a.clone(), -1734 }, -1735 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1736 }; -1737 update_report(&mut report, probe_report_eu.clone()); -1738 -1739 assert!(!report.udp); -1740 assert!(report.ipv4_can_send); -1741 assert_eq!(report.icmpv4, Some(true)); -1742 -1743 // A second ICMPv4 probe which did not work. -1744 let probe_report_na = ProbeReport { -1745 ipv4_can_send: false, -1746 ipv6_can_send: false, -1747 icmpv4: Some(false), -1748 icmpv6: None, -1749 latency: None, -1750 probe: Probe::IcmpV4 { -1751 delay: Duration::ZERO, -1752 node: relay_b.clone(), -1753 }, -1754 addr: None, -1755 }; -1756 update_report(&mut report, probe_report_na); +1722 // An ICMPv4 probe from the EU relay server. +1723 let probe_report_eu = ProbeReport { +1724 ipv4_can_send: true, +1725 ipv6_can_send: false, +1726 icmpv4: Some(true), +1727 icmpv6: None, +1728 latency: Some(Duration::from_millis(5)), +1729 probe: Probe::IcmpV4 { +1730 delay: Duration::ZERO, +1731 node: relay_a.clone(), +1732 }, +1733 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1734 }; +1735 update_report(&mut report, probe_report_eu.clone()); +1736 +1737 assert!(!report.udp); +1738 assert!(report.ipv4_can_send); +1739 assert_eq!(report.icmpv4, Some(true)); +1740 +1741 // A second ICMPv4 probe which did not work. +1742 let probe_report_na = ProbeReport { +1743 ipv4_can_send: false, +1744 ipv6_can_send: false, +1745 icmpv4: Some(false), +1746 icmpv6: None, +1747 latency: None, +1748 probe: Probe::IcmpV4 { +1749 delay: Duration::ZERO, +1750 node: relay_b.clone(), +1751 }, +1752 addr: None, +1753 }; +1754 update_report(&mut report, probe_report_na); +1755 +1756 assert_eq!(report.icmpv4, Some(true)); 1757 -1758 assert_eq!(report.icmpv4, Some(true)); -1759 -1760 // Behold, a STUN probe arrives! -1761 let probe_report_eu_stun = ProbeReport { -1762 ipv4_can_send: true, -1763 ipv6_can_send: false, -1764 icmpv4: None, -1765 icmpv6: None, -1766 latency: Some(Duration::from_millis(5)), -1767 probe: Probe::StunIpv4 { -1768 delay: Duration::ZERO, -1769 node: relay_a.clone(), -1770 }, -1771 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1772 }; -1773 update_report(&mut report, probe_report_eu_stun); -1774 -1775 assert!(report.udp); -1776 assert_eq!(report.icmpv4, Some(true)); -1777 } -1778 -1779 // # ICMP permissions on Linux +1758 // Behold, a STUN probe arrives! +1759 let probe_report_eu_stun = ProbeReport { +1760 ipv4_can_send: true, +1761 ipv6_can_send: false, +1762 icmpv4: None, +1763 icmpv6: None, +1764 latency: Some(Duration::from_millis(5)), +1765 probe: Probe::StunIpv4 { +1766 delay: Duration::ZERO, +1767 node: relay_a.clone(), +1768 }, +1769 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1770 }; +1771 update_report(&mut report, probe_report_eu_stun); +1772 +1773 assert!(report.udp); +1774 assert_eq!(report.icmpv4, Some(true)); +1775 } +1776 +1777 // # ICMP permissions on Linux +1778 // +1779 // ## Using capabilities: CAP_NET_RAW 1780 // -1781 // ## Using capabilities: CAP_NET_RAW -1782 // -1783 // To run ICMP tests on Linux you need CAP_NET_RAW capabilities. When running tests -1784 // this means you first need to build the binary, set the capabilities and finally run -1785 // the tests. +1781 // To run ICMP tests on Linux you need CAP_NET_RAW capabilities. When running tests +1782 // this means you first need to build the binary, set the capabilities and finally run +1783 // the tests. +1784 // +1785 // Build the test binary: 1786 // -1787 // Build the test binary: +1787 // cargo nextest run -p iroh net_report::reportgen::tests --no-run 1788 // -1789 // cargo nextest run -p iroh net_report::reportgen::tests --no-run +1789 // Find out the test binary location: 1790 // -1791 // Find out the test binary location: -1792 // -1793 // cargo nextest list --message-format json -p iroh net_report::reportgen::tests \ -1794 // | jq '."rust-suites"."iroh"."binary-path"' | tr -d \" -1795 // -1796 // Set the CAP_NET_RAW permission, note that nextest runs each test in a child process -1797 // so the capabilities need to be inherited: +1791 // cargo nextest list --message-format json -p iroh net_report::reportgen::tests \ +1792 // | jq '."rust-suites"."iroh"."binary-path"' | tr -d \" +1793 // +1794 // Set the CAP_NET_RAW permission, note that nextest runs each test in a child process +1795 // so the capabilities need to be inherited: +1796 // +1797 // sudo setcap CAP_NET_RAW=eip target/debug/deps/iroh-abc123 1798 // -1799 // sudo setcap CAP_NET_RAW=eip target/debug/deps/iroh-abc123 +1799 // Finally run the test: 1800 // -1801 // Finally run the test: +1801 // cargo nextest run -p iroh net_report::reportgen::tests 1802 // -1803 // cargo nextest run -p iroh net_report::reportgen::tests +1803 // This allows the pinger to create a SOCK_RAW socket for IPPROTO_ICMP. 1804 // -1805 // This allows the pinger to create a SOCK_RAW socket for IPPROTO_ICMP. -1806 // +1805 // +1806 // ## Using sysctl 1807 // -1808 // ## Using sysctl -1809 // -1810 // Now you know the hard way, you can also get this permission a little easier, but -1811 // slightly less secure, by allowing any process running with your group ID to create a -1812 // SOCK_DGRAM for IPPROTO_ICMP. +1808 // Now you know the hard way, you can also get this permission a little easier, but +1809 // slightly less secure, by allowing any process running with your group ID to create a +1810 // SOCK_DGRAM for IPPROTO_ICMP. +1811 // +1812 // First find out your group ID: 1813 // -1814 // First find out your group ID: +1814 // id --group 1815 // -1816 // id --group +1816 // Then allow this group to send pings. Note that this is an inclusive range: 1817 // -1818 // Then allow this group to send pings. Note that this is an inclusive range: +1818 // sudo sysctl net.ipv4.ping_group_range="1234 1234" 1819 // -1820 // sudo sysctl net.ipv4.ping_group_range="1234 1234" -1821 // -1822 // Note that this does not survive a reboot usually, commonly you need to edit -1823 // /etc/sysctl.conf or /etc/sysctl.d/* to persist this across reboots. -1824 // -1825 // TODO: Not sure what about IPv6 pings using sysctl. -1826 #[tokio::test] -1827 #[traced_test] -1828 async fn test_icmpk_probe() { -1829 let pinger = Pinger::new(); -1830 let (server, node) = test_utils::relay().await; -1831 let addr = server.stun_addr().expect("test relay serves stun"); -1832 let probe = Probe::IcmpV4 { -1833 delay: Duration::from_secs(0), -1834 node: Arc::new(node), -1835 }; -1836 -1837 // A single ICMP packet might get lost. Try several and take the first. -1838 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); -1839 let mut tasks = JoinSet::new(); -1840 for i in 0..8 { -1841 let probe = probe.clone(); -1842 let pinger = pinger.clone(); -1843 let tx = tx.clone(); -1844 tasks.spawn(async move { -1845 time::sleep(Duration::from_millis(i * 100)).await; -1846 let res = run_icmp_probe(probe, addr, pinger).await; -1847 tx.send(res).ok(); -1848 }); -1849 } -1850 let mut last_err = None; -1851 while let Some(res) = rx.recv().await { -1852 match res { -1853 Ok(report) => { -1854 dbg!(&report); -1855 assert_eq!(report.icmpv4, Some(true)); -1856 assert!( -1857 report.latency.expect("should have a latency") > Duration::from_secs(0) -1858 ); -1859 break; -1860 } -1861 Err(ProbeErrorWithProbe::Error(err, _probe)) => { -1862 last_err = Some(err); -1863 } -1864 Err(ProbeErrorWithProbe::AbortSet(_err, _probe)) => { -1865 // We don't have permission, too bad. -1866 // panic!("no ping permission: {err:#}"); -1867 break; -1868 } -1869 } -1870 } -1871 if let Some(err) = last_err { -1872 panic!("Ping error: {err:#}"); -1873 } -1874 } -1875 -1876 #[tokio::test] -1877 async fn test_measure_https_latency() -> Result { -1878 let (server, relay) = test_utils::relay().await; -1879 let dns_resolver = dns::tests::resolver(); -1880 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); -1881 let (latency, ip) = -1882 measure_https_latency(&dns_resolver, &relay, server.certificates()).await?; +1820 // Note that this does not survive a reboot usually, commonly you need to edit +1821 // /etc/sysctl.conf or /etc/sysctl.d/* to persist this across reboots. +1822 // +1823 // TODO: Not sure what about IPv6 pings using sysctl. +1824 #[tokio::test] +1825 #[traced_test] +1826 async fn test_icmpk_probe() { +1827 let pinger = Pinger::new(); +1828 let (server, node) = test_utils::relay().await; +1829 let addr = server.stun_addr().expect("test relay serves stun"); +1830 let probe = Probe::IcmpV4 { +1831 delay: Duration::from_secs(0), +1832 node: Arc::new(node), +1833 }; +1834 +1835 // A single ICMP packet might get lost. Try several and take the first. +1836 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); +1837 let mut tasks = JoinSet::new(); +1838 for i in 0..8 { +1839 let probe = probe.clone(); +1840 let pinger = pinger.clone(); +1841 let tx = tx.clone(); +1842 tasks.spawn(async move { +1843 time::sleep(Duration::from_millis(i * 100)).await; +1844 let res = run_icmp_probe(probe, addr, pinger).await; +1845 tx.send(res).ok(); +1846 }); +1847 } +1848 let mut last_err = None; +1849 while let Some(res) = rx.recv().await { +1850 match res { +1851 Ok(report) => { +1852 dbg!(&report); +1853 assert_eq!(report.icmpv4, Some(true)); +1854 assert!( +1855 report.latency.expect("should have a latency") > Duration::from_secs(0) +1856 ); +1857 break; +1858 } +1859 Err(ProbeErrorWithProbe::Error(err, _probe)) => { +1860 last_err = Some(err); +1861 } +1862 Err(ProbeErrorWithProbe::AbortSet(_err, _probe)) => { +1863 // We don't have permission, too bad. +1864 // panic!("no ping permission: {err:#}"); +1865 break; +1866 } +1867 } +1868 } +1869 if let Some(err) = last_err { +1870 panic!("Ping error: {err:#}"); +1871 } +1872 } +1873 +1874 #[tokio::test] +1875 async fn test_measure_https_latency() -> Result { +1876 let (server, relay) = test_utils::relay().await; +1877 let dns_resolver = dns::tests::resolver(); +1878 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); +1879 let (latency, ip) = +1880 measure_https_latency(&dns_resolver, &relay, server.certificates()).await?; +1881 +1882 assert!(latency > Duration::ZERO); 1883 -1884 assert!(latency > Duration::ZERO); -1885 -1886 let relay_url_ip = relay -1887 .url -1888 .host_str() -1889 .unwrap() -1890 .parse::<std::net::IpAddr>() -1891 .e()?; -1892 assert_eq!(ip, relay_url_ip); -1893 Ok(()) -1894 } -1895 -1896 #[tokio::test] -1897 #[traced_test] -1898 async fn test_quic_probe() -> Result { -1899 let (server, relay) = test_utils::relay().await; -1900 let relay = Arc::new(relay); -1901 let client_config = iroh_relay::client::make_dangerous_client_config(); -1902 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; -1903 let client_addr = ep.local_addr().e()?; -1904 let quic_addr_disc = QuicConfig { -1905 ep: ep.clone(), -1906 client_config, -1907 ipv4: true, -1908 ipv6: true, -1909 }; -1910 let url = relay.url.clone(); -1911 let port = server.quic_addr().unwrap().port(); -1912 let probe = Probe::QuicIpv4 { -1913 delay: Duration::from_secs(0), -1914 node: relay, -1915 }; -1916 let probe = match run_quic_probe( -1917 quic_addr_disc, -1918 url, -1919 (Ipv4Addr::LOCALHOST, port).into(), -1920 probe, -1921 None, -1922 ) -1923 .await -1924 { -1925 Ok(probe) => probe, -1926 Err(e) => match e { -1927 ProbeErrorWithProbe::AbortSet(err, _) | ProbeErrorWithProbe::Error(err, _) => { -1928 return Err(err.into()); -1929 } -1930 }, -1931 }; -1932 assert!(probe.ipv4_can_send); -1933 assert_eq!(probe.addr.unwrap(), client_addr); -1934 ep.wait_idle().await; -1935 server.shutdown().await?; -1936 Ok(()) -1937 } -1938}

\ No newline at end of file +1884 let relay_url_ip = relay +1885 .url +1886 .host_str() +1887 .unwrap() +1888 .parse::<std::net::IpAddr>() +1889 .e()?; +1890 assert_eq!(ip, relay_url_ip); +1891 Ok(()) +1892 } +1893 +1894 #[tokio::test] +1895 #[traced_test] +1896 async fn test_quic_probe() -> Result { +1897 let (server, relay) = test_utils::relay().await; +1898 let relay = Arc::new(relay); +1899 let client_config = iroh_relay::client::make_dangerous_client_config(); +1900 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; +1901 let client_addr = ep.local_addr().e()?; +1902 let quic_addr_disc = QuicConfig { +1903 ep: ep.clone(), +1904 client_config, +1905 ipv4: true, +1906 ipv6: true, +1907 }; +1908 let url = relay.url.clone(); +1909 let port = server.quic_addr().unwrap().port(); +1910 let probe = Probe::QuicIpv4 { +1911 delay: Duration::from_secs(0), +1912 node: relay, +1913 }; +1914 let probe = match run_quic_probe( +1915 quic_addr_disc, +1916 url, +1917 (Ipv4Addr::LOCALHOST, port).into(), +1918 probe, +1919 None, +1920 ) +1921 .await +1922 { +1923 Ok(probe) => probe, +1924 Err(e) => match e { +1925 ProbeErrorWithProbe::AbortSet(err, _) | ProbeErrorWithProbe::Error(err, _) => { +1926 return Err(err.into()); +1927 } +1928 }, +1929 }; +1930 assert!(probe.ipv4_can_send); +1931 assert_eq!(probe.addr.unwrap(), client_addr); +1932 ep.wait_idle().await; +1933 server.shutdown().await?; +1934 Ok(()) +1935 } +1936} \ No newline at end of file