winping-rs 0.11.0

An easy-to-use ICMP Echo API for Windows programs without requiring elevated rights.
Documentation
use core::fmt::{self, Debug, Display, Formatter};
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use core::ptr;
use std::sync::Arc;

use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE};
use windows_sys::Win32::NetworkManagement::IpHelper::{
    IP_BUF_TOO_SMALL, IP_FLAG_DF, IP_OPTION_INFORMATION, IP_SUCCESS, Icmp6CreateFile, Icmp6SendEcho2, IcmpCloseHandle,
    IcmpCreateFile, IcmpSendEcho, IcmpSendEcho2Ex,
};
use windows_sys::Win32::Networking::WinSock::{AF_INET6, SOCKADDR_IN6};

use crate::util::{windows_ipv4, windows_ipv6};
use crate::{Buffer, Error};

struct Handles {
    v4: HANDLE,
    v6: HANDLE,
}

// SAFETY: HANDLE is a raw pointer, which is why these are not derived, but ICMP
// handles from Icmp(6)CreateFile are not thread-affine - Windows places no
// apartment or owning-thread requirement on them. The handles are set once in
// Pinger::new and never mutated afterwards; every send takes &self and only
// passes the handle to the API by value, and IcmpCloseHandle runs exactly once
// when the last Arc<Handles> is dropped. AsyncPinger already relies on the same
// property, sharing its handles between the caller and the worker thread.
unsafe impl Send for Handles {}
// SAFETY: see the comment on the Send impl above.
unsafe impl Sync for Handles {}

/// A pair of IP (v4 or v6) addresses, source and destination.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum IpPair {
    /// A pair of IPv4 addresses.
    V4 {
        /// The address to send from.
        src: Ipv4Addr,
        /// The address to send to.
        dst: Ipv4Addr,
    },

    /// A pair of IPv6 addresses.
    V6 {
        /// The address to send from.
        src: Ipv6Addr,
        /// The address to send to.
        dst: Ipv6Addr,
    },
}

/// A pinger that blocks when sending.
///
/// This is cheap to clone - clones share the underlying ICMP handles - and is
/// `Send` + `Sync`, so a single `Pinger` can be shared across threads. Note that
/// each send needs its own [`Buffer`], as `send` takes it by `&mut`.
#[derive(Clone)]
pub struct Pinger {
    handles: Arc<Handles>,
    ttl: u8,
    df: bool,
    timeout: u32,
}

/// An error when creating a Pinger.
pub enum CreateError {
    /// The ICMPv4 handle could not be created.
    NoV4(Pinger),
    /// The ICMPv6 handle could not be created.
    NoV6(Pinger),
    /// Neither handle could be created.
    None,
}

impl Debug for CreateError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                CreateError::None => "failed to create ICMP V4 and V6 handles",
                CreateError::NoV4(_) => "failed to create ICMP V4 handle",
                CreateError::NoV6(_) => "failed to create ICMP V6 handle",
            }
        )
    }
}

impl Display for CreateError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl core::error::Error for CreateError {}

impl Pinger {
    /// Creates a new Pinger.
    /// If one ICMP handle (v4 or v6) fails to initialize,
    /// this will return the Pinger embedded in an error. The
    /// Pinger is still usable in this state, but sending
    /// on the failed version will return an Error.
    /// If both v4 and v6 fail, the pinger is not embedded
    /// in the error.
    pub fn new() -> Result<Self, CreateError> {
        // SAFETY: IcmpCreateFile has no preconditions; failure is reported
        // via INVALID_HANDLE_VALUE, which is checked below.
        let v4 = unsafe { IcmpCreateFile() };
        // SAFETY: as above, for the v6 handle.
        let v6 = unsafe { Icmp6CreateFile() };
        let ret = Self {
            handles: Arc::new(Handles { v4, v6 }),
            ttl: 255,
            df: false,
            timeout: 2000,
        };
        match (v4, v6) {
            (INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE) => Err(CreateError::None),
            (INVALID_HANDLE_VALUE, _) => Err(CreateError::NoV6(ret)),
            (_, INVALID_HANDLE_VALUE) => Err(CreateError::NoV4(ret)),
            (_, _) => Ok(ret),
        }
    }

    /// Creates a new Pinger, ignoring v6 failures. If you want to use
    /// both v4 and v6, use new() instead.
    pub fn new_v4() -> Option<Self> {
        match Self::new() {
            Ok(ret) | Err(CreateError::NoV6(ret)) => Some(ret),
            _ => None,
        }
    }

    /// Creates a new Pinger, ignoring v4 failures. If you want to use
    /// both v4 and v6, use new() instead.
    pub fn new_v6() -> Option<Self> {
        match Self::new() {
            Ok(ret) | Err(CreateError::NoV4(ret)) => Some(ret),
            _ => None,
        }
    }

    /// Sets the IP TTL for future requets.
    pub fn set_ttl(&mut self, ttl: u8) {
        self.ttl = ttl;
    }

    /// Gets the current IP TTL value.
    pub fn ttl(&self) -> u8 {
        self.ttl
    }

    /// Sets the IP Don't Fragment bit for future requests.
    pub fn set_df(&mut self, df: bool) {
        self.df = df;
    }

    /// Gets the current IP Don't Fragment bit.
    pub fn df(&self) -> bool {
        self.df
    }

    /// Sets the timeout, in milliseconds, for future requests.
    pub fn set_timeout(&mut self, timeout: u32) {
        self.timeout = timeout;
    }

    /// Gets the current timeout in milliseconds.
    pub fn timeout(&self) -> u32 {
        self.timeout
    }

    #[inline]
    fn make_ip_opts(&self) -> IP_OPTION_INFORMATION {
        // IP_OPTION_INFORMATION::Flags is a u8, but windows-sys types IP_FLAG_DF as u32.
        #[expect(
            clippy::as_conversions,
            clippy::cast_possible_truncation,
            reason = "IP_FLAG_DF is the constant 2"
        )]
        const DONT_FRAGMENT: u8 = IP_FLAG_DF as u8;
        IP_OPTION_INFORMATION {
            Ttl: self.ttl,
            Flags: if self.df { DONT_FRAGMENT } else { 0 },
            ..Default::default()
        }
    }

    /// Send an ICMPv4 request to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send4(&self, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
        buf.init_for_send();
        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
        // and every argument outlives this synchronous call.
        let ret = unsafe {
            IcmpSendEcho(
                self.handles.v4,
                windows_ipv4(dst),
                buf.request_data_ptr(),
                buf.request_data_len(),
                &self.make_ip_opts(),
                buf.reply_data_ptr(),
                buf.reply_data_len(),
                self.timeout,
            )
        };
        finish_v4(ret, buf)
    }

    /// Sends an ICMPv4 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send4_from(&self, src: Ipv4Addr, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
        buf.init_for_send();
        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
        // and every argument outlives this synchronous call.
        let ret = unsafe {
            IcmpSendEcho2Ex(
                self.handles.v4,
                ptr::null_mut(), // Event
                None,            // ApcRoutine
                ptr::null(),     // ApcContext
                windows_ipv4(src),
                windows_ipv4(dst),
                buf.request_data_ptr(),
                buf.request_data_len(),
                &self.make_ip_opts(),
                buf.reply_data_ptr(),
                buf.reply_data_len(),
                self.timeout,
            )
        };
        finish_v4(ret, buf)
    }

    /// Sends an ICMPv6 request to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send6(&self, dst: Ipv6Addr, buf: &mut Buffer) -> Result<u32, Error> {
        let dst = SOCKADDR_IN6 {
            sin6_family: AF_INET6,
            sin6_addr: windows_ipv6(dst),
            ..Default::default()
        };
        buf.init_for_send();

        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
        // and every argument outlives this synchronous call.
        let ret = unsafe {
            Icmp6SendEcho2(
                self.handles.v6,
                ptr::null_mut(), // Event
                None,            // ApcRoutine
                ptr::null(),     // ApcContext
                &SOCKADDR_IN6::default(),
                &dst,
                buf.request_data_ptr(),
                buf.request_data_len(),
                &self.make_ip_opts(),
                buf.reply_data_ptr(),
                buf.reply_data_len(),
                self.timeout,
            )
        };
        finish_v6(ret, buf)
    }

    /// Sends an ICMPv6 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send6_from(&self, src: Ipv6Addr, dst: Ipv6Addr, buf: &mut Buffer) -> Result<u32, Error> {
        let dst = SOCKADDR_IN6 {
            sin6_family: AF_INET6,
            sin6_addr: windows_ipv6(dst),
            ..Default::default()
        };
        let src = SOCKADDR_IN6 {
            sin6_family: AF_INET6,
            sin6_addr: windows_ipv6(src),
            ..Default::default()
        };
        buf.init_for_send();

        // SAFETY: buf's pointers are valid for the lengths passed alongside them,
        // and every argument outlives this synchronous call.
        let ret = unsafe {
            Icmp6SendEcho2(
                self.handles.v6,
                ptr::null_mut(), // Event
                None,            // ApcRoutine
                ptr::null(),     // ApcContext
                &src,
                &dst,
                buf.request_data_ptr(),
                buf.request_data_len(),
                &self.make_ip_opts(),
                buf.reply_data_ptr(),
                buf.reply_data_len(),
                self.timeout,
            )
        };
        finish_v6(ret, buf)
    }

    /// Sends an ICMP request to the destination address. Supports both v4 and v6. On success, returns the round trip time in milliseconds.
    pub fn send(&self, dst: IpAddr, buf: &mut Buffer) -> Result<u32, Error> {
        match dst {
            IpAddr::V4(ip) => self.send4(ip, buf),
            IpAddr::V6(ip) => self.send6(ip, buf),
        }
    }

    /// 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.
    pub fn send_from(&mut self, src_dst_pair: IpPair, buf: &mut Buffer) -> Result<u32, Error> {
        match src_dst_pair {
            IpPair::V4 { src, dst } => self.send4_from(src, dst, buf),
            IpPair::V6 { src, dst } => self.send6_from(src, dst, buf),
        }
    }
}

const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Pinger>();
};

/// Interprets the return of a blocking ICMPv4 send and records the reply state.
fn finish_v4(ret: u32, buf: &mut Buffer) -> Result<u32, Error> {
    if ret == 0 {
        return Err(Error::from_lasterror());
    }
    // init_for_send always sizes for a full reply, so None is unreachable.
    let Some(reply) = buf.as_echo_reply() else {
        return Err(Error::from_iperror(IP_BUF_TOO_SMALL));
    };
    let (status, rtt) = (reply.Status, reply.RoundTripTime);
    buf.set_filled4();
    if status == IP_SUCCESS {
        Ok(rtt)
    } else {
        Err(Error::from_iperror(status))
    }
}

/// Interprets the return of a blocking ICMPv6 send and records the reply state.
fn finish_v6(ret: u32, buf: &mut Buffer) -> Result<u32, Error> {
    if ret == 0 {
        return Err(Error::from_lasterror());
    }
    let Some(reply) = buf.as_echo_reply6() else {
        return Err(Error::from_iperror(IP_BUF_TOO_SMALL));
    };
    let (status, rtt) = (reply.Status, reply.RoundTripTime);
    buf.set_filled6();
    if status == IP_SUCCESS {
        Ok(rtt)
    } else {
        Err(Error::from_iperror(status))
    }
}

impl Drop for Handles {
    fn drop(&mut self) {
        if self.v4 != INVALID_HANDLE_VALUE {
            // SAFETY: v4 is a live handle from IcmpCreateFile, closed exactly
            // once because Handles is owned by a single Arc.
            let ret = unsafe { IcmpCloseHandle(self.v4) };
            debug_assert_ne!(0, ret);
        }
        if self.v6 != INVALID_HANDLE_VALUE {
            // SAFETY: as above, for the v6 handle.
            let ret = unsafe { IcmpCloseHandle(self.v6) };
            debug_assert_ne!(0, ret);
        }
    }
}