Skip to main content

winping/
error.rs

1use core::fmt::{self, Debug, Display, Formatter};
2use core::ptr;
3
4use windows_sys::Win32::Foundation::{
5    ERROR_HOST_UNREACHABLE, ERROR_NETWORK_UNREACHABLE, ERROR_PROTOCOL_UNREACHABLE, GetLastError, NO_ERROR,
6};
7use windows_sys::Win32::NetworkManagement::IpHelper::{
8    GetIpErrorString, IP_DEST_HOST_UNREACHABLE, IP_DEST_NET_UNREACHABLE, IP_DEST_PROT_UNREACHABLE, IP_PACKET_TOO_BIG,
9    IP_REQ_TIMED_OUT, IP_STATUS_BASE, IP_TTL_EXPIRED_REASSEM, IP_TTL_EXPIRED_TRANSIT, MAX_IP_STATUS,
10};
11use windows_sys::Win32::System::Diagnostics::Debug::{
12    FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessageW,
13};
14
15/// An error when sending a ping request.
16#[derive(Copy, Clone, Eq, PartialEq, Hash)]
17pub enum Error {
18    /// The ping request timed out.
19    Timeout,
20    /// The destination network is unreachable.
21    NetUnreachable,
22    /// The destination host is unreachable.
23    HostUnreachable,
24    /// The IP TTL expired during transit.
25    TtlExpired,
26    /// The IP reassembly timer expired.
27    ReassemblyExpired,
28    /// The packet needs fragmented, but the DF bit is set.
29    NeedsFragmented,
30    /// The destination protocol is unreachable.
31    ProtocolUnreachable,
32    /// Some other error ocurred. Format with debug or diplay to get more info.
33    Other(u32),
34}
35
36impl Error {
37    pub(crate) fn from_iperror(err: u32) -> Self {
38        match err {
39            IP_REQ_TIMED_OUT => Error::Timeout,
40            IP_DEST_HOST_UNREACHABLE => Error::HostUnreachable,
41            IP_DEST_NET_UNREACHABLE => Error::NetUnreachable,
42            IP_TTL_EXPIRED_TRANSIT => Error::TtlExpired,
43            IP_TTL_EXPIRED_REASSEM => Error::ReassemblyExpired,
44            IP_DEST_PROT_UNREACHABLE => Error::ProtocolUnreachable,
45            IP_PACKET_TOO_BIG => Error::NeedsFragmented,
46            _ => Error::Other(err),
47        }
48    }
49
50    /// Creates an Error from the last Windows error
51    pub(crate) fn from_lasterror() -> Self {
52        // SAFETY: GetLastError has no preconditions and no out-parameters.
53        Self::from_winerror(unsafe { GetLastError() })
54    }
55
56    /// Takes either a Windows error or IP_STATUS value
57    pub(crate) fn from_winerror(err: u32) -> Self {
58        match err {
59            IP_STATUS_BASE..=MAX_IP_STATUS => Error::from_iperror(err),
60            ERROR_HOST_UNREACHABLE => Error::HostUnreachable,
61            ERROR_NETWORK_UNREACHABLE => Error::NetUnreachable,
62            ERROR_PROTOCOL_UNREACHABLE => Error::ProtocolUnreachable,
63            _ => Error::Other(err),
64        }
65    }
66}
67
68impl Debug for Error {
69    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
70        match self {
71            Error::Timeout => write!(f, "request timed out"),
72            Error::HostUnreachable => write!(f, "destination host unreachable"),
73            Error::NetUnreachable => write!(f, "destination network unreachable"),
74            Error::TtlExpired => write!(f, "tTL expired in transit"),
75            Error::ReassemblyExpired => write!(f, "reassembly timed out waiting for fragments"),
76            Error::NeedsFragmented => write!(f, "packet needs fragmented"),
77            Error::ProtocolUnreachable => write!(f, "destination protocol unreachable"),
78            Error::Other(err @ IP_STATUS_BASE..=MAX_IP_STATUS) => {
79                let mut buf = [0u16; 256];
80                // Leave room for the terminating null. Must stay <= buf.len().
81                let mut size = 255;
82                // SAFETY: buf is valid for BUF_LEN u16 writes, and size tells
83                // GetIpErrorString how much of it may be written.
84                let ret = unsafe { GetIpErrorString(*err, buf.as_mut_ptr(), &mut size) };
85                debug_assert_eq!(NO_ERROR, ret);
86                let len = buf.iter().take_while(|x| **x != 0).count();
87                let s = String::from_utf16_lossy(&buf[..len]);
88                write!(f, "other IP error ({}): {}", err, s.trim())
89            }
90            Error::Other(err) => {
91                const FLAGS: u32 = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
92                let mut buf = [0u16; 256];
93                // SAFETY: FORMAT_MESSAGE_FROM_SYSTEM means lpsource is unused,
94                // FORMAT_MESSAGE_IGNORE_INSERTS means arguments is unused, and
95                // buf is valid for the BUF_LEN u16 writes nsize permits.
96                let len = unsafe {
97                    FormatMessageW(
98                        FLAGS,
99                        ptr::null(),
100                        *err,
101                        0, // lang id
102                        buf.as_mut_ptr(),
103                        256, // Must stay <= buf.len().
104                        ptr::null(),
105                    )
106                };
107                // FormatMessageW returns the character count written, which is
108                // bounded by BUF_LEN, so this cannot exceed buf.
109                let s = String::from_utf16_lossy(&buf[..usize::try_from(len).unwrap_or(0)]);
110                write!(f, "other error ({}): {}", err, s.trim())
111            }
112        }
113    }
114}
115
116impl Display for Error {
117    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
118        Debug::fmt(self, f)
119    }
120}
121
122impl core::error::Error for Error {}