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::ptr;

use windows_sys::Win32::Foundation::{
    ERROR_HOST_UNREACHABLE, ERROR_NETWORK_UNREACHABLE, ERROR_PROTOCOL_UNREACHABLE, GetLastError, NO_ERROR,
};
use windows_sys::Win32::NetworkManagement::IpHelper::{
    GetIpErrorString, IP_DEST_HOST_UNREACHABLE, IP_DEST_NET_UNREACHABLE, IP_DEST_PROT_UNREACHABLE, IP_PACKET_TOO_BIG,
    IP_REQ_TIMED_OUT, IP_STATUS_BASE, IP_TTL_EXPIRED_REASSEM, IP_TTL_EXPIRED_TRANSIT, MAX_IP_STATUS,
};
use windows_sys::Win32::System::Diagnostics::Debug::{
    FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessageW,
};

/// An error when sending a ping request.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub enum Error {
    /// The ping request timed out.
    Timeout,
    /// The destination network is unreachable.
    NetUnreachable,
    /// The destination host is unreachable.
    HostUnreachable,
    /// The IP TTL expired during transit.
    TtlExpired,
    /// The IP reassembly timer expired.
    ReassemblyExpired,
    /// The packet needs fragmented, but the DF bit is set.
    NeedsFragmented,
    /// The destination protocol is unreachable.
    ProtocolUnreachable,
    /// Some other error ocurred. Format with debug or diplay to get more info.
    Other(u32),
}

impl Error {
    pub(crate) fn from_iperror(err: u32) -> Self {
        match err {
            IP_REQ_TIMED_OUT => Error::Timeout,
            IP_DEST_HOST_UNREACHABLE => Error::HostUnreachable,
            IP_DEST_NET_UNREACHABLE => Error::NetUnreachable,
            IP_TTL_EXPIRED_TRANSIT => Error::TtlExpired,
            IP_TTL_EXPIRED_REASSEM => Error::ReassemblyExpired,
            IP_DEST_PROT_UNREACHABLE => Error::ProtocolUnreachable,
            IP_PACKET_TOO_BIG => Error::NeedsFragmented,
            _ => Error::Other(err),
        }
    }

    /// Creates an Error from the last Windows error
    pub(crate) fn from_lasterror() -> Self {
        // SAFETY: GetLastError has no preconditions and no out-parameters.
        Self::from_winerror(unsafe { GetLastError() })
    }

    /// Takes either a Windows error or IP_STATUS value
    pub(crate) fn from_winerror(err: u32) -> Self {
        match err {
            IP_STATUS_BASE..=MAX_IP_STATUS => Error::from_iperror(err),
            ERROR_HOST_UNREACHABLE => Error::HostUnreachable,
            ERROR_NETWORK_UNREACHABLE => Error::NetUnreachable,
            ERROR_PROTOCOL_UNREACHABLE => Error::ProtocolUnreachable,
            _ => Error::Other(err),
        }
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Error::Timeout => write!(f, "request timed out"),
            Error::HostUnreachable => write!(f, "destination host unreachable"),
            Error::NetUnreachable => write!(f, "destination network unreachable"),
            Error::TtlExpired => write!(f, "tTL expired in transit"),
            Error::ReassemblyExpired => write!(f, "reassembly timed out waiting for fragments"),
            Error::NeedsFragmented => write!(f, "packet needs fragmented"),
            Error::ProtocolUnreachable => write!(f, "destination protocol unreachable"),
            Error::Other(err @ IP_STATUS_BASE..=MAX_IP_STATUS) => {
                let mut buf = [0u16; 256];
                // Leave room for the terminating null. Must stay <= buf.len().
                let mut size = 255;
                // SAFETY: buf is valid for BUF_LEN u16 writes, and size tells
                // GetIpErrorString how much of it may be written.
                let ret = unsafe { GetIpErrorString(*err, buf.as_mut_ptr(), &mut size) };
                debug_assert_eq!(NO_ERROR, ret);
                let len = buf.iter().take_while(|x| **x != 0).count();
                let s = String::from_utf16_lossy(&buf[..len]);
                write!(f, "other IP error ({}): {}", err, s.trim())
            }
            Error::Other(err) => {
                const FLAGS: u32 = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
                let mut buf = [0u16; 256];
                // SAFETY: FORMAT_MESSAGE_FROM_SYSTEM means lpsource is unused,
                // FORMAT_MESSAGE_IGNORE_INSERTS means arguments is unused, and
                // buf is valid for the BUF_LEN u16 writes nsize permits.
                let len = unsafe {
                    FormatMessageW(
                        FLAGS,
                        ptr::null(),
                        *err,
                        0, // lang id
                        buf.as_mut_ptr(),
                        256, // Must stay <= buf.len().
                        ptr::null(),
                    )
                };
                // FormatMessageW returns the character count written, which is
                // bounded by BUF_LEN, so this cannot exceed buf.
                let s = String::from_utf16_lossy(&buf[..usize::try_from(len).unwrap_or(0)]);
                write!(f, "other error ({}): {}", err, s.trim())
            }
        }
    }
}

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

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