Skip to main content

winping/
buffer.rs

1use core::ffi::c_void;
2use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3
4#[cfg(target_pointer_width = "64")]
5use windows_sys::Win32::NetworkManagement::IpHelper::ICMP_ECHO_REPLY32;
6use windows_sys::Win32::NetworkManagement::IpHelper::{ICMP_ECHO_REPLY, ICMPV6_ECHO_REPLY_LH as ICMPV6_ECHO_REPLY};
7
8use crate::util::{rust_ipv4, rust_ipv6};
9
10// Chunk is a lump of u8, apropriately sized and aligned
11// for the necessary ICMP(V6)_ECHO_REPLY(32) types on
12// 32 and 64 bit platforms.
13#[cfg(target_pointer_width = "64")]
14#[derive(Copy, Clone, Debug, Eq, PartialEq)]
15#[repr(C, align(8))]
16struct Chunk([u8; 8]);
17#[cfg(target_pointer_width = "32")]
18#[derive(Copy, Clone, Debug, Eq, PartialEq)]
19#[repr(C, align(4))]
20struct Chunk([u8; 4]);
21const CHUNK_SIZE: usize = size_of::<Chunk>();
22const _: () = {
23    assert!(CHUNK_SIZE == align_of::<Chunk>());
24    assert!(CHUNK_SIZE == align_of::<ICMP_ECHO_REPLY>());
25    assert!(CHUNK_SIZE >= align_of::<ICMPV6_ECHO_REPLY>());
26    #[cfg(target_pointer_width = "64")]
27    assert!(CHUNK_SIZE >= align_of::<ICMP_ECHO_REPLY32>());
28};
29
30/// A buffer for request and reply data.
31#[derive(Clone, Debug)]
32#[expect(
33    clippy::partial_pub_fields,
34    reason = "request_data is deliberately public; the reply side is an implementation detail"
35)]
36pub struct Buffer {
37    /// The payload sent with each request. Push bytes here before sending.
38    pub request_data: Vec<u8>,
39    reply_data: Vec<Chunk>,
40    state: ReplyState,
41}
42
43const _: () = {
44    const fn assert_send_sync<T: Send + Sync>() {}
45    assert_send_sync::<Buffer>();
46};
47
48#[derive(Copy, Clone, Eq, PartialEq, Debug)]
49enum ReplyState {
50    Empty,
51    Filled4 { data_len: usize },
52    Filled6 { data_len: usize },
53}
54
55impl Default for Buffer {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl Buffer {
62    /// Creates a new, empty buffer with no request data.
63    pub const fn new() -> Self {
64        Self {
65            request_data: Vec::new(),
66            reply_data: Vec::new(),
67            state: ReplyState::Empty,
68        }
69    }
70
71    /// Creates a new buffer with the provided request data.
72    pub const fn with_data(request_data: Vec<u8>) -> Self {
73        Self {
74            request_data,
75            reply_data: Vec::new(),
76            state: ReplyState::Empty,
77        }
78    }
79
80    pub(crate) fn init_for_send(&mut self) {
81        // Reply buffer must be large enough for:
82        // 1. Any possible ICMP_ECHO(V6)_REPLY(32) type +
83        // 2. An ICMP error (8 bytes) +
84        // 3. An IO_STATUS_BLOCK (up to 16 bytes) +
85        // 4. The length of the request data
86        #[cfg(target_pointer_width = "64")]
87        const MIN_ECHO_REPLY_SIZE: usize = {
88            assert!(size_of::<ICMPV6_ECHO_REPLY>() <= size_of::<ICMP_ECHO_REPLY>());
89            assert!(size_of::<ICMP_ECHO_REPLY32>() <= size_of::<ICMP_ECHO_REPLY>());
90            size_of::<ICMP_ECHO_REPLY>()
91        };
92
93        #[cfg(target_pointer_width = "32")]
94        const MIN_ECHO_REPLY_SIZE: usize = {
95            assert!(size_of::<ICMP_ECHO_REPLY>() <= size_of::<ICMPV6_ECHO_REPLY>());
96            size_of::<ICMPV6_ECHO_REPLY>()
97        };
98
99        const BASE_SIZE: usize = MIN_ECHO_REPLY_SIZE + 24;
100        let size = BASE_SIZE + self.request_data.len();
101
102        let chunks = size / CHUNK_SIZE
103            + match size % CHUNK_SIZE {
104                0 => 0,
105                _ => 1,
106            };
107        self.reply_data.resize(chunks, Chunk([0; CHUNK_SIZE]));
108        self.state = ReplyState::Empty;
109    }
110
111    pub(crate) fn request_data_ptr(&mut self) -> *mut c_void {
112        self.request_data.as_mut_ptr().cast::<c_void>()
113    }
114
115    /// Saturates rather than truncating: the ICMP APIs cap request size at
116    /// u16::MAX anyway, and a truncated length would misdescribe the buffer.
117    pub(crate) fn request_data_len(&self) -> u16 {
118        u16::try_from(self.request_data.len()).unwrap_or(u16::MAX)
119    }
120
121    pub(crate) fn reply_data_ptr(&mut self) -> *mut c_void {
122        self.reply_data.as_mut_ptr().cast::<c_void>()
123    }
124
125    fn reply_data_ptr_const(&self) -> *const c_void {
126        self.reply_data.as_ptr().cast::<c_void>()
127    }
128
129    /// Size of the reply buffer in bytes, for indexing and length checks.
130    fn reply_len_bytes(&self) -> usize {
131        self.reply_data.len() * CHUNK_SIZE
132    }
133
134    /// The same length, in the u32 the ICMP APIs take.
135    pub(crate) fn reply_data_len(&self) -> u32 {
136        u32::try_from(self.reply_len_bytes()).unwrap_or(u32::MAX)
137    }
138
139    pub(crate) fn as_echo_reply(&self) -> Option<&ICMP_ECHO_REPLY> {
140        if self.reply_len_bytes() >= size_of::<ICMP_ECHO_REPLY>() {
141            // SAFETY: the length check above guarantees enough initialized
142            // bytes, Chunk's repr guarantees sufficient alignment, and every
143            // field of the reply types is Copy.
144            Some(unsafe { &*self.reply_data_ptr_const().cast() })
145        } else {
146            None
147        }
148    }
149
150    #[cfg(all(target_pointer_width = "64", feature = "async"))]
151    pub(crate) fn as_echo_reply32(&self) -> Option<&ICMP_ECHO_REPLY32> {
152        if self.reply_len_bytes() >= size_of::<ICMP_ECHO_REPLY32>() {
153            // SAFETY: as in as_echo_reply; IcmpParseReplies has rewritten the
154            // buffer to the 32-bit layout by the time this is called.
155            Some(unsafe { &*self.reply_data_ptr_const().cast() })
156        } else {
157            None
158        }
159    }
160
161    pub(crate) fn as_echo_reply6(&self) -> Option<&ICMPV6_ECHO_REPLY> {
162        if self.reply_len_bytes() >= size_of::<ICMPV6_ECHO_REPLY>() {
163            // SAFETY: the length check above guarantees enough initialized
164            // bytes, Chunk's repr guarantees sufficient alignment, and every
165            // field of the reply types is Copy.
166            Some(unsafe { &*self.reply_data_ptr_const().cast() })
167        } else {
168            None
169        }
170    }
171
172    pub(crate) fn set_filled4(&mut self) {
173        let data_len = self.as_echo_reply().map_or(0, |reply| usize::from(reply.DataSize));
174        self.state = ReplyState::Filled4 { data_len }
175    }
176
177    pub(crate) fn set_filled6(&mut self) {
178        // RFC 4443, section 4.2, reply data MUST be same as request data
179        let data_len = self.request_data.len();
180        self.state = ReplyState::Filled6 { data_len }
181    }
182
183    /// The reply data from the last ping this buffer was used in. Empty if no
184    /// request was sent with this buffer, or if there was no reply.
185    pub fn reply_data(&self) -> &[u8] {
186        let (len, offset) = match self.state {
187            ReplyState::Empty => (0, 0),
188            ReplyState::Filled4 { data_len } => {
189                // No need to treat ICMP_ECHO_REPLY32 separately.
190                // IcmpParseReplies does not move the reply data when
191                // converting ICMP_ECHO_REPLY to ICMP_ECHO_REPLY32,
192                // so offset is still size of ICMP_ECHO_REPLY.
193                (data_len, size_of::<ICMP_ECHO_REPLY>())
194            }
195            ReplyState::Filled6 { data_len } => (data_len, size_of::<ICMPV6_ECHO_REPLY>()),
196        };
197
198        if len == 0 || offset + len > self.reply_len_bytes() {
199            &[]
200        } else {
201            // SAFETY: offset + len is within the reply buffer, checked above.
202            let start = unsafe { self.reply_data_ptr_const().cast::<u8>().add(offset) };
203            // SAFETY: start..start + len lies inside a single live allocation
204            // that the ICMP API has written, and u8 has no invalid values.
205            unsafe { core::slice::from_raw_parts(start, len) }
206        }
207    }
208
209    /// The responding Ipv4Addr from the last request, or None if that request was
210    /// v6, the buffer wasn't used in a request, or there was no reply.
211    pub fn responding_ipv4(&self) -> Option<Ipv4Addr> {
212        match self.state {
213            ReplyState::Filled4 { .. } => self.as_echo_reply().map(|reply| rust_ipv4(reply.Address)),
214            _ => None,
215        }
216    }
217
218    /// The responding Ipv6Addr from the last request, or None if that request was
219    /// v4, the buffer wasn't used in a request, or there was no reply.
220    pub fn responding_ipv6(&self) -> Option<Ipv6Addr> {
221        match self.state {
222            ReplyState::Filled6 { .. } => self.as_echo_reply6().map(|reply| rust_ipv6(reply.Address.sin6_addr)),
223            _ => None,
224        }
225    }
226
227    /// The responding IpAddr from the last request, or None if the buffer wasn't
228    /// used in a request or there was no reply.
229    pub fn responding_ip(&self) -> Option<IpAddr> {
230        self.responding_ipv4()
231            .map(IpAddr::V4)
232            .or_else(|| self.responding_ipv6().map(IpAddr::V6))
233    }
234}