From 82fb65a57dee33445b61d2470c9390d80ad08f50 Mon Sep 17 00:00:00 2001 From: ssrlive <30760636+ssrlive@users.noreply.github.com> Date: Mon, 17 Nov 2025 19:01:35 +0800 Subject: [PATCH] Optimize memory allocation logic when constructing packet buffer --- src/lib.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 7207a6b..a1d6e77 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,10 @@ const TUN_PROTO_IP6: [u8; 2] = [0x00, 0x0A]; #[cfg(any(target_os = "macos", target_os = "ios"))] const TUN_PROTO_IP4: [u8; 2] = [0x00, 0x02]; +/// Minimum MTU required for IPv6 (per RFC 8200 §5: MTU ≥ 1280). +/// Also satisfies IPv4 minimum MTU (RFC 791 §3.1: 68 bytes). +const MIN_MTU: u16 = 1280; + /// Configuration for the IP stack. /// /// This structure holds configuration parameters that control the behavior of the IP stack, @@ -61,7 +65,7 @@ const TUN_PROTO_IP4: [u8; 2] = [0x00, 0x02]; #[non_exhaustive] pub struct IpStackConfig { /// Maximum Transmission Unit (MTU) size in bytes. - /// Default is `u16::MAX` (65535). + /// Default is `MIN_MTU` (1280). pub mtu: u16, /// Whether to include packet information headers (Unix platforms only). /// Default is `false`. @@ -76,7 +80,7 @@ pub struct IpStackConfig { impl Default for IpStackConfig { fn default() -> Self { IpStackConfig { - mtu: u16::MAX, + mtu: MIN_MTU, packet_information: false, tcp_config: Arc::new(TcpConfig::default()), udp_timeout: Duration::from_secs(30), @@ -300,9 +304,16 @@ fn run( let (session_remove_tx, mut session_remove_rx) = mpsc::unbounded_channel::(); let pi = config.packet_information; let offset = if pi && cfg!(unix) { 4 } else { 0 }; - let mut buffer = vec![0_u8; u16::MAX as usize + offset]; + let mut buffer = vec![0_u8; config.mtu as usize + offset]; let (up_pkt_sender, mut up_pkt_receiver) = mpsc::unbounded_channel::(); + if config.mtu < MIN_MTU { + log::warn!( + "the MTU in the configuration ({}) below the MIN_MTU (1280) can cause problems.", + config.mtu + ); + } + tokio::spawn(async move { loop { select! {