net-kit 0.1.0

Cross-platform network reachability monitoring with a single Net facade and Tokio runtime support.
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
use std::sync::{Arc, Mutex};
use std::time::Duration;

use n0_watcher::Watcher as _;
use tokio::runtime::Handle;
use tokio::sync::{oneshot, watch};
use tokio::time::{self, MissedTickBehavior};
use vibe_ready::{log_s, VibeEngine, VibeEngineConfig, VibeLogListener};

use crate::net::{NetworkStatusListener, NetworkStatusListenerHandle};
use crate::net_error::NetError;
use crate::network_status::NetworkStatus;

use super::monitor_runtime::MonitorRuntime;
use super::monitor_state::{Dispatcher, MonitorState, SharedListener};

pub(crate) struct InnerNet {
    engine: VibeEngine,
    state: Arc<Mutex<MonitorState>>,
}

impl InnerNet {
    /// Create the engine using the Tokio runtime bundled with (and owned by)
    /// `net-kit` via vibe-ready.
    pub fn new() -> Result<InnerNet, NetError> {
        let config = VibeEngineConfig::builder()
            .app_name("net-kit")
            .runtime_worker_threads(3)
            .callback_threads(2)
            .queue_capacity(1024, 256)
            .build();

        let engine = VibeEngine::create(config).map_err(NetError::from)?;

        Ok(InnerNet {
            engine,
            state: Arc::new(Mutex::new(MonitorState::default())),
        })
    }

    /// Create the engine using a Tokio runtime supplied by the developer. The
    /// caller is responsible for keeping that runtime alive; `shutdown` only
    /// destroys engine resources and does not close this runtime.
    pub fn new_with_tokio_rt(runtime_handle: Handle) -> Result<InnerNet, NetError> {
        let config = VibeEngineConfig::builder().app_name("net-kit").build();
        let engine = VibeEngine::create_with_runtime_handle(config, runtime_handle)
            .map_err(NetError::from)?;

        Ok(InnerNet {
            engine,
            state: Arc::new(Mutex::new(MonitorState::default())),
        })
    }

    /// Lock the instance state. Returns [`NetError::Lock`] on poison; never
    /// panics.
    fn lock_state(&self) -> Result<std::sync::MutexGuard<'_, MonitorState>, NetError> {
        self.state.lock().map_err(NetError::from_poison)
    }

    /// Start network monitoring. Redundant calls are ignored; `start` may be
    /// called again after `shutdown`.
    ///
    /// Synchronous part: if not already monitoring, post the monitor task on the
    /// engine and return the initial-state receiver; the caller then awaits
    /// [`InnerNet::wait_for_initial_state`] outside the lock.
    pub fn begin(&self) -> Result<watch::Receiver<bool>, NetError> {
        let mut state = self.lock_state()?;
        if let Some(monitor) = state.monitor.as_ref() {
            // Already monitoring; reuse its initial-state receiver.
            Ok(monitor.initial_state.clone())
        } else {
            Ok(self.spawn_monitor_task(&mut state))
        }
    }

    /// Post the long-lived monitor task on the engine's async lane and return
    /// the initial-state receiver.
    fn spawn_monitor_task(&self, state: &mut MonitorState) -> watch::Receiver<bool> {
        let (stop_sender, stop_receiver) = oneshot::channel();
        let (initial_state_sender, initial_state) = watch::channel(false);

        let shared_state = Arc::clone(&self.state);
        let dispatcher = self.dispatcher();

        self.engine.post(Self::monitor_until_stopped(
            shared_state,
            dispatcher,
            stop_receiver,
            initial_state_sender,
        ));

        state.monitor = Some(MonitorRuntime {
            stop_sender,
            initial_state: initial_state.clone(),
        });
        initial_state
    }

    /// Build a dispatcher that delivers a single listener callback to the
    /// engine callback thread pool.
    fn dispatcher(&self) -> Dispatcher {
        let callback = self.engine.executor().callback();
        Arc::new(move |listener: SharedListener, status: NetworkStatus| {
            callback.execute(move || listener(status));
        })
    }

    pub async fn wait_for_initial_state(mut initial_state: watch::Receiver<bool>) {
        while !*initial_state.borrow_and_update() {
            if initial_state.changed().await.is_err() {
                break;
            }
        }
    }

    /// Stop network monitoring and destroy the engine, releasing all resources
    /// created by `start`. Redundant calls are ignored.
    ///
    /// The engine is destroyed on a best-effort basis even if an internal lock
    /// is poisoned; the lock error is returned to the caller, but engine
    /// resources are still released, keeping the logic self-contained.
    pub fn shutdown(&self) -> Result<(), NetError> {
        // Collect the result of the lock operations first, but destroy the
        // engine regardless of success or failure.
        let lock_result = (|| -> Result<(), NetError> {
            let monitor = self.lock_state()?.monitor.take();
            if let Some(monitor) = monitor {
                let _ = monitor.stop_sender.send(());
            }
            // Silently reset the state; no callbacks are fired.
            self.lock_state()?.reachability = NetworkStatus::Unavailable;
            Ok(())
        })();

        // Destroy the engine: this cancels the monitor task on the async lane
        // and reclaims runtime resources. A developer-supplied external runtime
        // is not closed (see vibe-ready semantics). Destroy runs regardless of
        // whether the lock operations above failed, ensuring resources are
        // released.
        self.engine.destroy(|_result| {});

        lock_result
    }

    /// Query whether the network is currently available. Returns
    /// [`NetError::Lock`] on poison.
    pub fn local_network_reachability(&self) -> Result<NetworkStatus, NetError> {
        #[cfg(target_os = "windows")]
        if let Some(reachability) = Self::windows_network_reachability() {
            self.update_reachability(reachability)?;
            return Ok(reachability);
        }

        Ok(self.lock_state()?.reachability)
    }

    /// Register a network notification listener; multiple may be registered.
    /// Callbacks are executed on the engine callback thread pool.
    pub fn register(
        &self,
        listener: NetworkStatusListener,
    ) -> Result<NetworkStatusListenerHandle, NetError> {
        let mut state = self.lock_state()?;
        let handle = state.next_listener_handle();
        state.listeners.insert(handle, Arc::from(listener));
        Ok(handle)
    }

    /// Unregister a network notification listener by handle. Returns
    /// [`NetError::Lock`] on poison.
    pub fn unregister(&self, handle: NetworkStatusListenerHandle) -> Result<bool, NetError> {
        Ok(self.lock_state()?.listeners.remove(&handle).is_some())
    }

    /// Clear all registered network listeners.
    pub fn clear_all_listener(&self) -> Result<(), NetError> {
        self.lock_state()?.listeners.clear();
        Ok(())
    }

    /// Query the name of the network the host is currently connected to.
    ///
    /// On Windows the connected Wi-Fi SSID is preferred, falling back to the
    /// `NetworkListManager` connected-network name. On other platforms no name
    /// is currently resolvable, so `Ok(None)` is returned. This call inspects
    /// the operating system directly and does not touch the instance lock, so
    /// it never returns [`NetError::Lock`]; the `Result` is kept for API
    /// symmetry with the other state-touching methods.
    pub fn get_current_network_name(&self) -> Result<Option<String>, NetError> {
        #[cfg(target_os = "windows")]
        {
            Ok(Self::query_current_network())
        }

        #[cfg(not(target_os = "windows"))]
        {
            Ok(None)
        }
    }

    // ------------------------------------------------------------------
    // Monitor task and reachability computation
    // ------------------------------------------------------------------

    fn reachability_from_state(state: &netwatch::netmon::State) -> NetworkStatus {
        if state.default_route_interface.is_some() && (state.have_v4 || state.have_v6) {
            NetworkStatus::Available
        } else {
            NetworkStatus::Unavailable
        }
    }

    fn current_reachability(state: &netwatch::netmon::State) -> NetworkStatus {
        #[cfg(target_os = "windows")]
        if let Some(reachability) = Self::windows_network_reachability() {
            return reachability;
        }

        Self::reachability_from_state(state)
    }

    /// Update reachability and, when it changes, dispatch all listener
    /// callbacks on the callback thread pool.
    fn update_reachability(&self, reachability: NetworkStatus) -> Result<(), NetError> {
        Self::update_reachability_inner(&self.state, &self.dispatcher(), reachability)
    }

    /// Static version used by the monitor task (which only holds an
    /// `Arc<Mutex<MonitorState>>` and the dispatcher).
    ///
    /// Returns [`NetError::Lock`] on poison, leaving handling to the caller;
    /// never panics.
    fn update_reachability_inner(
        state: &Arc<Mutex<MonitorState>>,
        dispatcher: &Dispatcher,
        reachability: NetworkStatus,
    ) -> Result<(), NetError> {
        let listeners = {
            let mut guard = state.lock().map_err(NetError::from_poison)?;
            if guard.reachability == reachability {
                return Ok(());
            }
            guard.reachability = reachability;
            guard.listeners.values().cloned().collect::<Vec<_>>()
        };

        log_s!(
            "network_status_listener",
            "network_status",
            reachability.name()
        );

        for listener in listeners {
            dispatcher(listener, reachability);
        }
        Ok(())
    }

    /// Monitor task body: ported from the reference project's
    /// `monitor_until_stopped`, but the state comes from the instance rather
    /// than a global.
    ///
    /// This task runs on the engine's async lane and cannot return errors to
    /// the developer; if an internal lock becomes poisoned
    /// (`update_reachability_inner` returns `Err`), the task gracefully exits
    /// the loop and resets the state, and never panics.
    async fn monitor_until_stopped(
        state: Arc<Mutex<MonitorState>>,
        dispatcher: Dispatcher,
        mut stop_receiver: oneshot::Receiver<()>,
        initial_state: watch::Sender<bool>,
    ) {
        let Ok(monitor) = netwatch::netmon::Monitor::new().await else {
            let _ =
                Self::update_reachability_inner(&state, &dispatcher, NetworkStatus::Unavailable);
            let _ = initial_state.send(true);
            return;
        };
        let mut interface_state = monitor.interface_state();

        let current = Self::current_reachability(&interface_state.get());
        // If the initial state update fails (lock poisoned), end the task.
        if Self::update_reachability_inner(&state, &dispatcher, current).is_err() {
            let _ = initial_state.send(true);
            return;
        }
        let _ = initial_state.send(true);

        let mut refresh_interval = time::interval(Duration::from_secs(2));
        refresh_interval.set_missed_tick_behavior(MissedTickBehavior::Skip);

        loop {
            tokio::select! {
                _ = &mut stop_receiver => break,
                update = interface_state.updated() => {
                    match update {
                        Ok(new_state) => {
                            let reachability = Self::current_reachability(&new_state);
                            // Exit the monitor loop if the lock is poisoned.
                            if Self::update_reachability_inner(&state, &dispatcher, reachability).is_err() {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }
                _ = refresh_interval.tick() => {
                    let reachability = Self::current_reachability(&interface_state.get());
                    if Self::update_reachability_inner(&state, &dispatcher, reachability).is_err() {
                        break;
                    }
                }
            }
        }

        // The task is exiting; silently reset the state. If the lock is
        // poisoned it cannot be reset, so just give up (without panicking).
        if let Ok(mut guard) = state.lock() {
            guard.reachability = NetworkStatus::Unavailable;
        }
    }

    // ------------------------------------------------------------------
    // Windows network reachability (based on the NetworkListManager COM API)
    // ------------------------------------------------------------------

    #[cfg(target_os = "windows")]
    fn reachability_from_windows_connectivity(
        connectivity: windows::Win32::Networking::NetworkListManager::NLM_CONNECTIVITY,
    ) -> NetworkStatus {
        use windows::Win32::Networking::NetworkListManager::{
            NLM_CONNECTIVITY_IPV4_INTERNET, NLM_CONNECTIVITY_IPV6_INTERNET,
        };

        if connectivity.0 & NLM_CONNECTIVITY_IPV4_INTERNET.0 != 0
            || connectivity.0 & NLM_CONNECTIVITY_IPV6_INTERNET.0 != 0
        {
            NetworkStatus::Available
        } else {
            NetworkStatus::Unavailable
        }
    }

    #[cfg(target_os = "windows")]
    fn windows_network_reachability() -> Option<NetworkStatus> {
        use windows::Win32::{
            Networking::NetworkListManager::{INetworkListManager, NetworkListManager},
            System::Com::{
                CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED,
            },
        };

        unsafe {
            let com_initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
            let reachability = (|| {
                let manager: INetworkListManager =
                    CoCreateInstance(&NetworkListManager, None, CLSCTX_ALL).ok()?;
                let connectivity = manager.GetConnectivity().ok()?;
                Some(Self::reachability_from_windows_connectivity(connectivity))
            })();

            if com_initialized {
                CoUninitialize();
            }

            reachability
        }
    }

    // ------------------------------------------------------------------
    // Windows connected-network name (Wi-Fi SSID + NetworkListManager)
    // ------------------------------------------------------------------

    /// Resolve the name of the currently connected network on Windows.
    ///
    /// Prefers the active Wi-Fi SSID; if that is unavailable, falls back to the
    /// `NetworkListManager` connected-network name. Returns `None` when no
    /// connected network can be resolved.
    #[cfg(target_os = "windows")]
    fn query_current_network() -> Option<String> {
        Self::query_wifi_network().or_else(Self::query_windows_connected_network)
    }

    /// Query the active Wi-Fi SSID via `netsh wlan show interfaces`.
    #[cfg(target_os = "windows")]
    fn query_wifi_network() -> Option<String> {
        use std::process::Command;

        let output = Command::new("netsh")
            .args(["wlan", "show", "interfaces"])
            .output()
            .ok()?;

        if !output.status.success() {
            return None;
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        Self::parse_netsh_wifi_ssid(&stdout)
    }

    /// Extract the `SSID` value from `netsh wlan show interfaces` output,
    /// ignoring the `BSSID` line and any empty value.
    #[cfg(target_os = "windows")]
    fn parse_netsh_wifi_ssid(output: &str) -> Option<String> {
        output.lines().find_map(|line| {
            let (key, value) = line.split_once(':')?;
            let key = key.trim();
            if key.eq_ignore_ascii_case("SSID") && !key.eq_ignore_ascii_case("BSSID") {
                let name = value.trim();
                if !name.is_empty() {
                    return Some(name.to_string());
                }
            }
            None
        })
    }

    /// Query the first connected network's name via the `NetworkListManager`
    /// COM API. COM is uninitialized on every exit path via an RAII guard, even
    /// on early returns.
    #[cfg(target_os = "windows")]
    fn query_windows_connected_network() -> Option<String> {
        use windows::Win32::Foundation::RPC_E_CHANGED_MODE;
        use windows::Win32::Networking::NetworkListManager::{
            INetworkListManager, NetworkListManager, NLM_ENUM_NETWORK_CONNECTED,
        };
        use windows::Win32::System::Com::{
            CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_MULTITHREADED,
        };

        struct CoUninit(bool);
        impl Drop for CoUninit {
            fn drop(&mut self) {
                if self.0 {
                    unsafe { CoUninitialize() };
                }
            }
        }

        let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
        let should_uninit = hr.is_ok();
        // `RPC_E_CHANGED_MODE` means COM is already initialized with a different
        // model on this thread; the existing apartment is reused and must not be
        // uninitialized here. Any other failure is fatal to this query.
        if hr.is_err() && hr != RPC_E_CHANGED_MODE {
            return None;
        }
        let _co_guard = CoUninit(should_uninit);

        unsafe {
            let nlm: INetworkListManager =
                CoCreateInstance(&NetworkListManager, None, CLSCTX_ALL).ok()?;
            let networks = nlm.GetNetworks(NLM_ENUM_NETWORK_CONNECTED).ok()?;
            let mut fetched = 0;
            let mut items = [None];
            networks.Next(&mut items, Some(&mut fetched)).ok()?;
            if fetched == 0 {
                return None;
            }

            let name = items[0].as_ref()?.GetName().ok()?.to_string();
            if name.trim().is_empty() {
                return None;
            }

            Some(name)
        }
    }

    /// Install (or clear, with `None`) a listener that receives the engine's
    /// internal log records. Forwarded straight to the engine; the callback runs
    /// on the engine's logging path.
    pub fn set_log_listener(&self, listener: Option<VibeLogListener>) {
        self.engine.set_log_listener(listener)
    }
}