use std::ffi::{c_int, c_void};
use std::io::{self, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr::{self, NonNull};
use super::super::refresh_trigger::RefreshTrigger;
#[cfg(test)]
#[path = "macos_tests.rs"]
mod tests;
type NativeCallback = unsafe extern "C" fn(*mut c_void);
unsafe extern "C" {
fn open_net_path_monitor_start(
notify: Option<NativeCallback>,
context: *mut c_void,
output: *mut *mut c_void,
) -> c_int;
fn open_net_path_monitor_stop(monitor: *mut c_void);
}
#[derive(Clone, Copy, Debug)]
struct NativeApi {
start: unsafe extern "C" fn(Option<NativeCallback>, *mut c_void, *mut *mut c_void) -> c_int,
stop: unsafe extern "C" fn(*mut c_void),
}
#[derive(Debug)]
pub(crate) struct NativeNetworkMonitor {
handle: NonNull<c_void>,
api: NativeApi,
_trigger: Box<RefreshTrigger>,
}
unsafe impl Send for NativeNetworkMonitor {}
unsafe impl Sync for NativeNetworkMonitor {}
impl NativeNetworkMonitor {
pub(crate) fn start(trigger: RefreshTrigger) -> io::Result<Self> {
Self::start_with(
trigger,
NativeApi {
start: open_net_path_monitor_start,
stop: open_net_path_monitor_stop,
},
)
}
fn start_with(trigger: RefreshTrigger, api: NativeApi) -> io::Result<Self> {
let trigger = Box::new(trigger);
let context = ptr::from_ref(trigger.as_ref()).cast_mut().cast();
let mut handle = ptr::null_mut();
let status = unsafe { (api.start)(Some(notify), context, &mut handle) };
if status != 0 {
if !handle.is_null() {
unsafe { (api.stop)(handle) };
}
return Err(io::Error::other(format!(
"macOS network-change monitor initialization failed (native status {status})"
)));
}
let handle = NonNull::new(handle).ok_or_else(|| {
io::Error::other("macOS network-change monitor returned a null handle")
})?;
Ok(Self {
handle,
api,
_trigger: trigger,
})
}
}
impl Drop for NativeNetworkMonitor {
fn drop(&mut self) {
unsafe { (self.api.stop)(self.handle.as_ptr()) };
}
}
unsafe extern "C" fn notify(context: *mut c_void) {
if context.is_null() {
return;
}
let result = catch_unwind(AssertUnwindSafe(|| {
let trigger = unsafe { &*context.cast::<RefreshTrigger>() };
let _ = trigger.notify();
}));
if result.is_err() {
let _ = io::stderr()
.lock()
.write_all(b"open-net: macOS network-change callback failed\n");
}
}