1use core::ffi::c_void;
15use core::mem::replace;
16use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
17use core::pin::Pin;
18use core::ptr;
19use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
20use core::task::{Context, Poll, Waker};
21use std::sync::mpsc::{self, Receiver, SyncSender};
22use std::sync::{Arc, LazyLock, Mutex};
23use std::thread;
24
25use windows_sys::Win32::Foundation::{
26 ERROR_IO_PENDING, GetLastError, HANDLE, WAIT_FAILED, WAIT_IO_COMPLETION, WAIT_OBJECT_0,
27};
28use windows_sys::Win32::NetworkManagement::IpHelper::{
29 IP_BUF_TOO_SMALL, IP_FLAG_DF, IP_OPTION_INFORMATION, IP_SUCCESS, Icmp6CreateFile, Icmp6ParseReplies,
30 Icmp6SendEcho2, IcmpCreateFile, IcmpParseReplies, IcmpSendEcho2, IcmpSendEcho2Ex,
31};
32use windows_sys::Win32::Networking::WinSock::{AF_INET6, SOCKADDR_IN6};
33use windows_sys::Win32::Storage::FileSystem::{DELETE, SYNCHRONIZE};
34use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
35use windows_sys::Win32::System::Threading::{
36 CreateEventExW, EVENT_MODIFY_STATE, INFINITE, SetEvent, WaitForSingleObjectEx,
37};
38
39use crate::util::{windows_ipv4, windows_ipv6};
40use crate::{Buffer, Error, IpPair};
41
42#[derive(Clone)]
44pub struct AsyncPinger {
45 worker: Worker,
46 ttl: u8,
47 df: bool,
48 timeout: u32,
49}
50
51#[must_use]
53pub struct AsyncResult {
54 pub result: Result<u32, Error>,
56 pub buffer: Buffer,
58}
59
60pub struct PingFuture {
63 state: Arc<Mutex<State>>,
64 kind: IpKind,
65}
66
67const _: () = {
68 const fn assert_send_unpin<T: Send + Unpin>() {}
69 assert_send_unpin::<PingFuture>();
70};
71
72enum State {
73 Unpolled(Buffer),
74 Polled(Buffer, Waker),
75 Ready(Buffer),
76 Failed(Buffer, u32),
77 FailedAsyncSend(Buffer, u32),
78 Invalid,
79}
80
81impl AsyncPinger {
88 #[expect(
99 clippy::new_without_default,
100 reason = "new() starts a worker thread, so Default would be misleading"
101 )]
102 pub fn new() -> Self {
103 Self {
104 worker: Worker::new(),
105 ttl: 255,
106 df: false,
107 timeout: 2000,
108 }
109 }
110
111 pub fn set_ttl(&mut self, ttl: u8) {
113 self.ttl = ttl
114 }
115
116 pub fn ttl(&self) -> u8 {
118 self.ttl
119 }
120
121 pub fn set_df(&mut self, df: bool) {
123 self.df = df;
124 }
125
126 pub fn df(&self) -> bool {
128 self.df
129 }
130
131 pub fn set_timeout(&mut self, timeout: u32) {
133 self.timeout = timeout;
134 }
135
136 pub fn timeout(&self) -> u32 {
138 self.timeout
139 }
140
141 pub fn send4(&self, dst: Ipv4Addr, mut buf: Buffer) -> PingFuture {
143 buf.init_for_send();
144 self.worker.begin_v4(None, dst, buf, self.ttl, self.timeout, self.df)
145 }
146
147 pub fn send4_from(&self, src: Ipv4Addr, dst: Ipv4Addr, mut buf: Buffer) -> PingFuture {
149 buf.init_for_send();
150 self.worker
151 .begin_v4(Some(src), dst, buf, self.ttl, self.timeout, self.df)
152 }
153
154 pub fn send6(&self, dst: Ipv6Addr, mut buf: Buffer) -> PingFuture {
156 buf.init_for_send();
157 self.worker.begin_v6(None, dst, buf, self.ttl, self.timeout, self.df)
158 }
159
160 pub fn send6_from(&self, src: Ipv6Addr, dst: Ipv6Addr, mut buf: Buffer) -> PingFuture {
162 buf.init_for_send();
163 self.worker
164 .begin_v6(Some(src), dst, buf, self.ttl, self.timeout, self.df)
165 }
166
167 pub fn send(&self, dst: IpAddr, buf: Buffer) -> PingFuture {
169 match dst {
170 IpAddr::V4(dst) => self.send4(dst, buf),
171 IpAddr::V6(dst) => self.send6(dst, buf),
172 }
173 }
174
175 pub fn send_from(&self, src_dst_pair: IpPair, buf: Buffer) -> PingFuture {
177 match src_dst_pair {
178 IpPair::V4 { src, dst } => self.send4_from(src, dst, buf),
179 IpPair::V6 { src, dst } => self.send6_from(src, dst, buf),
180 }
181 }
182}
183
184#[derive(Copy, Clone)]
185enum IpOptionalPair {
186 V4 { src: Option<Ipv4Addr>, dst: Ipv4Addr },
187 V6 { src: Option<Ipv6Addr>, dst: Ipv6Addr },
188}
189
190#[derive(Copy, Clone, Eq, PartialEq, Debug)]
191enum IpKind {
192 V4,
193 V6,
194}
195
196#[derive(Clone)]
197struct Worker {
198 inner: SyncSender<Job>,
199}
200
201struct Job {
202 pair: IpOptionalPair,
203 data_ptr: *mut c_void,
204 data_len: u16,
205 reply_ptr: *mut c_void,
206 reply_len: u32,
207 ttl: u8,
208 timeout: u32,
209 df: bool,
210 cx: Arc<Mutex<State>>,
211}
212
213unsafe impl Send for Job {}
218
219impl Worker {
220 fn new() -> Self {
221 Self {
222 inner: ASYNC.tx.clone(),
223 }
224 }
225
226 fn begin_v4(
227 &self,
228 src: Option<Ipv4Addr>,
229 dst: Ipv4Addr,
230 mut buf: Buffer,
231 ttl: u8,
232 timeout: u32,
233 df: bool,
234 ) -> PingFuture {
235 let data_ptr = buf.request_data_ptr();
236 let data_len = buf.request_data_len();
237 let reply_ptr = buf.reply_data_ptr();
238 let reply_len = buf.reply_data_len();
239 let state = Arc::new(Mutex::new(State::Unpolled(buf)));
240 let cx = Arc::clone(&state);
241 let job = Job {
242 pair: IpOptionalPair::V4 { src, dst },
243 data_ptr,
244 data_len,
245 reply_ptr,
246 reply_len,
247 ttl,
248 timeout,
249 df,
250 cx,
251 };
252 self.inner
253 .send(job)
254 .expect("the async worker thread never drops the receiver");
255 unsafe { SetEvent(ASYNC.handles.input_event) };
257 PingFuture {
258 state,
259 kind: IpKind::V4,
260 }
261 }
262
263 fn begin_v6(
264 &self,
265 src: Option<Ipv6Addr>,
266 dst: Ipv6Addr,
267 mut buf: Buffer,
268 ttl: u8,
269 timeout: u32,
270 df: bool,
271 ) -> PingFuture {
272 let data_ptr = buf.request_data_ptr();
273 let data_len = buf.request_data_len();
274 let reply_ptr = buf.reply_data_ptr();
275 let reply_len = buf.reply_data_len();
276 let state = Arc::new(Mutex::new(State::Unpolled(buf)));
277 let cx = Arc::clone(&state);
278 let job = Job {
279 pair: IpOptionalPair::V6 { src, dst },
280 data_ptr,
281 data_len,
282 reply_ptr,
283 reply_len,
284 ttl,
285 timeout,
286 df,
287 cx,
288 };
289 self.inner
290 .send(job)
291 .expect("the async worker thread never drops the receiver");
292 unsafe { SetEvent(ASYNC.handles.input_event) };
294 PingFuture {
295 state,
296 kind: IpKind::V6,
297 }
298 }
299}
300
301#[derive(Copy, Clone)]
304struct Handles {
305 input_event: HANDLE,
306 icmp: HANDLE,
307 icmp6: HANDLE,
308}
309unsafe impl Send for Handles {}
315unsafe impl Sync for Handles {}
317
318struct AsyncGlobals {
319 handles: Handles,
320 tx: SyncSender<Job>,
321}
322
323static ASYNC_BUFFER_SIZE_CT: Option<&'static str> = std::option_env!("WINPING_ASYNC_BUFFER_SIZE");
324static ASYNC_BUFFER_SIZE_RT_IS_SET: AtomicBool = AtomicBool::new(false);
325static ASYNC_BUFFER_SIZE_RT: AtomicUsize = AtomicUsize::new(0);
326static ASYNC_BUFFER_SIZE_DEFAULT: usize = 1024;
327
328pub fn set_async_buffer_size(size: usize) {
338 ASYNC_BUFFER_SIZE_RT.store(size, Ordering::SeqCst);
339 ASYNC_BUFFER_SIZE_RT_IS_SET.store(true, Ordering::SeqCst);
340}
341
342static ASYNC: LazyLock<AsyncGlobals> = LazyLock::new(|| {
343 let channel_size = if ASYNC_BUFFER_SIZE_RT_IS_SET.load(Ordering::Relaxed) {
344 ASYNC_BUFFER_SIZE_RT.load(Ordering::Relaxed)
345 } else {
346 ASYNC_BUFFER_SIZE_CT.map_or(ASYNC_BUFFER_SIZE_DEFAULT, |s| {
347 s.parse()
348 .expect("Failed to parse value of WINPING_ASYNC_BUFFER_SIZE compile-time environment variable")
349 })
350 };
351 let (tx, rx) = mpsc::sync_channel(channel_size);
352 const EVENT_ACCESS: u32 = DELETE | EVENT_MODIFY_STATE | SYNCHRONIZE;
353 let input_event = unsafe { CreateEventExW(ptr::null(), ptr::null(), 0, EVENT_ACCESS) };
356 assert!(!input_event.is_null(), "could not initialize event handle");
357 let icmp = unsafe { IcmpCreateFile() };
360 let icmp6 = unsafe { Icmp6CreateFile() };
362 let handles = Handles {
363 input_event,
364 icmp,
365 icmp6,
366 };
367
368 thread::spawn(move || {
369 loop {
370 let wait = unsafe { WaitForSingleObjectEx(handles.input_event, INFINITE, 1) };
374 match wait {
375 WAIT_IO_COMPLETION | WAIT_OBJECT_0 => while try_recv_job(&rx, &handles) {},
376 WAIT_FAILED => {
377 let err = Error::from_lasterror();
378 unreachable!("AsyncPinger thread failed to wait in event loop: {}", err)
379 }
380 x => unreachable!("unexpected return from WaitForSingleObjectEx: {:x}", x),
381 }
382 }
383 });
384
385 AsyncGlobals { handles, tx }
386});
387
388#[inline]
389fn try_recv_job(rx: &Receiver<Job>, handles: &Handles) -> bool {
390 let job = match rx.try_recv() {
391 Ok(job) => job,
392 _ => return false,
393 };
394 #[expect(
396 clippy::as_conversions,
397 clippy::cast_possible_truncation,
398 reason = "IP_FLAG_DF is the constant 2"
399 )]
400 const DONT_FRAGMENT: u8 = IP_FLAG_DF as u8;
401 let ip_opts = IP_OPTION_INFORMATION {
402 Ttl: job.ttl,
403 Flags: if job.df { DONT_FRAGMENT } else { 0 },
404 ..Default::default()
405 };
406 let arcptr = Arc::into_raw(job.cx);
407
408 #[inline]
409 fn after_send(ret: u32, arcptr: *const Mutex<State>) {
410 if ret != 0 {
413 let arc = unsafe { Arc::from_raw(arcptr) };
415 let mut lock = arc.lock().expect("state mutex poisoned");
416 let state = replace(&mut *lock, State::Invalid);
417 match state {
418 State::Unpolled(buf) => *lock = State::FailedAsyncSend(buf, ret),
419 State::Polled(buf, waker) => {
420 *lock = State::FailedAsyncSend(buf, ret);
421 waker.wake();
422 }
423 _ => {} }
425 return;
426 }
427 let err = unsafe { GetLastError() };
429 if err != ERROR_IO_PENDING {
430 let arc = unsafe { Arc::from_raw(arcptr) };
432 let mut lock = arc.lock().expect("state mutex poisoned");
433 let state = replace(&mut *lock, State::Invalid);
434 match state {
435 State::Unpolled(buf) => *lock = State::Failed(buf, err),
436 State::Polled(buf, waker) => {
437 *lock = State::Failed(buf, err);
438 waker.wake();
439 }
440 _ => {} }
442 }
443 }
444
445 use IpOptionalPair::{V4, V6};
446 match job.pair {
447 V4 { src: Some(src), dst } => {
448 let ret = unsafe {
451 IcmpSendEcho2Ex(
452 handles.icmp,
453 ptr::null_mut(), Some(callback_fn), arcptr.cast(), windows_ipv4(src),
457 windows_ipv4(dst),
458 job.data_ptr,
459 job.data_len,
460 &ip_opts,
461 job.reply_ptr,
462 job.reply_len,
463 job.timeout,
464 )
465 };
466 after_send(ret, arcptr);
467 }
468 V4 { src: None, dst } => {
469 let ret = unsafe {
472 IcmpSendEcho2(
473 handles.icmp,
474 ptr::null_mut(), Some(callback_fn), arcptr.cast(), windows_ipv4(dst),
478 job.data_ptr,
479 job.data_len,
480 &ip_opts,
481 job.reply_ptr,
482 job.reply_len,
483 job.timeout,
484 )
485 };
486 after_send(ret, arcptr);
487 }
488 V6 { src, dst } => {
489 let src = SOCKADDR_IN6 {
490 sin6_family: AF_INET6,
491 sin6_addr: windows_ipv6(src.unwrap_or(Ipv6Addr::UNSPECIFIED)),
492 ..Default::default()
493 };
494 let dst = SOCKADDR_IN6 {
495 sin6_family: AF_INET6,
496 sin6_addr: windows_ipv6(dst),
497 ..Default::default()
498 };
499 let ret = unsafe {
502 Icmp6SendEcho2(
503 handles.icmp6,
504 ptr::null_mut(), Some(callback_fn), arcptr.cast(), &src,
508 &dst,
509 job.data_ptr,
510 job.data_len,
511 &ip_opts,
512 job.reply_ptr,
513 job.reply_len,
514 job.timeout,
515 )
516 };
517 after_send(ret, arcptr);
518 }
519 }
520 true
521}
522
523unsafe extern "system" fn callback_fn(apccontext: *mut c_void, _io_status_block: *mut IO_STATUS_BLOCK, _rsvd: u32) {
526 let state_arc = unsafe { Arc::from_raw(apccontext.cast::<Mutex<State>>()) };
529 let mut lock = state_arc.lock().expect("state mutex poisoned");
530 let state = replace(&mut *lock, State::Invalid);
531 match state {
532 State::Unpolled(buf) => *lock = State::Ready(buf),
533 State::Polled(buf, waker) => {
534 *lock = State::Ready(buf);
535 waker.wake();
536 }
537 _ => {} }
539}
540
541impl Future for PingFuture {
542 type Output = AsyncResult;
543 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
544 let mut lock = self.state.lock().expect("state mutex poisoned");
545 let state = replace(&mut *lock, State::Invalid);
546 match state {
547 State::Unpolled(buf) | State::Polled(buf, _) => {
548 *lock = State::Polled(buf, cx.waker().clone());
549 Poll::Pending
550 }
551 State::Ready(mut buf) => {
552 drop(lock);
553 let ret = match self.kind {
554 IpKind::V4 => unsafe { IcmpParseReplies(buf.reply_data_ptr(), buf.reply_data_len()) },
556 IpKind::V6 => unsafe { Icmp6ParseReplies(buf.reply_data_ptr(), buf.reply_data_len()) },
558 };
559 let result = if ret == 0 {
560 Err(Error::from_lasterror())
561 } else {
562 let parsed = match self.kind {
564 IpKind::V4 => {
565 #[cfg(target_pointer_width = "32")]
566 let reply = buf.as_echo_reply();
567 #[cfg(target_pointer_width = "64")]
568 let reply = buf.as_echo_reply32();
569
570 let parsed = reply.map(|reply| (reply.Status, reply.RoundTripTime));
571 if parsed.is_some() {
572 buf.set_filled4();
573 }
574 parsed
575 }
576 IpKind::V6 => {
577 let parsed = buf.as_echo_reply6().map(|reply| (reply.Status, reply.RoundTripTime));
578 if parsed.is_some() {
579 buf.set_filled6();
580 }
581 parsed
582 }
583 };
584 match parsed {
585 Some((IP_SUCCESS, rtt)) => Ok(rtt),
586 Some((status, _)) => Err(Error::from_iperror(status)),
587 None => Err(Error::from_iperror(IP_BUF_TOO_SMALL)),
588 }
589 };
590 Poll::Ready(AsyncResult { result, buffer: buf })
591 }
592 State::Failed(buf, err) => {
593 drop(lock);
594 Poll::Ready(AsyncResult {
595 result: Err(Error::from_winerror(err)),
596 buffer: buf,
597 })
598 }
599 State::FailedAsyncSend(_buf, err) => {
600 unreachable!("Failed to send async. Expected return of 0, got {} instead.", err)
601 }
602 State::Invalid => unreachable!(),
603 }
604 }
605}