Skip to main content

winping/
pinger.rs

1use core::fmt::{self, Debug, Display, Formatter};
2use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
3use core::ptr;
4use std::sync::Arc;
5
6use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
7use windows_sys::Win32::NetworkManagement::IpHelper::{
8    IP_BUF_TOO_SMALL, IP_FLAG_DF, IP_OPTION_INFORMATION, IP_SUCCESS, Icmp6CreateFile, Icmp6SendEcho2, IcmpCloseHandle,
9    IcmpCreateFile, IcmpSendEcho, IcmpSendEcho2Ex,
10};
11use windows_sys::Win32::Networking::WinSock::{AF_INET6, SOCKADDR_IN6};
12
13use crate::util::{windows_ipv4, windows_ipv6};
14use crate::{Buffer, Error};
15
16struct Handles {
17    v4: HANDLE,
18    v6: HANDLE,
19}
20
21// SAFETY: HANDLE is a raw pointer, which is why these are not derived, but ICMP
22// handles from Icmp(6)CreateFile are not thread-affine - Windows places no
23// apartment or owning-thread requirement on them. The handles are set once in
24// Pinger::new and never mutated afterwards; every send takes &self and only
25// passes the handle to the API by value, and IcmpCloseHandle runs exactly once
26// when the last Arc<Handles> is dropped. AsyncPinger already relies on the same
27// property, sharing its handles between the caller and the worker thread.
28unsafe impl Send for Handles {}
29// SAFETY: see the comment on the Send impl above.
30unsafe impl Sync for Handles {}
31
32/// A pair of IP (v4 or v6) addresses, source and destination.
33#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
34pub enum IpPair {
35    /// A pair of IPv4 addresses.
36    V4 {
37        /// The address to send from.
38        src: Ipv4Addr,
39        /// The address to send to.
40        dst: Ipv4Addr,
41    },
42
43    /// A pair of IPv6 addresses.
44    V6 {
45        /// The address to send from.
46        src: Ipv6Addr,
47        /// The address to send to.
48        dst: Ipv6Addr,
49    },
50}
51
52/// A pinger that blocks when sending.
53///
54/// This is cheap to clone - clones share the underlying ICMP handles - and is
55/// `Send` + `Sync`, so a single `Pinger` can be shared across threads. Note that
56/// each send needs its own [`Buffer`], as `send` takes it by `&mut`.
57#[derive(Clone)]
58pub struct Pinger {
59    handles: Arc<Handles>,
60    ttl: u8,
61    df: bool,
62    timeout: u32,
63}
64
65/// An error when creating a Pinger.
66pub enum CreateError {
67    /// The ICMPv4 handle could not be created.
68    NoV4(Pinger),
69    /// The ICMPv6 handle could not be created.
70    NoV6(Pinger),
71    /// Neither handle could be created.
72    None,
73}
74
75impl Debug for CreateError {
76    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77        write!(
78            f,
79            "{}",
80            match self {
81                CreateError::None => "failed to create ICMP V4 and V6 handles",
82                CreateError::NoV4(_) => "failed to create ICMP V4 handle",
83                CreateError::NoV6(_) => "failed to create ICMP V6 handle",
84            }
85        )
86    }
87}
88
89impl Display for CreateError {
90    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
91        Debug::fmt(self, f)
92    }
93}
94
95impl core::error::Error for CreateError {}
96
97impl Pinger {
98    /// Creates a new Pinger.
99    /// If one ICMP handle (v4 or v6) fails to initialize,
100    /// this will return the Pinger embedded in an error. The
101    /// Pinger is still usable in this state, but sending
102    /// on the failed version will return an Error.
103    /// If both v4 and v6 fail, the pinger is not embedded
104    /// in the error.
105    pub fn new() -> Result<Self, CreateError> {
106        // SAFETY: IcmpCreateFile has no preconditions; failure is reported
107        // via INVALID_HANDLE_VALUE, which is checked below.
108        let v4 = unsafe { IcmpCreateFile() };
109        // SAFETY: as above, for the v6 handle.
110        let v6 = unsafe { Icmp6CreateFile() };
111        let ret = Self {
112            handles: Arc::new(Handles { v4, v6 }),
113            ttl: 255,
114            df: false,
115            timeout: 2000,
116        };
117        match (v4, v6) {
118            (INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE) => Err(CreateError::None),
119            (INVALID_HANDLE_VALUE, _) => Err(CreateError::NoV6(ret)),
120            (_, INVALID_HANDLE_VALUE) => Err(CreateError::NoV4(ret)),
121            (_, _) => Ok(ret),
122        }
123    }
124
125    /// Creates a new Pinger, ignoring v6 failures. If you want to use
126    /// both v4 and v6, use new() instead.
127    pub fn new_v4() -> Option<Self> {
128        match Self::new() {
129            Ok(ret) | Err(CreateError::NoV6(ret)) => Some(ret),
130            _ => None,
131        }
132    }
133
134    /// Creates a new Pinger, ignoring v4 failures. If you want to use
135    /// both v4 and v6, use new() instead.
136    pub fn new_v6() -> Option<Self> {
137        match Self::new() {
138            Ok(ret) | Err(CreateError::NoV4(ret)) => Some(ret),
139            _ => None,
140        }
141    }
142
143    /// Sets the IP TTL for future requets.
144    pub fn set_ttl(&mut self, ttl: u8) {
145        self.ttl = ttl;
146    }
147
148    /// Gets the current IP TTL value.
149    pub fn ttl(&self) -> u8 {
150        self.ttl
151    }
152
153    /// Sets the IP Don't Fragment bit for future requests.
154    pub fn set_df(&mut self, df: bool) {
155        self.df = df;
156    }
157
158    /// Gets the current IP Don't Fragment bit.
159    pub fn df(&self) -> bool {
160        self.df
161    }
162
163    /// Sets the timeout, in milliseconds, for future requests.
164    pub fn set_timeout(&mut self, timeout: u32) {
165        self.timeout = timeout;
166    }
167
168    /// Gets the current timeout in milliseconds.
169    pub fn timeout(&self) -> u32 {
170        self.timeout
171    }
172
173    #[inline]
174    fn make_ip_opts(&self) -> IP_OPTION_INFORMATION {
175        // IP_OPTION_INFORMATION::Flags is a u8, but windows-sys types IP_FLAG_DF as u32.
176        #[expect(
177            clippy::as_conversions,
178            clippy::cast_possible_truncation,
179            reason = "IP_FLAG_DF is the constant 2"
180        )]
181        const DONT_FRAGMENT: u8 = IP_FLAG_DF as u8;
182        IP_OPTION_INFORMATION {
183            Ttl: self.ttl,
184            Flags: if self.df { DONT_FRAGMENT } else { 0 },
185            ..Default::default()
186        }
187    }
188
189    /// Send an ICMPv4 request to the destination address. On success, returns the round trip time in milliseconds.
190    pub fn send4(&self, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
191        buf.init_for_send();
192        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
193        // and every argument outlives this synchronous call.
194        let ret = unsafe {
195            IcmpSendEcho(
196                self.handles.v4,
197                windows_ipv4(dst),
198                buf.request_data_ptr(),
199                buf.request_data_len(),
200                &self.make_ip_opts(),
201                buf.reply_data_ptr(),
202                buf.reply_data_len(),
203                self.timeout,
204            )
205        };
206        finish_v4(ret, buf)
207    }
208
209    /// Sends an ICMPv4 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
210    pub fn send4_from(&self, src: Ipv4Addr, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
211        buf.init_for_send();
212        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
213        // and every argument outlives this synchronous call.
214        let ret = unsafe {
215            IcmpSendEcho2Ex(
216                self.handles.v4,
217                ptr::null_mut(), // Event
218                None,            // ApcRoutine
219                ptr::null(),     // ApcContext
220                windows_ipv4(src),
221                windows_ipv4(dst),
222                buf.request_data_ptr(),
223                buf.request_data_len(),
224                &self.make_ip_opts(),
225                buf.reply_data_ptr(),
226                buf.reply_data_len(),
227                self.timeout,
228            )
229        };
230        finish_v4(ret, buf)
231    }
232
233    /// Sends an ICMPv6 request to the destination address. On success, returns the round trip time in milliseconds.
234    pub fn send6(&self, dst: Ipv6Addr, buf: &mut Buffer) -> Result<u32, Error> {
235        let dst = SOCKADDR_IN6 {
236            sin6_family: AF_INET6,
237            sin6_addr: windows_ipv6(dst),
238            ..Default::default()
239        };
240        buf.init_for_send();
241
242        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
243        // and every argument outlives this synchronous call.
244        let ret = unsafe {
245            Icmp6SendEcho2(
246                self.handles.v6,
247                ptr::null_mut(), // Event
248                None,            // ApcRoutine
249                ptr::null(),     // ApcContext
250                &SOCKADDR_IN6::default(),
251                &dst,
252                buf.request_data_ptr(),
253                buf.request_data_len(),
254                &self.make_ip_opts(),
255                buf.reply_data_ptr(),
256                buf.reply_data_len(),
257                self.timeout,
258            )
259        };
260        finish_v6(ret, buf)
261    }
262
263    /// Sends an ICMPv6 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
264    pub fn send6_from(&self, src: Ipv6Addr, dst: Ipv6Addr, buf: &mut Buffer) -> Result<u32, Error> {
265        let dst = SOCKADDR_IN6 {
266            sin6_family: AF_INET6,
267            sin6_addr: windows_ipv6(dst),
268            ..Default::default()
269        };
270        let src = SOCKADDR_IN6 {
271            sin6_family: AF_INET6,
272            sin6_addr: windows_ipv6(src),
273            ..Default::default()
274        };
275        buf.init_for_send();
276
277        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
278        // and every argument outlives this synchronous call.
279        let ret = unsafe {
280            Icmp6SendEcho2(
281                self.handles.v6,
282                ptr::null_mut(), // Event
283                None,            // ApcRoutine
284                ptr::null(),     // ApcContext
285                &src,
286                &dst,
287                buf.request_data_ptr(),
288                buf.request_data_len(),
289                &self.make_ip_opts(),
290                buf.reply_data_ptr(),
291                buf.reply_data_len(),
292                self.timeout,
293            )
294        };
295        finish_v6(ret, buf)
296    }
297
298    /// Sends an ICMP request to the destination address. Supports both v4 and v6. On success, returns the round trip time in milliseconds.
299    pub fn send(&self, dst: IpAddr, buf: &mut Buffer) -> Result<u32, Error> {
300        match dst {
301            IpAddr::V4(ip) => self.send4(ip, buf),
302            IpAddr::V6(ip) => self.send6(ip, buf),
303        }
304    }
305
306    /// Sends an ICMP request from the source address to the destination address. Supports both v4 and v6. On success, returns the round trip time in milliseconds.
307    pub fn send_from(&mut self, src_dst_pair: IpPair, buf: &mut Buffer) -> Result<u32, Error> {
308        match src_dst_pair {
309            IpPair::V4 { src, dst } => self.send4_from(src, dst, buf),
310            IpPair::V6 { src, dst } => self.send6_from(src, dst, buf),
311        }
312    }
313}
314
315const _: () = {
316    const fn assert_send_sync<T: Send + Sync>() {}
317    assert_send_sync::<Pinger>();
318};
319
320/// Interprets the return of a blocking ICMPv4 send and records the reply state.
321fn finish_v4(ret: u32, buf: &mut Buffer) -> Result<u32, Error> {
322    if ret == 0 {
323        return Err(Error::from_lasterror());
324    }
325    // init_for_send always sizes for a full reply, so None is unreachable.
326    let Some(reply) = buf.as_echo_reply() else {
327        return Err(Error::from_iperror(IP_BUF_TOO_SMALL));
328    };
329    let (status, rtt) = (reply.Status, reply.RoundTripTime);
330    buf.set_filled4();
331    if status == IP_SUCCESS {
332        Ok(rtt)
333    } else {
334        Err(Error::from_iperror(status))
335    }
336}
337
338/// Interprets the return of a blocking ICMPv6 send and records the reply state.
339fn finish_v6(ret: u32, buf: &mut Buffer) -> Result<u32, Error> {
340    if ret == 0 {
341        return Err(Error::from_lasterror());
342    }
343    let Some(reply) = buf.as_echo_reply6() else {
344        return Err(Error::from_iperror(IP_BUF_TOO_SMALL));
345    };
346    let (status, rtt) = (reply.Status, reply.RoundTripTime);
347    buf.set_filled6();
348    if status == IP_SUCCESS {
349        Ok(rtt)
350    } else {
351        Err(Error::from_iperror(status))
352    }
353}
354
355impl Drop for Handles {
356    fn drop(&mut self) {
357        if self.v4 != INVALID_HANDLE_VALUE {
358            // SAFETY: v4 is a live handle from IcmpCreateFile, closed exactly
359            // once because Handles is owned by a single Arc.
360            let ret = unsafe { IcmpCloseHandle(self.v4) };
361            debug_assert_ne!(0, ret);
362        }
363        if self.v6 != INVALID_HANDLE_VALUE {
364            // SAFETY: as above, for the v6 handle.
365            let ret = unsafe { IcmpCloseHandle(self.v6) };
366            debug_assert_ne!(0, ret);
367        }
368    }
369}