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
21unsafe impl Send for Handles {}
29unsafe impl Sync for Handles {}
31
32#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
34pub enum IpPair {
35 V4 {
37 src: Ipv4Addr,
39 dst: Ipv4Addr,
41 },
42
43 V6 {
45 src: Ipv6Addr,
47 dst: Ipv6Addr,
49 },
50}
51
52#[derive(Clone)]
58pub struct Pinger {
59 handles: Arc<Handles>,
60 ttl: u8,
61 df: bool,
62 timeout: u32,
63}
64
65pub enum CreateError {
67 NoV4(Pinger),
69 NoV6(Pinger),
71 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 pub fn new() -> Result<Self, CreateError> {
106 let v4 = unsafe { IcmpCreateFile() };
109 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 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 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 pub fn set_ttl(&mut self, ttl: u8) {
145 self.ttl = ttl;
146 }
147
148 pub fn ttl(&self) -> u8 {
150 self.ttl
151 }
152
153 pub fn set_df(&mut self, df: bool) {
155 self.df = df;
156 }
157
158 pub fn df(&self) -> bool {
160 self.df
161 }
162
163 pub fn set_timeout(&mut self, timeout: u32) {
165 self.timeout = timeout;
166 }
167
168 pub fn timeout(&self) -> u32 {
170 self.timeout
171 }
172
173 #[inline]
174 fn make_ip_opts(&self) -> IP_OPTION_INFORMATION {
175 #[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 pub fn send4(&self, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
191 buf.init_for_send();
192 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 pub fn send4_from(&self, src: Ipv4Addr, dst: Ipv4Addr, buf: &mut Buffer) -> Result<u32, Error> {
211 buf.init_for_send();
212 let ret = unsafe {
215 IcmpSendEcho2Ex(
216 self.handles.v4,
217 ptr::null_mut(), None, ptr::null(), 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 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 let ret = unsafe {
245 Icmp6SendEcho2(
246 self.handles.v6,
247 ptr::null_mut(), None, ptr::null(), &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 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 let ret = unsafe {
280 Icmp6SendEcho2(
281 self.handles.v6,
282 ptr::null_mut(), None, ptr::null(), &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 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 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
320fn finish_v4(ret: u32, buf: &mut Buffer) -> Result<u32, Error> {
322 if ret == 0 {
323 return Err(Error::from_lasterror());
324 }
325 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
338fn 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 let ret = unsafe { IcmpCloseHandle(self.v4) };
361 debug_assert_ne!(0, ret);
362 }
363 if self.v6 != INVALID_HANDLE_VALUE {
364 let ret = unsafe { IcmpCloseHandle(self.v6) };
366 debug_assert_ne!(0, ret);
367 }
368 }
369}