winping-rs 0.11.0

An easy-to-use ICMP Echo API for Windows programs without requiring elevated rights.
Documentation
use core::ffi::c_void;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};

#[cfg(target_pointer_width = "64")]
use windows_sys::Win32::NetworkManagement::IpHelper::ICMP_ECHO_REPLY32;
use windows_sys::Win32::NetworkManagement::IpHelper::{ICMP_ECHO_REPLY, ICMPV6_ECHO_REPLY_LH as ICMPV6_ECHO_REPLY};

use crate::util::{rust_ipv4, rust_ipv6};

// Chunk is a lump of u8, apropriately sized and aligned
// for the necessary ICMP(V6)_ECHO_REPLY(32) types on
// 32 and 64 bit platforms.
#[cfg(target_pointer_width = "64")]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C, align(8))]
struct Chunk([u8; 8]);
#[cfg(target_pointer_width = "32")]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(C, align(4))]
struct Chunk([u8; 4]);
const CHUNK_SIZE: usize = size_of::<Chunk>();
const _: () = {
    assert!(CHUNK_SIZE == align_of::<Chunk>());
    assert!(CHUNK_SIZE == align_of::<ICMP_ECHO_REPLY>());
    assert!(CHUNK_SIZE >= align_of::<ICMPV6_ECHO_REPLY>());
    #[cfg(target_pointer_width = "64")]
    assert!(CHUNK_SIZE >= align_of::<ICMP_ECHO_REPLY32>());
};

/// A buffer for request and reply data.
#[derive(Clone, Debug)]
#[expect(
    clippy::partial_pub_fields,
    reason = "request_data is deliberately public; the reply side is an implementation detail"
)]
pub struct Buffer {
    /// The payload sent with each request. Push bytes here before sending.
    pub request_data: Vec<u8>,
    reply_data: Vec<Chunk>,
    state: ReplyState,
}

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

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum ReplyState {
    Empty,
    Filled4 { data_len: usize },
    Filled6 { data_len: usize },
}

impl Default for Buffer {
    fn default() -> Self {
        Self::new()
    }
}

impl Buffer {
    /// Creates a new, empty buffer with no request data.
    pub const fn new() -> Self {
        Self {
            request_data: Vec::new(),
            reply_data: Vec::new(),
            state: ReplyState::Empty,
        }
    }

    /// Creates a new buffer with the provided request data.
    pub const fn with_data(request_data: Vec<u8>) -> Self {
        Self {
            request_data,
            reply_data: Vec::new(),
            state: ReplyState::Empty,
        }
    }

    pub(crate) fn init_for_send(&mut self) {
        // Reply buffer must be large enough for:
        // 1. Any possible ICMP_ECHO(V6)_REPLY(32) type +
        // 2. An ICMP error (8 bytes) +
        // 3. An IO_STATUS_BLOCK (up to 16 bytes) +
        // 4. The length of the request data
        #[cfg(target_pointer_width = "64")]
        const MIN_ECHO_REPLY_SIZE: usize = {
            assert!(size_of::<ICMPV6_ECHO_REPLY>() <= size_of::<ICMP_ECHO_REPLY>());
            assert!(size_of::<ICMP_ECHO_REPLY32>() <= size_of::<ICMP_ECHO_REPLY>());
            size_of::<ICMP_ECHO_REPLY>()
        };

        #[cfg(target_pointer_width = "32")]
        const MIN_ECHO_REPLY_SIZE: usize = {
            assert!(size_of::<ICMP_ECHO_REPLY>() <= size_of::<ICMPV6_ECHO_REPLY>());
            size_of::<ICMPV6_ECHO_REPLY>()
        };

        const BASE_SIZE: usize = MIN_ECHO_REPLY_SIZE + 24;
        let size = BASE_SIZE + self.request_data.len();

        let chunks = size / CHUNK_SIZE
            + match size % CHUNK_SIZE {
                0 => 0,
                _ => 1,
            };
        self.reply_data.resize(chunks, Chunk([0; CHUNK_SIZE]));
        self.state = ReplyState::Empty;
    }

    pub(crate) fn request_data_ptr(&mut self) -> *mut c_void {
        self.request_data.as_mut_ptr().cast::<c_void>()
    }

    /// Saturates rather than truncating: the ICMP APIs cap request size at
    /// u16::MAX anyway, and a truncated length would misdescribe the buffer.
    pub(crate) fn request_data_len(&self) -> u16 {
        u16::try_from(self.request_data.len()).unwrap_or(u16::MAX)
    }

    pub(crate) fn reply_data_ptr(&mut self) -> *mut c_void {
        self.reply_data.as_mut_ptr().cast::<c_void>()
    }

    fn reply_data_ptr_const(&self) -> *const c_void {
        self.reply_data.as_ptr().cast::<c_void>()
    }

    /// Size of the reply buffer in bytes, for indexing and length checks.
    fn reply_len_bytes(&self) -> usize {
        self.reply_data.len() * CHUNK_SIZE
    }

    /// The same length, in the u32 the ICMP APIs take.
    pub(crate) fn reply_data_len(&self) -> u32 {
        u32::try_from(self.reply_len_bytes()).unwrap_or(u32::MAX)
    }

    pub(crate) fn as_echo_reply(&self) -> Option<&ICMP_ECHO_REPLY> {
        if self.reply_len_bytes() >= size_of::<ICMP_ECHO_REPLY>() {
            // SAFETY: the length check above guarantees enough initialized
            // bytes, Chunk's repr guarantees sufficient alignment, and every
            // field of the reply types is Copy.
            Some(unsafe { &*self.reply_data_ptr_const().cast() })
        } else {
            None
        }
    }

    #[cfg(all(target_pointer_width = "64", feature = "async"))]
    pub(crate) fn as_echo_reply32(&self) -> Option<&ICMP_ECHO_REPLY32> {
        if self.reply_len_bytes() >= size_of::<ICMP_ECHO_REPLY32>() {
            // SAFETY: as in as_echo_reply; IcmpParseReplies has rewritten the
            // buffer to the 32-bit layout by the time this is called.
            Some(unsafe { &*self.reply_data_ptr_const().cast() })
        } else {
            None
        }
    }

    pub(crate) fn as_echo_reply6(&self) -> Option<&ICMPV6_ECHO_REPLY> {
        if self.reply_len_bytes() >= size_of::<ICMPV6_ECHO_REPLY>() {
            // SAFETY: the length check above guarantees enough initialized
            // bytes, Chunk's repr guarantees sufficient alignment, and every
            // field of the reply types is Copy.
            Some(unsafe { &*self.reply_data_ptr_const().cast() })
        } else {
            None
        }
    }

    pub(crate) fn set_filled4(&mut self) {
        let data_len = self.as_echo_reply().map_or(0, |reply| usize::from(reply.DataSize));
        self.state = ReplyState::Filled4 { data_len }
    }

    pub(crate) fn set_filled6(&mut self) {
        // RFC 4443, section 4.2, reply data MUST be same as request data
        let data_len = self.request_data.len();
        self.state = ReplyState::Filled6 { data_len }
    }

    /// The reply data from the last ping this buffer was used in. Empty if no
    /// request was sent with this buffer, or if there was no reply.
    pub fn reply_data(&self) -> &[u8] {
        let (len, offset) = match self.state {
            ReplyState::Empty => (0, 0),
            ReplyState::Filled4 { data_len } => {
                // No need to treat ICMP_ECHO_REPLY32 separately.
                // IcmpParseReplies does not move the reply data when
                // converting ICMP_ECHO_REPLY to ICMP_ECHO_REPLY32,
                // so offset is still size of ICMP_ECHO_REPLY.
                (data_len, size_of::<ICMP_ECHO_REPLY>())
            }
            ReplyState::Filled6 { data_len } => (data_len, size_of::<ICMPV6_ECHO_REPLY>()),
        };

        if len == 0 || offset + len > self.reply_len_bytes() {
            &[]
        } else {
            // SAFETY: offset + len is within the reply buffer, checked above.
            let start = unsafe { self.reply_data_ptr_const().cast::<u8>().add(offset) };
            // SAFETY: start..start + len lies inside a single live allocation
            // that the ICMP API has written, and u8 has no invalid values.
            unsafe { core::slice::from_raw_parts(start, len) }
        }
    }

    /// The responding Ipv4Addr from the last request, or None if that request was
    /// v6, the buffer wasn't used in a request, or there was no reply.
    pub fn responding_ipv4(&self) -> Option<Ipv4Addr> {
        match self.state {
            ReplyState::Filled4 { .. } => self.as_echo_reply().map(|reply| rust_ipv4(reply.Address)),
            _ => None,
        }
    }

    /// The responding Ipv6Addr from the last request, or None if that request was
    /// v4, the buffer wasn't used in a request, or there was no reply.
    pub fn responding_ipv6(&self) -> Option<Ipv6Addr> {
        match self.state {
            ReplyState::Filled6 { .. } => self.as_echo_reply6().map(|reply| rust_ipv6(reply.Address.sin6_addr)),
            _ => None,
        }
    }

    /// The responding IpAddr from the last request, or None if the buffer wasn't
    /// used in a request or there was no reply.
    pub fn responding_ip(&self) -> Option<IpAddr> {
        self.responding_ipv4()
            .map(IpAddr::V4)
            .or_else(|| self.responding_ipv6().map(IpAddr::V6))
    }
}