Skip to content

Commit 74c7d1d

Browse files
committed
Refactor auto_mtu_detection
1 parent 12d23c3 commit 74c7d1d

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

talpid-wireguard/src/lib.rs

+8-7
Original file line numberDiff line numberDiff line change
@@ -999,7 +999,7 @@ async fn auto_mtu_detection(
999999
#[cfg(any(target_os = "macos", target_os = "linux"))] iface_name: String,
10001000
current_mtu: u16,
10011001
) -> Result<u16> {
1002-
use futures::{stream::FuturesOrdered, TryStreamExt};
1002+
use futures::{future, stream::FuturesUnordered, TryStreamExt};
10031003
use surge_ping::{Client, Config, PingIdentifier, PingSequence, SurgeError};
10041004
use talpid_tunnel::{ICMP_HEADER_SIZE, MIN_IPV4_MTU};
10051005
use tokio_stream::StreamExt;
@@ -1015,34 +1015,35 @@ async fn auto_mtu_detection(
10151015
let step_size = 20;
10161016

10171017
let linspace = mtu_spacing(MIN_IPV4_MTU, current_mtu, step_size);
1018+
let largest_payload = vec![0; current_mtu as usize];
10181019

1019-
let set: FuturesOrdered<_> = linspace
1020+
let ping_stream: FuturesUnordered<_> = linspace
10201021
.iter()
10211022
.enumerate()
10221023
.map(|(i, &mtu)| {
10231024
let client = client.clone();
1025+
let payload = &largest_payload[0..(mtu - IPV4_HEADER_SIZE - ICMP_HEADER_SIZE) as usize];
10241026
async move {
10251027
log::trace!("Sending ICMP ping of total size {mtu}");
1026-
let payload = vec![0; (mtu - IPV4_HEADER_SIZE - ICMP_HEADER_SIZE) as usize]; //? Can we avoid allocating here?
10271028
client
10281029
.pinger(IpAddr::V4(gateway), PingIdentifier(111)) //? Is a static identified ok, or should we randomize?
10291030
.await
10301031
.timeout(PING_TIMEOUT) // TODO: choose a good timeout
1031-
.ping(PingSequence(i as u16), &payload)
1032+
.ping(PingSequence(i as u16), payload)
10321033
.await
10331034
}
10341035
})
10351036
.collect();
10361037

1037-
let res = set
1038+
let res = ping_stream
10381039
.map(|res| match res {
10391040
// Map successful pings to packet size
10401041
Ok((packet, _rtt)) => {
10411042
let surge_ping::IcmpPacket::V4(packet) = packet else {
10421043
panic!("ICMP ping response was not of IPv4 type");
10431044
};
10441045
let size = packet.get_size() as u16 + IPV4_HEADER_SIZE;
1045-
log::debug!("Got ICMP ping response of total size {size}");
1046+
log::trace!("Got ICMP ping response of total size {size}");
10461047
debug_assert_eq!(size, linspace[packet.get_sequence().0 as usize]);
10471048
Ok(Some(size))
10481049
}
@@ -1054,7 +1055,7 @@ async fn auto_mtu_detection(
10541055
// Short circuit and return error on unexpected error types
10551056
Err(e) => Err(e),
10561057
})
1057-
.try_fold(None, |acc, x| async move { Ok(std::cmp::max(acc, x)) })
1058+
.try_fold(None, |acc, mtu| future::ready(Ok(acc.max(mtu))))
10581059
.await;
10591060
match res {
10601061
Ok(Some(verified_mtu)) => Ok(verified_mtu),

0 commit comments

Comments
 (0)