open-net 0.3.5

A cross-platform async networking library for Rust with HTTP and WebSocket clients, network status monitoring, configurable retries, WebSocket reconnection and heartbeats, and managed client lifecycles. Reuse common networking infrastructure across applications to avoid repeated implementation and debugging, helping save development time and AI coding tokens.
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Fresh Windows observations. This module only samples; the service owns commit authority.
//!
//! Call each query on its service's bounded blocking worker. Cancellation revokes
//! the result even when a synchronous COM call cannot itself be interrupted.

#![cfg_attr(not(target_os = "windows"), allow(dead_code))]

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;

#[cfg(target_os = "windows")]
use crate::error::{ErrorContext, WindowsReachabilityDiagnostic, WindowsReachabilityOperation};
use crate::error::{ErrorKind, ErrorStage, NetError};
use crate::net_status::{NetworkNameSource, NetworkStatus};

const MAX_OUTPUT_BYTES: usize = 64 * 1024;

pub(crate) struct WindowsObservation {
    pub(crate) reachability: NetworkStatus,
}

/// A value owned exclusively by an explicitly requested name observation.
/// Ordinary connectivity sampling cannot construct or publish this type.
pub(crate) struct NameSample {
    pub(crate) name: Option<String>,
    pub(crate) source: NetworkNameSource,
    pub(crate) diagnostics: Vec<NetError>,
}

fn check_request(deadline: Instant, cancelled: &AtomicBool) -> Result<(), NetError> {
    let kind = if cancelled.load(Ordering::Acquire) {
        Some(ErrorKind::Cancelled)
    } else if Instant::now() >= deadline {
        Some(ErrorKind::TimedOut)
    } else {
        None
    };
    kind.map_or(Ok(()), |kind| {
        Err(NetError::from(kind).with_stage(ErrorStage::NetworkMonitor))
    })
}

fn monitor_io(error: impl Into<crate::error::BoxError>) -> NetError {
    NetError::with_source(ErrorKind::Io, error).with_stage(ErrorStage::NetworkMonitor)
}

fn reachability_from_bits(bits: u32) -> NetworkStatus {
    // NLM_CONNECTIVITY_IPV4_INTERNET and NLM_CONNECTIVITY_IPV6_INTERNET.
    // Local/subnet connectivity alone does not establish Internet availability.
    if bits & (0x40 | 0x400) != 0 {
        NetworkStatus::Available
    } else {
        NetworkStatus::Unavailable
    }
}

fn parse_wifi_ssid(output: &[u8]) -> Result<Option<String>, NetError> {
    // An OEM-codepage SSID must not become a fabricated lossy UTF-8 name. In that
    // case the caller can still use the Unicode NLM name and retain this cause.
    let output = std::str::from_utf8(output).map_err(monitor_io)?;
    Ok(output.lines().find_map(|line| {
        let (key, value) = line.split_once(':')?;
        let name = value.trim();
        (key.trim().eq_ignore_ascii_case("SSID") && !name.is_empty()).then(|| name.to_owned())
    }))
}

fn resolve_name(
    wifi: Result<Option<String>, NetError>,
    fallback: impl FnOnce() -> Result<Option<String>, NetError>,
) -> Result<NameSample, NetError> {
    let mut diagnostics = Vec::new();
    match wifi {
        Ok(Some(name)) => {
            return Ok(NameSample {
                name: Some(name),
                source: NetworkNameSource::WifiSsid,
                diagnostics,
            });
        }
        Ok(None) => {}
        Err(error) if matches!(error.kind(), ErrorKind::TimedOut | ErrorKind::Cancelled) => {
            return Err(error);
        }
        Err(error) => diagnostics.push(error),
    }
    // Only successful enumeration may establish that no name exists. A failed
    // fallback never turns into a successful observation with name=None.
    let name = fallback()?;
    let source = if name.is_some() {
        NetworkNameSource::NetworkListManager
    } else {
        NetworkNameSource::None
    };
    Ok(NameSample {
        name,
        source,
        diagnostics,
    })
}

fn append_output(output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), NetError> {
    if bytes.len() > MAX_OUTPUT_BYTES.saturating_sub(output.len()) {
        return Err(NetError::from(ErrorKind::ItemTooLarge).with_stage(ErrorStage::NetworkMonitor));
    }
    output.extend_from_slice(bytes);
    Ok(())
}

/// Own the child until it has been waited for, including every early-return path.
struct ManagedChild {
    child: std::process::Child,
    reaped: bool,
}

impl ManagedChild {
    fn new(child: std::process::Child) -> Self {
        Self {
            child,
            reaped: false,
        }
    }

    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
        let status = self.child.try_wait()?;
        self.reaped = status.is_some();
        Ok(status)
    }

    fn terminate(&mut self) -> std::io::Result<()> {
        if self.reaped {
            return Ok(());
        }
        // kill can race with normal exit. wait is mandatory in either case and
        // owns the definitive cleanup result; merely dropping Child is not enough.
        let killed = self.child.kill();
        match self.child.wait() {
            Ok(_) => {
                self.reaped = true;
                Ok(())
            }
            Err(error) => Err(killed.err().unwrap_or(error)),
        }
    }
}

impl Drop for ManagedChild {
    fn drop(&mut self) {
        if let Err(error) = self.terminate() {
            crate::log_e!(crate::common::log::log_def::LogType::Engine;
                "net_status.drop", "event|error", "network_status_query_child_cleanup",
                format!("{:?}", error.kind()));
        }
    }
}

/// This worker never invokes netsh or connected-network name enumeration.
#[cfg(target_os = "windows")]
pub(crate) fn sample_reachability(
    deadline: Instant,
    cancelled: &AtomicBool,
) -> Result<WindowsObservation, NetError> {
    sample_reachability_using(&NativeWindowsApi, deadline, cancelled)
}

#[cfg(target_os = "windows")]
fn sample_reachability_using(
    api: &impl WindowsApi,
    deadline: Instant,
    cancelled: &AtomicBool,
) -> Result<WindowsObservation, NetError> {
    with_manager_using(
        api,
        deadline,
        cancelled,
        QueryKind::Reachability,
        |manager| {
            QueryKind::Reachability.record(WindowsReachabilityOperation::NlmGetConnectivity);
            let connectivity = api.get_connectivity(manager).map_err(|error| {
                QueryKind::Reachability
                    .error(WindowsReachabilityOperation::NlmGetConnectivity, error)
            })?;
            check_request(deadline, cancelled)?;
            Ok(WindowsObservation {
                reachability: reachability_from_bits(connectivity),
            })
        },
    )
}

/// Query names only for the separate, explicitly enabled name service.
/// It neither queries nor publishes Internet connectivity.
#[cfg(any(target_os = "windows", test))]
pub(crate) fn query_name(
    deadline: Instant,
    cancelled: &AtomicBool,
) -> Result<NameSample, NetError> {
    #[cfg(target_os = "windows")]
    {
        with_manager(deadline, cancelled, |manager| {
            let sample = resolve_name(query_wifi_ssid(deadline, cancelled), || {
                query_nlm_name(manager, deadline, cancelled)
            })?;
            check_request(deadline, cancelled)?;
            Ok(sample)
        })
    }
    #[cfg(not(target_os = "windows"))]
    {
        check_request(deadline, cancelled)?;
        Err(NetError::from(ErrorKind::Unsupported).with_stage(ErrorStage::NetworkMonitor))
    }
}

#[cfg(target_os = "windows")]
fn with_manager<T>(
    deadline: Instant,
    cancelled: &AtomicBool,
    query: impl FnOnce(
        &windows::Win32::Networking::NetworkListManager::INetworkListManager,
    ) -> Result<T, NetError>,
) -> Result<T, NetError> {
    with_manager_using(
        &NativeWindowsApi,
        deadline,
        cancelled,
        QueryKind::Name,
        query,
    )
}

#[cfg(target_os = "windows")]
#[derive(Clone, Copy)]
enum QueryKind {
    Reachability,
    Name,
}

#[cfg(target_os = "windows")]
impl QueryKind {
    fn record(self, operation: WindowsReachabilityOperation) {
        if matches!(self, Self::Reachability) {
            super::super::sample_diagnostics::native_operation(operation);
        }
    }

    fn error(
        self,
        operation: WindowsReachabilityOperation,
        source: windows::core::Error,
    ) -> NetError {
        match self {
            Self::Name => monitor_io(source),
            Self::Reachability => {
                let diagnostic = WindowsReachabilityDiagnostic {
                    operation,
                    hresult: source.code().0 as u32,
                };
                let phase = match operation {
                    WindowsReachabilityOperation::ComInit => {
                        crate::error::NetworkMonitorPhase::ComInit
                    }
                    WindowsReachabilityOperation::NlmCreate => {
                        crate::error::NetworkMonitorPhase::NlmCreate
                    }
                    WindowsReachabilityOperation::NlmGetConnectivity => {
                        crate::error::NetworkMonitorPhase::NlmGetConnectivity
                    }
                };
                NetError::with_source(ErrorKind::Io, source)
                    .with_context(ErrorContext {
                        stage: Some(ErrorStage::NetworkMonitor),
                        windows_reachability: Some(diagnostic),
                        ..ErrorContext::default()
                    })
                    .with_network_monitor_phase(phase)
            }
        }
    }
}

// A private per-call boundary lets tests fail each native operation without
// changing system services, global hooks, or the production sampling policy.
#[cfg(target_os = "windows")]
trait WindowsApi {
    type Apartment;
    type Manager;
    fn initialize(&self) -> windows::core::Result<Self::Apartment>;
    fn create_manager(&self) -> windows::core::Result<Self::Manager>;
    fn get_connectivity(&self, manager: &Self::Manager) -> windows::core::Result<u32>;
}

#[cfg(target_os = "windows")]
fn with_manager_using<A: WindowsApi, T>(
    api: &A,
    deadline: Instant,
    cancelled: &AtomicBool,
    kind: QueryKind,
    query: impl FnOnce(&A::Manager) -> Result<T, NetError>,
) -> Result<T, NetError> {
    check_request(deadline, cancelled)?;
    kind.record(WindowsReachabilityOperation::ComInit);
    let _apartment = api
        .initialize()
        .map_err(|error| kind.error(WindowsReachabilityOperation::ComInit, error))?;
    check_request(deadline, cancelled)?;
    kind.record(WindowsReachabilityOperation::NlmCreate);
    let manager = api
        .create_manager()
        .map_err(|error| kind.error(WindowsReachabilityOperation::NlmCreate, error))?;
    check_request(deadline, cancelled)?;
    let observation = query(&manager)?;
    check_request(deadline, cancelled)?;
    Ok(observation)
}

#[cfg(target_os = "windows")]
struct NativeWindowsApi;

#[cfg(target_os = "windows")]
struct ComApartment;

#[cfg(target_os = "windows")]
impl Drop for ComApartment {
    fn drop(&mut self) {
        use windows::Win32::System::Com::CoUninitialize;
        // SAFETY: This guard lives on the initializing worker thread and
        // exists only after successful CoInitializeEx, including S_FALSE.
        unsafe { CoUninitialize() };
    }
}

#[cfg(target_os = "windows")]
impl WindowsApi for NativeWindowsApi {
    type Apartment = ComApartment;
    type Manager = windows::Win32::Networking::NetworkListManager::INetworkListManager;

    fn initialize(&self) -> windows::core::Result<ComApartment> {
        use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
        // SAFETY: with_manager_using creates, uses and releases all interfaces
        // on this worker before dropping the guard. S_FALSE also owns one init.
        unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.ok()?;
        Ok(ComApartment)
    }

    fn create_manager(&self) -> windows::core::Result<Self::Manager> {
        use windows::Win32::Networking::NetworkListManager::NetworkListManager;
        use windows::Win32::System::Com::{CoCreateInstance, CLSCTX_ALL};
        // SAFETY: with_manager_using holds a successful COM initialization;
        // the SDK supplies matching class/interface IDs and owns the reference.
        unsafe { CoCreateInstance(&NetworkListManager, None, CLSCTX_ALL) }
    }

    fn get_connectivity(&self, manager: &Self::Manager) -> windows::core::Result<u32> {
        // SAFETY: manager remains live in this apartment; no raw output buffer is used.
        unsafe { manager.GetConnectivity() }.map(|connectivity| connectivity.0 as u32)
    }
}

#[cfg(target_os = "windows")]
fn query_nlm_name(
    manager: &windows::Win32::Networking::NetworkListManager::INetworkListManager,
    deadline: Instant,
    cancelled: &AtomicBool,
) -> Result<Option<String>, NetError> {
    use windows::Win32::Networking::NetworkListManager::NLM_ENUM_NETWORK_CONNECTED;

    check_request(deadline, cancelled)?;
    // SAFETY: The manager is a live interface in the current initialized apartment.
    let networks =
        unsafe { manager.GetNetworks(NLM_ENUM_NETWORK_CONNECTED) }.map_err(monitor_io)?;
    // Connected sets are normally small. Bound work even with an abnormal provider.
    for _ in 0..1024 {
        check_request(deadline, cancelled)?;
        let mut fetched = 0;
        let mut items = [None];
        // SAFETY: Both output references remain exclusively borrowed for the
        // call. The generated binding supplies the one-element slice length.
        unsafe { networks.Next(&mut items, Some(&mut fetched)) }.map_err(monitor_io)?;
        check_request(deadline, cancelled)?;
        if fetched == 0 {
            return Ok(None);
        }
        let network = items[0]
            .as_ref()
            .ok_or_else(|| NetError::from(ErrorKind::Internal))?;
        // SAFETY: The enumerated interface is live on the same apartment; its
        // returned BSTR is owned by the generated Windows binding.
        let name = unsafe { network.GetName() }
            .map_err(monitor_io)?
            .to_string();
        check_request(deadline, cancelled)?;
        if !name.trim().is_empty() {
            return Ok(Some(name));
        }
    }
    Err(NetError::from(ErrorKind::ResourceExhausted).with_stage(ErrorStage::NetworkMonitor))
}

#[cfg(target_os = "windows")]
fn query_wifi_ssid(deadline: Instant, cancelled: &AtomicBool) -> Result<Option<String>, NetError> {
    check_request(deadline, cancelled)?;
    let mut command = std::process::Command::new(system_netsh_path()?);
    command.args(["wlan", "show", "interfaces"]);
    parse_wifi_ssid(&command_output(command, deadline, cancelled)?)
}

#[cfg(target_os = "windows")]
fn system_netsh_path() -> Result<std::path::PathBuf, NetError> {
    use std::os::windows::ffi::OsStringExt;
    use windows::Win32::System::SystemInformation::GetSystemDirectoryW;

    // A bounded UTF-16 Windows path buffer also avoids environment/PATH lookup.
    let mut directory = vec![0u16; 32_768];
    // SAFETY: the generated binding passes this exclusively owned output slice.
    let length = unsafe { GetSystemDirectoryW(Some(&mut directory)) } as usize;
    if length == 0 {
        return Err(monitor_io(std::io::Error::last_os_error()));
    }
    if length >= directory.len() {
        return Err(NetError::from(ErrorKind::ItemTooLarge).with_stage(ErrorStage::NetworkMonitor));
    }
    directory.truncate(length);
    let directory = std::path::PathBuf::from(std::ffi::OsString::from_wide(&directory));
    if !directory.is_absolute() {
        return Err(NetError::from(ErrorKind::InvalidConfig).with_stage(ErrorStage::NetworkMonitor));
    }
    Ok(directory.join("netsh.exe"))
}

#[cfg(target_os = "windows")]
fn command_output(
    mut command: std::process::Command,
    deadline: Instant,
    cancelled: &AtomicBool,
) -> Result<Vec<u8>, NetError> {
    use std::io::Read;
    use std::os::windows::io::AsRawHandle;
    use std::os::windows::process::CommandExt;
    use std::process::Stdio;
    use std::time::Duration;
    use windows::Win32::Foundation::{ERROR_BROKEN_PIPE, HANDLE};
    use windows::Win32::System::Pipes::PeekNamedPipe;

    check_request(deadline, cancelled)?;
    let child = command
        .creation_flags(0x0800_0000) // CREATE_NO_WINDOW
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(monitor_io)?;
    let mut child = ManagedChild::new(child);
    let mut stdout = child
        .child
        .stdout
        .take()
        .ok_or_else(|| NetError::from(ErrorKind::Internal))?;
    let mut output = Vec::new();
    let mut chunk = [0; 4096];
    let mut exit = None;

    loop {
        check_request(deadline, cancelled)?;
        let mut available = 0;
        // SAFETY: stdout owns this live pipe handle through the call, and
        // available is a valid exclusive output pointer. No buffer is supplied.
        // No other code reads this handle. Read only bytes already in the pipe,
        // so a child that keeps stdout open cannot block the cancellation loop.
        let peeked = unsafe {
            PeekNamedPipe(
                HANDLE(stdout.as_raw_handle()),
                None,
                0,
                None,
                Some(&mut available),
                None,
            )
        };
        if let Err(error) = peeked {
            if error.code() != windows::core::HRESULT::from_win32(ERROR_BROKEN_PIPE.0) {
                return Err(monitor_io(error));
            }
        }
        if available > 0 {
            let length = (available as usize).min(chunk.len());
            let read = stdout.read(&mut chunk[..length]).map_err(monitor_io)?;
            append_output(&mut output, &chunk[..read])?;
            if read != 0 {
                continue;
            }
        }
        if exit.is_none() {
            exit = child.try_wait().map_err(monitor_io)?;
            if exit.is_some() {
                // The child may have written between the empty peek and its
                // exit. Drain once more after observing exit before parsing.
                continue;
            }
        }
        if let Some(status) = exit {
            if !status.success() {
                return Err(monitor_io(std::io::Error::other(format!(
                    "Windows network-name query exited with {status}"
                ))));
            }
            check_request(deadline, cancelled)?;
            return Ok(output);
        }
        std::thread::sleep(
            deadline
                .saturating_duration_since(Instant::now())
                .min(Duration::from_millis(5)),
        );
    }
}

#[cfg(all(test, target_os = "windows"))]
#[path = "windows_diagnostics_tests.rs"]
mod windows_diagnostics_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn only_internet_flags_establish_reachability() {
        for bits in [0, 0x01, 0x02, 0x10, 0x20, 0x100, 0x200, 0x333] {
            assert_eq!(reachability_from_bits(bits), NetworkStatus::Unavailable);
        }
        for bits in [0x40, 0x400, 0x440, 0x773] {
            assert_eq!(reachability_from_bits(bits), NetworkStatus::Available);
        }
    }

    #[test]
    fn ssid_parser_does_not_confuse_bssid_or_empty_values() {
        assert_eq!(
            parse_wifi_ssid(b" BSSID : 00:11:22:33:44:55\n SSID : \n SSID : cafe:guest\n").unwrap(),
            Some("cafe:guest".into())
        );
        assert!(parse_wifi_ssid(b"State : disconnected\n")
            .unwrap()
            .is_none());
        assert_eq!(
            parse_wifi_ssid(b"SSID : \xff").unwrap_err().kind(),
            ErrorKind::Io
        );
    }

    #[test]
    fn wifi_success_does_not_query_fallback() {
        let resolved =
            resolve_name(Ok(Some("wifi".into())), || panic!("unneeded fallback")).unwrap();
        assert_eq!(resolved.name.as_deref(), Some("wifi"));
        assert!(matches!(resolved.source, NetworkNameSource::WifiSsid));
        assert!(resolved.diagnostics.is_empty());
    }

    #[test]
    fn fallback_retains_wifi_failure_but_never_hides_its_own_failure() {
        let resolved = resolve_name(Err(NetError::from(ErrorKind::Io)), || {
            Ok(Some("wired".into()))
        })
        .unwrap();
        assert_eq!(resolved.name.as_deref(), Some("wired"));
        assert!(matches!(
            resolved.source,
            NetworkNameSource::NetworkListManager
        ));
        assert_eq!(resolved.diagnostics[0].kind(), ErrorKind::Io);
        let failed = resolve_name(Ok(None), || Err(NetError::from(ErrorKind::Io)));
        assert!(matches!(failed, Err(error) if error.kind() == ErrorKind::Io));
        let absent = resolve_name(Err(NetError::from(ErrorKind::Io)), || Ok(None)).unwrap();
        assert!(absent.name.is_none());
        assert!(matches!(absent.source, NetworkNameSource::None));
        assert_eq!(absent.diagnostics.len(), 1);
    }

    #[test]
    fn cancellation_and_timeout_do_not_attempt_name_fallback() {
        for kind in [ErrorKind::Cancelled, ErrorKind::TimedOut] {
            let result = resolve_name(Err(NetError::from(kind)), || panic!("invalid fallback"));
            assert!(matches!(result, Err(error) if error.kind() == kind));
        }
        let cancelled = AtomicBool::new(true);
        assert_eq!(
            check_request(Instant::now() + Duration::from_secs(1), &cancelled)
                .unwrap_err()
                .kind(),
            ErrorKind::Cancelled
        );
        cancelled.store(false, Ordering::Release);
        assert_eq!(
            check_request(Instant::now(), &cancelled)
                .unwrap_err()
                .kind(),
            ErrorKind::TimedOut
        );
    }

    #[test]
    fn oversized_stdout_does_not_grow_the_retained_buffer() {
        let mut output = vec![0; MAX_OUTPUT_BYTES - 1];
        assert_eq!(
            append_output(&mut output, b"12").unwrap_err().kind(),
            ErrorKind::ItemTooLarge
        );
        assert_eq!(output.len(), MAX_OUTPUT_BYTES - 1);
        append_output(&mut output, b"1").unwrap();
        assert_eq!(output.len(), MAX_OUTPUT_BYTES);
    }

    #[cfg(unix)]
    #[test]
    fn interrupted_child_is_killed_and_waited_for() {
        let child = std::process::Command::new("/bin/sh")
            .args(["-c", "exec sleep 30"])
            .spawn()
            .unwrap();
        let mut child = ManagedChild::new(child);
        child.terminate().unwrap();
        assert!(child.reaped);
        assert!(child.try_wait().unwrap().is_some());
        child.terminate().unwrap();
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn portable_flags_match_the_windows_api() {
        use windows::Win32::Networking::NetworkListManager::{
            NLM_CONNECTIVITY_IPV4_INTERNET, NLM_CONNECTIVITY_IPV6_INTERNET,
        };
        assert_eq!(NLM_CONNECTIVITY_IPV4_INTERNET.0, 0x40);
        assert_eq!(NLM_CONNECTIVITY_IPV6_INTERNET.0, 0x400);
    }

    #[cfg(target_os = "windows")]
    fn shell_command(script: &str) -> std::process::Command {
        let mut command = std::process::Command::new("cmd");
        command.args(["/D", "/C", script]);
        command
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn completed_child_output_is_drained_and_nonzero_exit_is_an_error() {
        let cancelled = AtomicBool::new(false);
        let deadline = Instant::now() + Duration::from_secs(10);
        let output =
            command_output(shell_command("echo SSID : test"), deadline, &cancelled).unwrap();
        assert_eq!(parse_wifi_ssid(&output).unwrap().as_deref(), Some("test"));
        assert_eq!(
            command_output(shell_command("exit /B 7"), deadline, &cancelled)
                .unwrap_err()
                .kind(),
            ErrorKind::Io
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn live_child_output_is_bounded_and_silent_child_times_out() {
        let cancelled = AtomicBool::new(false);
        let output = command_output(
            shell_command("for /L %i in (1,1,4096) do @echo 0123456789abcdef"),
            Instant::now() + Duration::from_secs(10),
            &cancelled,
        );
        assert_eq!(output.unwrap_err().kind(), ErrorKind::ItemTooLarge);
        let timeout = command_output(
            shell_command("for /L %i in (1,1,2147483647) do @rem busy"),
            Instant::now() + Duration::from_millis(30),
            &cancelled,
        );
        assert_eq!(timeout.unwrap_err().kind(), ErrorKind::TimedOut);
    }
}