winping-rs 0.11.0

An easy-to-use ICMP Echo API for Windows programs without requiring elevated rights.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
// Why a dedicated thread driving APCs, rather than simple event-based async
// (see the doc on AsyncPinger::new):
//  1. A future may be polled once and is only checked again after being woken.
//     Waiting on an event gives no callback with which to wake it.
//  2. Running the callback on the calling thread only works if the executor uses
//     wait functions in a particular way, which cannot be relied on.
//  3. Using events on the worker thread instead of callbacks would cap how many
//     requests could be waited on at once.
//
// State is mutated by both the calling and worker threads, so it lives in an
// Arc<Mutex>: the Mutex rules out data races, and the Arc means either thread
// dropping its handle leaves the other's intact.

use core::ffi::c_void;
use core::mem::replace;
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use core::pin::Pin;
use core::ptr;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use core::task::{Context, Poll, Waker};
use std::sync::mpsc::{self, Receiver, SyncSender};
use std::sync::{Arc, LazyLock, Mutex};
use std::thread;

use windows_sys::Win32::Foundation::{
    ERROR_IO_PENDING, GetLastError, HANDLE, WAIT_FAILED, WAIT_IO_COMPLETION, WAIT_OBJECT_0,
};
use windows_sys::Win32::NetworkManagement::IpHelper::{
    IP_BUF_TOO_SMALL, IP_FLAG_DF, IP_OPTION_INFORMATION, IP_SUCCESS, Icmp6CreateFile, Icmp6ParseReplies,
    Icmp6SendEcho2, IcmpCreateFile, IcmpParseReplies, IcmpSendEcho2, IcmpSendEcho2Ex,
};
use windows_sys::Win32::Networking::WinSock::{AF_INET6, SOCKADDR_IN6};
use windows_sys::Win32::Storage::FileSystem::{DELETE, SYNCHRONIZE};
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
use windows_sys::Win32::System::Threading::{
    CreateEventExW, EVENT_MODIFY_STATE, INFINITE, SetEvent, WaitForSingleObjectEx,
};

use crate::util::{windows_ipv4, windows_ipv6};
use crate::{Buffer, Error, IpPair};

/// A pinger that does not block when sending.
#[derive(Clone)]
pub struct AsyncPinger {
    worker: Worker,
    ttl: u8,
    df: bool,
    timeout: u32,
}

/// The result of an async ping, together with the buffer that was passed in.
#[must_use]
pub struct AsyncResult {
    /// The round trip time in milliseconds, or why the request failed.
    pub result: Result<u32, Error>,
    /// The buffer that was passed into the pinger, returned for reuse.
    pub buffer: Buffer,
}

/// The immediate return value of an AsyncPinger. You should probably just use
/// async/await syntax instead.
pub struct PingFuture {
    state: Arc<Mutex<State>>,
    kind: IpKind,
}

const _: () = {
    const fn assert_send_unpin<T: Send + Unpin>() {}
    assert_send_unpin::<PingFuture>();
};

enum State {
    Unpolled(Buffer),
    Polled(Buffer, Waker),
    Ready(Buffer),
    Failed(Buffer, u32),
    FailedAsyncSend(Buffer, u32),
    Invalid,
}

// Expected State Transitions
// Initial state: Unpolled
// Unpolled -> FailedAsyncSend if IcmpSend* returns unexpected value
// Unpolled -> Failed if IcmpSend* returns error (other than IO_PENDING)
// Unpolled -> Ready if not yet polled and callback_fn completes
// Polled -> Ready if already polled and callback_fn completes
impl AsyncPinger {
    /// Creates a new AsyncPinger.
    /// Creating one or more AsyncPingers will spawn
    /// a single dedicated thread which handles all async IO for all AsyncPingers.
    /// If ICMP handle initialization fails, all ping requests will return
    /// an error.
    ///
    /// # Panics
    ///
    /// This may panic if the compile-time environment variable `WINPING_ASYNC_BUFFER_SIZE`
    /// is set but cannot be parsed to a valid [`usize`]
    #[expect(
        clippy::new_without_default,
        reason = "new() starts a worker thread, so Default would be misleading"
    )]
    pub fn new() -> Self {
        Self {
            worker: Worker::new(),
            ttl: 255,
            df: false,
            timeout: 2000,
        }
    }

    /// Sets the IP TTL for future requets.
    pub fn set_ttl(&mut self, ttl: u8) {
        self.ttl = ttl
    }

    /// Gets the current IP TTL value.
    pub fn ttl(&self) -> u8 {
        self.ttl
    }

    /// Sets the IP Don't Fragment bit for future requests.
    pub fn set_df(&mut self, df: bool) {
        self.df = df;
    }

    /// Gets the current IP Don't Fragment bit.
    pub fn df(&self) -> bool {
        self.df
    }

    /// Sets the timeout, in milliseconds, for future requests.
    pub fn set_timeout(&mut self, timeout: u32) {
        self.timeout = timeout;
    }

    /// Gets the current timeout in milliseconds.
    pub fn timeout(&self) -> u32 {
        self.timeout
    }

    /// Send an ICMPv4 request to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send4(&self, dst: Ipv4Addr, mut buf: Buffer) -> PingFuture {
        buf.init_for_send();
        self.worker.begin_v4(None, dst, buf, self.ttl, self.timeout, self.df)
    }

    /// Sends an ICMPv4 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send4_from(&self, src: Ipv4Addr, dst: Ipv4Addr, mut buf: Buffer) -> PingFuture {
        buf.init_for_send();
        self.worker
            .begin_v4(Some(src), dst, buf, self.ttl, self.timeout, self.df)
    }

    /// Sends an ICMPv6 request to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send6(&self, dst: Ipv6Addr, mut buf: Buffer) -> PingFuture {
        buf.init_for_send();
        self.worker.begin_v6(None, dst, buf, self.ttl, self.timeout, self.df)
    }

    /// Sends an ICMPv6 request from the source address to the destination address. On success, returns the round trip time in milliseconds.
    pub fn send6_from(&self, src: Ipv6Addr, dst: Ipv6Addr, mut buf: Buffer) -> PingFuture {
        buf.init_for_send();
        self.worker
            .begin_v6(Some(src), dst, buf, self.ttl, self.timeout, self.df)
    }

    /// Sends an ICMP request to the destination address. Supports both v4 and v6. On success, returns the round trip time in milliseconds.
    pub fn send(&self, dst: IpAddr, buf: Buffer) -> PingFuture {
        match dst {
            IpAddr::V4(dst) => self.send4(dst, buf),
            IpAddr::V6(dst) => self.send6(dst, buf),
        }
    }

    /// Sends an ICMP request from the source address to the destination address. Supports both v4 and v6. On success, returns the round trip time in milliseconds.
    pub fn send_from(&self, src_dst_pair: IpPair, buf: Buffer) -> PingFuture {
        match src_dst_pair {
            IpPair::V4 { src, dst } => self.send4_from(src, dst, buf),
            IpPair::V6 { src, dst } => self.send6_from(src, dst, buf),
        }
    }
}

#[derive(Copy, Clone)]
enum IpOptionalPair {
    V4 { src: Option<Ipv4Addr>, dst: Ipv4Addr },
    V6 { src: Option<Ipv6Addr>, dst: Ipv6Addr },
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum IpKind {
    V4,
    V6,
}

#[derive(Clone)]
struct Worker {
    inner: SyncSender<Job>,
}

struct Job {
    pair: IpOptionalPair,
    data_ptr: *mut c_void,
    data_len: u16,
    reply_ptr: *mut c_void,
    reply_len: u32,
    ttl: u8,
    timeout: u32,
    df: bool,
    cx: Arc<Mutex<State>>,
}

// SAFETY: the raw pointers in Job address the request and reply buffers owned
// by the Buffer inside cx, which is kept alive by the Arc for as long as the
// request is in flight. Ownership moves to the worker thread with the Job, so
// only one thread accesses them at a time.
unsafe impl Send for Job {}

impl Worker {
    fn new() -> Self {
        Self {
            inner: ASYNC.tx.clone(),
        }
    }

    fn begin_v4(
        &self,
        src: Option<Ipv4Addr>,
        dst: Ipv4Addr,
        mut buf: Buffer,
        ttl: u8,
        timeout: u32,
        df: bool,
    ) -> PingFuture {
        let data_ptr = buf.request_data_ptr();
        let data_len = buf.request_data_len();
        let reply_ptr = buf.reply_data_ptr();
        let reply_len = buf.reply_data_len();
        let state = Arc::new(Mutex::new(State::Unpolled(buf)));
        let cx = Arc::clone(&state);
        let job = Job {
            pair: IpOptionalPair::V4 { src, dst },
            data_ptr,
            data_len,
            reply_ptr,
            reply_len,
            ttl,
            timeout,
            df,
            cx,
        };
        self.inner
            .send(job)
            .expect("the async worker thread never drops the receiver");
        // SAFETY: input_event is a live event handle created with EVENT_MODIFY_STATE.
        unsafe { SetEvent(ASYNC.handles.input_event) };
        PingFuture {
            state,
            kind: IpKind::V4,
        }
    }

    fn begin_v6(
        &self,
        src: Option<Ipv6Addr>,
        dst: Ipv6Addr,
        mut buf: Buffer,
        ttl: u8,
        timeout: u32,
        df: bool,
    ) -> PingFuture {
        let data_ptr = buf.request_data_ptr();
        let data_len = buf.request_data_len();
        let reply_ptr = buf.reply_data_ptr();
        let reply_len = buf.reply_data_len();
        let state = Arc::new(Mutex::new(State::Unpolled(buf)));
        let cx = Arc::clone(&state);
        let job = Job {
            pair: IpOptionalPair::V6 { src, dst },
            data_ptr,
            data_len,
            reply_ptr,
            reply_len,
            ttl,
            timeout,
            df,
            cx,
        };
        self.inner
            .send(job)
            .expect("the async worker thread never drops the receiver");
        // SAFETY: input_event is a live event handle created with EVENT_MODIFY_STATE.
        unsafe { SetEvent(ASYNC.handles.input_event) };
        PingFuture {
            state,
            kind: IpKind::V6,
        }
    }
}

/// The handles shared by every AsyncPinger, created once when the async worker
/// thread is started and only ever read afterwards.
#[derive(Copy, Clone)]
struct Handles {
    input_event: HANDLE,
    icmp: HANDLE,
    icmp6: HANDLE,
}
// Safety: ICMP file handles and event handles are not thread-affine; Windows
// allows them to be used from any thread. These are never mutated after
// creation, so sharing them across the calling and worker threads is sound.
// SAFETY: ICMP and event handles are not thread-affine, and these are written
// once during LazyLock initialization and only read afterwards.
unsafe impl Send for Handles {}
// SAFETY: see the comment on the Send impl above.
unsafe impl Sync for Handles {}

struct AsyncGlobals {
    handles: Handles,
    tx: SyncSender<Job>,
}

static ASYNC_BUFFER_SIZE_CT: Option<&'static str> = std::option_env!("WINPING_ASYNC_BUFFER_SIZE");
static ASYNC_BUFFER_SIZE_RT_IS_SET: AtomicBool = AtomicBool::new(false);
static ASYNC_BUFFER_SIZE_RT: AtomicUsize = AtomicUsize::new(0);
static ASYNC_BUFFER_SIZE_DEFAULT: usize = 1024;

/// Sets the size of the channel used to send ping requests to the async IO
/// thread described in [`AsyncPinger::new`].
///
/// Must be called before the first AsyncPinger is created, and takes precedence
/// over the `WINPING_ASYNC_BUFFER_SIZE` compile-time environment variable. If
/// neither is set, the size is 1024.
///
/// If that environment variable is set but cannot be parsed, creating the first
/// AsyncPinger panics.
pub fn set_async_buffer_size(size: usize) {
    ASYNC_BUFFER_SIZE_RT.store(size, Ordering::SeqCst);
    ASYNC_BUFFER_SIZE_RT_IS_SET.store(true, Ordering::SeqCst);
}

static ASYNC: LazyLock<AsyncGlobals> = LazyLock::new(|| {
    let channel_size = if ASYNC_BUFFER_SIZE_RT_IS_SET.load(Ordering::Relaxed) {
        ASYNC_BUFFER_SIZE_RT.load(Ordering::Relaxed)
    } else {
        ASYNC_BUFFER_SIZE_CT.map_or(ASYNC_BUFFER_SIZE_DEFAULT, |s| {
            s.parse()
                .expect("Failed to parse value of WINPING_ASYNC_BUFFER_SIZE compile-time environment variable")
        })
    };
    let (tx, rx) = mpsc::sync_channel(channel_size);
    const EVENT_ACCESS: u32 = DELETE | EVENT_MODIFY_STATE | SYNCHRONIZE;
    // SAFETY: null attributes and name are valid (unnamed event with default
    // security); the flags/access values are constants accepted by the API.
    let input_event = unsafe { CreateEventExW(ptr::null(), ptr::null(), 0, EVENT_ACCESS) };
    assert!(!input_event.is_null(), "could not initialize event handle");
    // Ignore failures for ICMP handles - instead, allow IcmpSendEcho (and similar) to error on use
    // SAFETY: IcmpCreateFile has no preconditions.
    let icmp = unsafe { IcmpCreateFile() };
    // SAFETY: Icmp6CreateFile has no preconditions.
    let icmp6 = unsafe { Icmp6CreateFile() };
    let handles = Handles {
        input_event,
        icmp,
        icmp6,
    };

    thread::spawn(move || {
        loop {
            // WaitForSingleObjectEx returns if input_event is signaled, or if callback_fn is called
            // SAFETY: input_event is a live event handle owned by this thread's
            // captured Handles, and SYNCHRONIZE access was requested for it.
            let wait = unsafe { WaitForSingleObjectEx(handles.input_event, INFINITE, 1) };
            match wait {
                WAIT_IO_COMPLETION | WAIT_OBJECT_0 => while try_recv_job(&rx, &handles) {},
                WAIT_FAILED => {
                    let err = Error::from_lasterror();
                    unreachable!("AsyncPinger thread failed to wait in event loop: {}", err)
                }
                x => unreachable!("unexpected return from WaitForSingleObjectEx: {:x}", x),
            }
        }
    });

    AsyncGlobals { handles, tx }
});

#[inline]
fn try_recv_job(rx: &Receiver<Job>, handles: &Handles) -> bool {
    let job = match rx.try_recv() {
        Ok(job) => job,
        _ => return false,
    };
    // IP_OPTION_INFORMATION::Flags is a u8, but windows-sys types IP_FLAG_DF as u32.
    #[expect(
        clippy::as_conversions,
        clippy::cast_possible_truncation,
        reason = "IP_FLAG_DF is the constant 2"
    )]
    const DONT_FRAGMENT: u8 = IP_FLAG_DF as u8;
    let ip_opts = IP_OPTION_INFORMATION {
        Ttl: job.ttl,
        Flags: if job.df { DONT_FRAGMENT } else { 0 },
        ..Default::default()
    };
    let arcptr = Arc::into_raw(job.cx);

    #[inline]
    fn after_send(ret: u32, arcptr: *const Mutex<State>) {
        // Only one branch may reclaim the leaked Arc, so the ret != 0 path
        // returns rather than falling through into the GetLastError check.
        if ret != 0 {
            // SAFETY: arcptr came from Arc::into_raw, and only one path reclaims it.
            let arc = unsafe { Arc::from_raw(arcptr) };
            let mut lock = arc.lock().expect("state mutex poisoned");
            let state = replace(&mut *lock, State::Invalid);
            match state {
                State::Unpolled(buf) => *lock = State::FailedAsyncSend(buf, ret),
                State::Polled(buf, waker) => {
                    *lock = State::FailedAsyncSend(buf, ret);
                    waker.wake();
                }
                _ => {} // Leave state as Invalid, pushes panic out of async thread
            }
            return;
        }
        // SAFETY: GetLastError has no preconditions and no out-parameters.
        let err = unsafe { GetLastError() };
        if err != ERROR_IO_PENDING {
            // SAFETY: arcptr came from Arc::into_raw, and only one path reclaims it.
            let arc = unsafe { Arc::from_raw(arcptr) };
            let mut lock = arc.lock().expect("state mutex poisoned");
            let state = replace(&mut *lock, State::Invalid);
            match state {
                State::Unpolled(buf) => *lock = State::Failed(buf, err),
                State::Polled(buf, waker) => {
                    *lock = State::Failed(buf, err);
                    waker.wake();
                }
                _ => {} // Leave state as Invalid, pushes panic out of async thread
            }
        }
    }

    use IpOptionalPair::{V4, V6};
    match job.pair {
        V4 { src: Some(src), dst } => {
            // SAFETY: the buffers behind arcptr stay alive until the APC runs, and
            // Icmp*SendEcho2* copies ip_opts before returning.
            let ret = unsafe {
                IcmpSendEcho2Ex(
                    handles.icmp,
                    ptr::null_mut(),   // Event
                    Some(callback_fn), // ApcRoutine
                    arcptr.cast(),     // ApcContext
                    windows_ipv4(src),
                    windows_ipv4(dst),
                    job.data_ptr,
                    job.data_len,
                    &ip_opts,
                    job.reply_ptr,
                    job.reply_len,
                    job.timeout,
                )
            };
            after_send(ret, arcptr);
        }
        V4 { src: None, dst } => {
            // SAFETY: the buffers behind arcptr stay alive until the APC runs, and
            // Icmp*SendEcho2* copies ip_opts before returning.
            let ret = unsafe {
                IcmpSendEcho2(
                    handles.icmp,
                    ptr::null_mut(),   // Event
                    Some(callback_fn), // ApcRoutine
                    arcptr.cast(),     // ApcContext
                    windows_ipv4(dst),
                    job.data_ptr,
                    job.data_len,
                    &ip_opts,
                    job.reply_ptr,
                    job.reply_len,
                    job.timeout,
                )
            };
            after_send(ret, arcptr);
        }
        V6 { src, dst } => {
            let src = SOCKADDR_IN6 {
                sin6_family: AF_INET6,
                sin6_addr: windows_ipv6(src.unwrap_or(Ipv6Addr::UNSPECIFIED)),
                ..Default::default()
            };
            let dst = SOCKADDR_IN6 {
                sin6_family: AF_INET6,
                sin6_addr: windows_ipv6(dst),
                ..Default::default()
            };
            // SAFETY: the buffers behind arcptr stay alive until the APC runs, and
            // Icmp*SendEcho2* copies ip_opts before returning.
            let ret = unsafe {
                Icmp6SendEcho2(
                    handles.icmp6,
                    ptr::null_mut(),   // Event
                    Some(callback_fn), // ApcRoutine
                    arcptr.cast(),     // ApcContext
                    &src,
                    &dst,
                    job.data_ptr,
                    job.data_len,
                    &ip_opts,
                    job.reply_ptr,
                    job.reply_len,
                    job.timeout,
                )
            };
            after_send(ret, arcptr);
        }
    }
    true
}

/// Matches [`windows_sys::Win32::System::IO::PIO_APC_ROUTINE`]. `apccontext` is
/// the pointer leaked by `Arc::into_raw` in `try_recv_job`, and this reclaims it.
unsafe extern "system" fn callback_fn(apccontext: *mut c_void, _io_status_block: *mut IO_STATUS_BLOCK, _rsvd: u32) {
    // SAFETY: apccontext is this request's Arc::into_raw pointer, and the APC
    // fires at most once, so the leaked strong count is reclaimed exactly once.
    let state_arc = unsafe { Arc::from_raw(apccontext.cast::<Mutex<State>>()) };
    let mut lock = state_arc.lock().expect("state mutex poisoned");
    let state = replace(&mut *lock, State::Invalid);
    match state {
        State::Unpolled(buf) => *lock = State::Ready(buf),
        State::Polled(buf, waker) => {
            *lock = State::Ready(buf);
            waker.wake();
        }
        _ => {} // Leave state as Invalid, pushes panic out of async thread
    }
}

impl Future for PingFuture {
    type Output = AsyncResult;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut lock = self.state.lock().expect("state mutex poisoned");
        let state = replace(&mut *lock, State::Invalid);
        match state {
            State::Unpolled(buf) | State::Polled(buf, _) => {
                *lock = State::Polled(buf, cx.waker().clone());
                Poll::Pending
            }
            State::Ready(mut buf) => {
                drop(lock);
                let ret = match self.kind {
                    // SAFETY: the reply buffer is live and reply_data_len describes it.
                    IpKind::V4 => unsafe { IcmpParseReplies(buf.reply_data_ptr(), buf.reply_data_len()) },
                    // SAFETY: as above, for the v6 parser.
                    IpKind::V6 => unsafe { Icmp6ParseReplies(buf.reply_data_ptr(), buf.reply_data_len()) },
                };
                let result = if ret == 0 {
                    Err(Error::from_lasterror())
                } else {
                    // init_for_send always sizes for a full reply, so None is unreachable.
                    let parsed = match self.kind {
                        IpKind::V4 => {
                            #[cfg(target_pointer_width = "32")]
                            let reply = buf.as_echo_reply();
                            #[cfg(target_pointer_width = "64")]
                            let reply = buf.as_echo_reply32();

                            let parsed = reply.map(|reply| (reply.Status, reply.RoundTripTime));
                            if parsed.is_some() {
                                buf.set_filled4();
                            }
                            parsed
                        }
                        IpKind::V6 => {
                            let parsed = buf.as_echo_reply6().map(|reply| (reply.Status, reply.RoundTripTime));
                            if parsed.is_some() {
                                buf.set_filled6();
                            }
                            parsed
                        }
                    };
                    match parsed {
                        Some((IP_SUCCESS, rtt)) => Ok(rtt),
                        Some((status, _)) => Err(Error::from_iperror(status)),
                        None => Err(Error::from_iperror(IP_BUF_TOO_SMALL)),
                    }
                };
                Poll::Ready(AsyncResult { result, buffer: buf })
            }
            State::Failed(buf, err) => {
                drop(lock);
                Poll::Ready(AsyncResult {
                    result: Err(Error::from_winerror(err)),
                    buffer: buf,
                })
            }
            State::FailedAsyncSend(_buf, err) => {
                unreachable!("Failed to send async. Expected return of 0, got {} instead.", err)
            }
            State::Invalid => unreachable!(),
        }
    }
}