M1 primary view: wx-rs patched+extended (Linux/GTK3 build, widget bridge), vendored wx 3.3.3 + asic-rs in thirdparty/, UI-SPEC table+KPIs+dialogs, build scripts
This commit is contained in:
+301
@@ -0,0 +1,301 @@
|
||||
// Copyright 2017 Amagicom AB.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! Bindings to [`SCDynamicStore`].
|
||||
//!
|
||||
//! See the examples directory for examples how to use this module.
|
||||
//!
|
||||
//! [`SCDynamicStore`]: https://developer.apple.com/documentation/systemconfiguration/scdynamicstore?language=objc
|
||||
|
||||
use crate::sys::{
|
||||
dynamic_store::{
|
||||
kSCDynamicStoreUseSessionKeys, SCDynamicStoreCallBack, SCDynamicStoreContext,
|
||||
SCDynamicStoreCopyKeyList, SCDynamicStoreCopyValue, SCDynamicStoreCreateRunLoopSource,
|
||||
SCDynamicStoreCreateWithOptions, SCDynamicStoreGetTypeID, SCDynamicStoreRef,
|
||||
SCDynamicStoreRemoveValue, SCDynamicStoreSetNotificationKeys, SCDynamicStoreSetValue,
|
||||
},
|
||||
dynamic_store_copy_specific::SCDynamicStoreCopyProxies,
|
||||
};
|
||||
use core_foundation::{
|
||||
array::{CFArray, CFArrayRef},
|
||||
base::{kCFAllocatorDefault, CFType, TCFType},
|
||||
boolean::CFBoolean,
|
||||
dictionary::CFDictionary,
|
||||
propertylist::{CFPropertyList, CFPropertyListSubClass},
|
||||
runloop::CFRunLoopSource,
|
||||
string::CFString,
|
||||
};
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
/// Struct describing the callback happening when a watched value in the dynamic store is changed.
|
||||
pub struct SCDynamicStoreCallBackContext<T> {
|
||||
/// The callback function that will be called when a watched value in the dynamic store is
|
||||
/// changed.
|
||||
pub callout: SCDynamicStoreCallBackT<T>,
|
||||
|
||||
/// The argument passed to each `callout` call. Can be used to keep state between
|
||||
/// callbacks.
|
||||
pub info: T,
|
||||
}
|
||||
|
||||
/// Signature for callback functions getting called when a watched value in the dynamic store is
|
||||
/// changed.
|
||||
///
|
||||
/// This is the safe callback definition, abstracting over the lower level `SCDynamicStoreCallBack`
|
||||
/// from the `system-configuration-sys` crate.
|
||||
pub type SCDynamicStoreCallBackT<T> =
|
||||
fn(store: SCDynamicStore, changed_keys: CFArray<CFString>, info: &mut T);
|
||||
|
||||
/// Builder for [`SCDynamicStore`] sessions.
|
||||
///
|
||||
/// [`SCDynamicStore`]: struct.SCDynamicStore.html
|
||||
pub struct SCDynamicStoreBuilder<T> {
|
||||
name: CFString,
|
||||
session_keys: bool,
|
||||
callback_context: Option<SCDynamicStoreCallBackContext<T>>,
|
||||
}
|
||||
|
||||
impl SCDynamicStoreBuilder<()> {
|
||||
/// Creates a new builder. `name` is used as the name parameter when creating the
|
||||
/// [`SCDynamicStore`] session.
|
||||
///
|
||||
/// [`SCDynamicStore`]: struct.SCDynamicStore.html
|
||||
pub fn new<S: Into<CFString>>(name: S) -> Self {
|
||||
SCDynamicStoreBuilder {
|
||||
name: name.into(),
|
||||
session_keys: false,
|
||||
callback_context: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SCDynamicStoreBuilder<T> {
|
||||
/// Set wether or not the created [`SCDynamicStore`] should have session keys or not.
|
||||
/// See [`SCDynamicStoreCreateWithOptions`] for details.
|
||||
///
|
||||
/// Defaults to `false`.
|
||||
///
|
||||
/// [`SCDynamicStore`]: struct.SCDynamicStore.html
|
||||
/// [`SCDynamicStoreCreateWithOptions`]: https://developer.apple.com/documentation/systemconfiguration/1437818-scdynamicstorecreatewithoptions?language=objc
|
||||
pub fn session_keys(mut self, session_keys: bool) -> Self {
|
||||
self.session_keys = session_keys;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set a callback context (callback function and data to pass to each callback call).
|
||||
///
|
||||
/// Defaults to having callbacks disabled.
|
||||
pub fn callback_context<T2>(
|
||||
self,
|
||||
callback_context: SCDynamicStoreCallBackContext<T2>,
|
||||
) -> SCDynamicStoreBuilder<T2> {
|
||||
SCDynamicStoreBuilder {
|
||||
name: self.name,
|
||||
session_keys: self.session_keys,
|
||||
callback_context: Some(callback_context),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the dynamic store session.
|
||||
pub fn build(mut self) -> SCDynamicStore {
|
||||
let store_options = self.create_store_options();
|
||||
if let Some(callback_context) = self.callback_context.take() {
|
||||
SCDynamicStore::create(
|
||||
&self.name,
|
||||
&store_options,
|
||||
Some(convert_callback::<T>),
|
||||
&mut self.create_context(callback_context),
|
||||
)
|
||||
} else {
|
||||
SCDynamicStore::create(&self.name, &store_options, None, ptr::null_mut())
|
||||
}
|
||||
}
|
||||
|
||||
fn create_store_options(&self) -> CFDictionary {
|
||||
let key = unsafe { CFString::wrap_under_create_rule(kSCDynamicStoreUseSessionKeys) };
|
||||
let value = CFBoolean::from(self.session_keys);
|
||||
let typed_dict = CFDictionary::from_CFType_pairs(&[(key, value)]);
|
||||
unsafe { CFDictionary::wrap_under_get_rule(typed_dict.as_concrete_TypeRef()) }
|
||||
}
|
||||
|
||||
fn create_context(
|
||||
&self,
|
||||
callback_context: SCDynamicStoreCallBackContext<T>,
|
||||
) -> SCDynamicStoreContext {
|
||||
// move the callback context struct to the heap and "forget" it.
|
||||
// It will later be brought back into the Rust typesystem and freed in
|
||||
// `release_callback_context`
|
||||
let info_ptr = Box::into_raw(Box::new(callback_context));
|
||||
|
||||
SCDynamicStoreContext {
|
||||
version: 0,
|
||||
info: info_ptr as *mut _ as *mut c_void,
|
||||
retain: None,
|
||||
release: Some(release_callback_context::<T>),
|
||||
copyDescription: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
declare_TCFType! {
|
||||
/// Access to the key-value pairs in the dynamic store of a running system.
|
||||
///
|
||||
/// Use the [`SCDynamicStoreBuilder`] to create instances of this.
|
||||
///
|
||||
/// [`SCDynamicStoreBuilder`]: struct.SCDynamicStoreBuilder.html
|
||||
SCDynamicStore, SCDynamicStoreRef
|
||||
}
|
||||
|
||||
impl_TCFType!(SCDynamicStore, SCDynamicStoreRef, SCDynamicStoreGetTypeID);
|
||||
|
||||
impl SCDynamicStore {
|
||||
/// Creates a new session used to interact with the dynamic store maintained by the System
|
||||
/// Configuration server.
|
||||
fn create(
|
||||
name: &CFString,
|
||||
store_options: &CFDictionary,
|
||||
callout: SCDynamicStoreCallBack,
|
||||
context: *mut SCDynamicStoreContext,
|
||||
) -> Self {
|
||||
unsafe {
|
||||
let store = SCDynamicStoreCreateWithOptions(
|
||||
kCFAllocatorDefault,
|
||||
name.as_concrete_TypeRef(),
|
||||
store_options.as_concrete_TypeRef(),
|
||||
callout,
|
||||
context,
|
||||
);
|
||||
SCDynamicStore::wrap_under_create_rule(store)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the keys that represent the current dynamic store entries that match the specified
|
||||
/// pattern. Or `None` if an error occured.
|
||||
///
|
||||
/// `pattern` - A regular expression pattern used to match the dynamic store keys.
|
||||
pub fn get_keys<S: Into<CFString>>(&self, pattern: S) -> Option<CFArray<CFString>> {
|
||||
let cf_pattern = pattern.into();
|
||||
unsafe {
|
||||
let array_ref = SCDynamicStoreCopyKeyList(
|
||||
self.as_concrete_TypeRef(),
|
||||
cf_pattern.as_concrete_TypeRef(),
|
||||
);
|
||||
if !array_ref.is_null() {
|
||||
Some(CFArray::wrap_under_create_rule(array_ref))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the key-value pairs that represent the current internet proxy settings. Or `None` if
|
||||
/// no proxy settings have been defined or if an error occured.
|
||||
pub fn get_proxies(&self) -> Option<CFDictionary<CFString, CFType>> {
|
||||
unsafe {
|
||||
let dictionary_ref = SCDynamicStoreCopyProxies(self.as_concrete_TypeRef());
|
||||
if !dictionary_ref.is_null() {
|
||||
Some(CFDictionary::wrap_under_create_rule(dictionary_ref))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// If the given key exists in the store, the associated value is returned.
|
||||
///
|
||||
/// Use `CFPropertyList::downcast_into` to cast the result into the correct type.
|
||||
pub fn get<S: Into<CFString>>(&self, key: S) -> Option<CFPropertyList> {
|
||||
let cf_key = key.into();
|
||||
unsafe {
|
||||
let dict_ref =
|
||||
SCDynamicStoreCopyValue(self.as_concrete_TypeRef(), cf_key.as_concrete_TypeRef());
|
||||
if !dict_ref.is_null() {
|
||||
Some(CFPropertyList::wrap_under_create_rule(dict_ref))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the value of the given key. Overwrites existing values.
|
||||
/// Returns `true` on success, false on failure.
|
||||
pub fn set<S: Into<CFString>, V: CFPropertyListSubClass>(&self, key: S, value: V) -> bool {
|
||||
self.set_raw(key, &value.into_CFPropertyList())
|
||||
}
|
||||
|
||||
/// Sets the value of the given key. Overwrites existing values.
|
||||
/// Returns `true` on success, false on failure.
|
||||
pub fn set_raw<S: Into<CFString>>(&self, key: S, value: &CFPropertyList) -> bool {
|
||||
let cf_key = key.into();
|
||||
let success = unsafe {
|
||||
SCDynamicStoreSetValue(
|
||||
self.as_concrete_TypeRef(),
|
||||
cf_key.as_concrete_TypeRef(),
|
||||
value.as_concrete_TypeRef(),
|
||||
)
|
||||
};
|
||||
success != 0
|
||||
}
|
||||
|
||||
/// Removes the value of the specified key from the dynamic store.
|
||||
pub fn remove<S: Into<CFString>>(&self, key: S) -> bool {
|
||||
let cf_key = key.into();
|
||||
let success = unsafe {
|
||||
SCDynamicStoreRemoveValue(self.as_concrete_TypeRef(), cf_key.as_concrete_TypeRef())
|
||||
};
|
||||
success != 0
|
||||
}
|
||||
|
||||
/// Specifies a set of keys and key patterns that should be monitored for changes.
|
||||
pub fn set_notification_keys<T1, T2>(
|
||||
&self,
|
||||
keys: &CFArray<T1>,
|
||||
patterns: &CFArray<T2>,
|
||||
) -> bool {
|
||||
let success = unsafe {
|
||||
SCDynamicStoreSetNotificationKeys(
|
||||
self.as_concrete_TypeRef(),
|
||||
keys.as_concrete_TypeRef(),
|
||||
patterns.as_concrete_TypeRef(),
|
||||
)
|
||||
};
|
||||
success != 0
|
||||
}
|
||||
|
||||
/// Creates a run loop source object that can be added to the application's run loop.
|
||||
pub fn create_run_loop_source(&self) -> CFRunLoopSource {
|
||||
unsafe {
|
||||
let run_loop_source_ref = SCDynamicStoreCreateRunLoopSource(
|
||||
kCFAllocatorDefault,
|
||||
self.as_concrete_TypeRef(),
|
||||
0,
|
||||
);
|
||||
CFRunLoopSource::wrap_under_create_rule(run_loop_source_ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw callback used by the safe `SCDynamicStore` to convert from the `SCDynamicStoreCallBack`
|
||||
/// to the `SCDynamicStoreCallBackT`
|
||||
unsafe extern "C" fn convert_callback<T>(
|
||||
store_ref: SCDynamicStoreRef,
|
||||
changed_keys_ref: CFArrayRef,
|
||||
context_ptr: *mut c_void,
|
||||
) {
|
||||
let store = SCDynamicStore::wrap_under_get_rule(store_ref);
|
||||
let changed_keys = CFArray::<CFString>::wrap_under_get_rule(changed_keys_ref);
|
||||
let context = &mut *(context_ptr as *mut _ as *mut SCDynamicStoreCallBackContext<T>);
|
||||
|
||||
(context.callout)(store, changed_keys, &mut context.info);
|
||||
}
|
||||
|
||||
// Release function called by core foundation on release of the dynamic store context.
|
||||
unsafe extern "C" fn release_callback_context<T>(context_ptr: *const c_void) {
|
||||
// Bring back the context object from raw ptr so it is correctly freed.
|
||||
let _context = Box::from_raw(context_ptr as *mut SCDynamicStoreCallBackContext<T>);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
// Copyright 2017 Amagicom AB.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! # SystemConfiguration bindings
|
||||
//!
|
||||
//! This crate is a high level binding to the Apple [SystemConfiguration] framework. For low level
|
||||
//! FFI bindings, check out the [`system-configuration-sys`] crate.
|
||||
//!
|
||||
//! This crate only implements a small part of the [SystemConfiguration] framework so far. If you
|
||||
//! need a yet unimplemented part, feel free to submit a pull request!
|
||||
//!
|
||||
//! [SystemConfiguration]: https://developer.apple.com/documentation/systemconfiguration?language=objc
|
||||
//! [`system-configuration-sys`]: https://crates.io/crates/system-configuration-sys
|
||||
|
||||
#![deny(missing_docs)]
|
||||
|
||||
/// CoreFoundation wrappers
|
||||
#[macro_use]
|
||||
pub extern crate core_foundation;
|
||||
/// Low-level SystemConfiguration bindings
|
||||
pub extern crate system_configuration_sys as sys;
|
||||
|
||||
pub mod dynamic_store;
|
||||
pub mod network_configuration;
|
||||
pub mod network_reachability;
|
||||
pub mod preferences;
|
||||
@@ -0,0 +1,347 @@
|
||||
//! Bindings for [`SCNetworkConfiguration`].
|
||||
//!
|
||||
//! [`SCNetworkConfiguration`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkconfiguration?language=objc
|
||||
use core_foundation::{
|
||||
array::CFArray,
|
||||
base::{TCFType, ToVoid},
|
||||
string::CFString,
|
||||
};
|
||||
use system_configuration_sys::network_configuration::{
|
||||
SCNetworkInterfaceCopyAll, SCNetworkInterfaceGetBSDName, SCNetworkInterfaceGetInterfaceType,
|
||||
SCNetworkInterfaceGetLocalizedDisplayName, SCNetworkInterfaceGetTypeID, SCNetworkInterfaceRef,
|
||||
SCNetworkServiceCopyAll, SCNetworkServiceGetEnabled, SCNetworkServiceGetInterface,
|
||||
SCNetworkServiceGetServiceID, SCNetworkServiceGetTypeID, SCNetworkServiceRef,
|
||||
SCNetworkSetCopyCurrent, SCNetworkSetGetServiceOrder, SCNetworkSetGetTypeID, SCNetworkSetRef,
|
||||
};
|
||||
|
||||
use crate::preferences::SCPreferences;
|
||||
|
||||
core_foundation::declare_TCFType!(
|
||||
/// Represents a network interface.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceRef`] and its [methods] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceRef`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkinterfaceref?language=objc
|
||||
/// [methods]: https://developer.apple.com/documentation/systemconfiguration/scnetworkconfiguration?language=objc
|
||||
SCNetworkInterface,
|
||||
SCNetworkInterfaceRef
|
||||
);
|
||||
core_foundation::impl_TCFType!(
|
||||
SCNetworkInterface,
|
||||
SCNetworkInterfaceRef,
|
||||
SCNetworkInterfaceGetTypeID
|
||||
);
|
||||
|
||||
// TODO: implement all the other methods a SCNetworkInterface has
|
||||
impl SCNetworkInterface {
|
||||
/// Get type of the network interface, if the type is recognized, returns `None` otherwise.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceGetInterfaceType`] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceGetInterfaceType`]: https://developer.apple.com/documentation/systemconfiguration/1517371-scnetworkinterfacegetinterfacety?language=objc
|
||||
pub fn interface_type(&self) -> Option<SCNetworkInterfaceType> {
|
||||
SCNetworkInterfaceType::from_cfstring(&self.interface_type_string()?)
|
||||
}
|
||||
|
||||
/// Returns the raw interface type identifier.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceGetInterfaceType`] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceGetInterfaceType`]: https://developer.apple.com/documentation/systemconfiguration/1517371-scnetworkinterfacegetinterfacety?language=objc
|
||||
pub fn interface_type_string(&self) -> Option<CFString> {
|
||||
unsafe {
|
||||
let ptr = SCNetworkInterfaceGetInterfaceType(self.0);
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(CFString::wrap_under_get_rule(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the _BSD_ name for the interface, such as `en0`.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceGetBSDName`] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceGetBSDName`]: https://developer.apple.com/documentation/systemconfiguration/1516854-scnetworkinterfacegetbsdname?language=objc
|
||||
pub fn bsd_name(&self) -> Option<CFString> {
|
||||
unsafe {
|
||||
let ptr = SCNetworkInterfaceGetBSDName(self.0);
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(CFString::wrap_under_get_rule(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the localized display name for the interface.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceGetLocalizedDisplayName`] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceGetLocalizedDisplayName`]: https://developer.apple.com/documentation/systemconfiguration/1517060-scnetworkinterfacegetlocalizeddi?language=objc
|
||||
pub fn display_name(&self) -> Option<CFString> {
|
||||
unsafe {
|
||||
let ptr = SCNetworkInterfaceGetLocalizedDisplayName(self.0);
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(CFString::wrap_under_get_rule(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the possible network interface types.
|
||||
///
|
||||
/// See [_Network Interface Types_] documentation for details.
|
||||
///
|
||||
/// [_Network Interface Types_]: https://developer.apple.com/documentation/systemconfiguration/scnetworkconfiguration/network_interface_types?language=objc
|
||||
#[derive(Debug)]
|
||||
pub enum SCNetworkInterfaceType {
|
||||
/// A 6to4 interface.
|
||||
SixToFour,
|
||||
/// Bluetooth interface.
|
||||
Bluetooth,
|
||||
/// Bridge interface.
|
||||
Bridge,
|
||||
/// Ethernet bond interface.
|
||||
Bond,
|
||||
/// Ethernet interface.
|
||||
Ethernet,
|
||||
/// FireWire interface.
|
||||
FireWire,
|
||||
/// IEEE80211 interface.
|
||||
IEEE80211,
|
||||
/// IPSec interface.
|
||||
IPSec,
|
||||
/// IrDA interface.
|
||||
IrDA,
|
||||
/// L2TP interface.
|
||||
L2TP,
|
||||
/// Modem interface.
|
||||
Modem,
|
||||
/// PPP interface.
|
||||
PPP,
|
||||
/// PPTP interface.
|
||||
///
|
||||
/// Deprecated, one should use the PPP variant.
|
||||
PPTP,
|
||||
/// Serial interface.
|
||||
Serial,
|
||||
/// VLAN interface.
|
||||
VLAN,
|
||||
/// WWAN interface.
|
||||
WWAN,
|
||||
/// IPv4 interface.
|
||||
IPv4,
|
||||
}
|
||||
|
||||
impl SCNetworkInterfaceType {
|
||||
/// Tries to construct a type by matching it to string constants used to identify a network
|
||||
/// interface type. If no constants match it, `None` is returned.
|
||||
pub fn from_cfstring(type_id: &CFString) -> Option<Self> {
|
||||
use system_configuration_sys::network_configuration::*;
|
||||
|
||||
let id_is_equal_to = |const_str| -> bool {
|
||||
let const_str = unsafe { CFString::wrap_under_get_rule(const_str) };
|
||||
&const_str == type_id
|
||||
};
|
||||
unsafe {
|
||||
if id_is_equal_to(kSCNetworkInterfaceType6to4) {
|
||||
Some(SCNetworkInterfaceType::SixToFour)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeBluetooth) {
|
||||
Some(SCNetworkInterfaceType::Bluetooth)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeBridge) {
|
||||
Some(SCNetworkInterfaceType::Bridge)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeBond) {
|
||||
Some(SCNetworkInterfaceType::Bond)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeEthernet) {
|
||||
Some(SCNetworkInterfaceType::Ethernet)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeFireWire) {
|
||||
Some(SCNetworkInterfaceType::FireWire)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeIEEE80211) {
|
||||
Some(SCNetworkInterfaceType::IEEE80211)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeIPSec) {
|
||||
Some(SCNetworkInterfaceType::IPSec)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeIrDA) {
|
||||
Some(SCNetworkInterfaceType::IrDA)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeL2TP) {
|
||||
Some(SCNetworkInterfaceType::L2TP)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeModem) {
|
||||
Some(SCNetworkInterfaceType::Modem)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypePPP) {
|
||||
Some(SCNetworkInterfaceType::PPP)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypePPTP) {
|
||||
Some(SCNetworkInterfaceType::PPTP)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeSerial) {
|
||||
Some(SCNetworkInterfaceType::Serial)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeVLAN) {
|
||||
Some(SCNetworkInterfaceType::VLAN)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeWWAN) {
|
||||
Some(SCNetworkInterfaceType::WWAN)
|
||||
} else if id_is_equal_to(kSCNetworkInterfaceTypeIPv4) {
|
||||
Some(SCNetworkInterfaceType::IPv4)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retrieve all current network interfaces
|
||||
///
|
||||
/// See [`SCNetworkInterfaceCopyAll`] for more details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceCopyAll`]: https://developer.apple.com/documentation/systemconfiguration/1517090-scnetworkinterfacecopyall?language=objc
|
||||
pub fn get_interfaces() -> CFArray<SCNetworkInterface> {
|
||||
unsafe { CFArray::<SCNetworkInterface>::wrap_under_create_rule(SCNetworkInterfaceCopyAll()) }
|
||||
}
|
||||
|
||||
core_foundation::declare_TCFType!(
|
||||
/// Represents a network service.
|
||||
///
|
||||
/// See [`SCNetworkInterfaceRef`] and its [methods] for details.
|
||||
///
|
||||
/// [`SCNetworkInterfaceRef`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkserviceref?language=objc
|
||||
/// [methods]: https://developer.apple.com/documentation/systemconfiguration/scnetworkconfiguration?language=objc
|
||||
SCNetworkService,
|
||||
SCNetworkServiceRef
|
||||
);
|
||||
|
||||
core_foundation::impl_TCFType!(
|
||||
SCNetworkService,
|
||||
SCNetworkServiceRef,
|
||||
SCNetworkServiceGetTypeID
|
||||
);
|
||||
|
||||
impl SCNetworkService {
|
||||
/// Returns an array of all network services
|
||||
pub fn get_services(prefs: &SCPreferences) -> CFArray<Self> {
|
||||
unsafe {
|
||||
let array_ptr = SCNetworkServiceCopyAll(prefs.to_void());
|
||||
if array_ptr.is_null() {
|
||||
return create_empty_array();
|
||||
}
|
||||
CFArray::<Self>::wrap_under_create_rule(array_ptr)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the network service is currently enabled
|
||||
pub fn enabled(&self) -> bool {
|
||||
unsafe { SCNetworkServiceGetEnabled(self.0) == 0 }
|
||||
}
|
||||
|
||||
/// Returns the network interface backing this network service, if it has one.
|
||||
pub fn network_interface(&self) -> Option<SCNetworkInterface> {
|
||||
unsafe {
|
||||
let ptr = SCNetworkServiceGetInterface(self.0);
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(SCNetworkInterface::wrap_under_get_rule(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the service identifier.
|
||||
pub fn id(&self) -> Option<CFString> {
|
||||
unsafe {
|
||||
let ptr = SCNetworkServiceGetServiceID(self.0);
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(CFString::wrap_under_get_rule(ptr))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core_foundation::declare_TCFType!(
|
||||
/// Represents a complete network configuration for a particular host.
|
||||
///
|
||||
/// See [`SCNetworkSet`] for details.
|
||||
///
|
||||
/// [`SCNetworkSet`]: https://developer.apple.com/documentation/systemconfiguration/scnetworksetref?language=objc
|
||||
SCNetworkSet,
|
||||
SCNetworkSetRef
|
||||
);
|
||||
|
||||
core_foundation::impl_TCFType!(SCNetworkSet, SCNetworkSetRef, SCNetworkSetGetTypeID);
|
||||
|
||||
impl SCNetworkSet {
|
||||
/// Constructs a new set of network services from the preferences.
|
||||
pub fn new(prefs: &SCPreferences) -> Self {
|
||||
let ptr = unsafe { SCNetworkSetCopyCurrent(prefs.to_void()) };
|
||||
unsafe { SCNetworkSet::wrap_under_create_rule(ptr) }
|
||||
}
|
||||
|
||||
/// Returns an list of network service identifiers, ordered by their priority.
|
||||
pub fn service_order(&self) -> CFArray<CFString> {
|
||||
unsafe {
|
||||
let array_ptr = SCNetworkSetGetServiceOrder(self.0);
|
||||
if array_ptr.is_null() {
|
||||
return create_empty_array();
|
||||
}
|
||||
CFArray::<CFString>::wrap_under_get_rule(array_ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_empty_array<T>() -> CFArray<T> {
|
||||
use std::ptr::null;
|
||||
unsafe {
|
||||
CFArray::wrap_under_create_rule(core_foundation::array::CFArrayCreate(
|
||||
null() as *const _,
|
||||
null() as *const _,
|
||||
0,
|
||||
null() as *const _,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_get_all_interfaces() {
|
||||
let _ = get_interfaces();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_type() {
|
||||
for iface in get_interfaces().into_iter() {
|
||||
if iface.interface_type().is_none() {
|
||||
panic!(
|
||||
"Interface {:?} ({:?}) has unrecognized type {:?}",
|
||||
iface.display_name(),
|
||||
iface.bsd_name(),
|
||||
iface.interface_type_string()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_service_order() {
|
||||
let prefs = SCPreferences::default(&CFString::new("test"));
|
||||
let services = SCNetworkService::get_services(&prefs);
|
||||
let set = SCNetworkSet::new(&prefs);
|
||||
let service_order = set.service_order();
|
||||
|
||||
assert!(service_order.iter().all(|service_id| {
|
||||
services
|
||||
.iter()
|
||||
.find(|service| service.id().as_ref() == Some(&*service_id))
|
||||
.is_some()
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_array() {
|
||||
let empty = create_empty_array::<CFString>();
|
||||
let values = empty.get_all_values();
|
||||
assert!(values.is_empty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
//! Bindings for [`SCNetworkReachability`]
|
||||
//!
|
||||
//! [`SCNetworkReachability`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d
|
||||
|
||||
use core_foundation::{
|
||||
base::{TCFType, ToVoid},
|
||||
runloop::CFRunLoop,
|
||||
string::{CFString, CFStringRef},
|
||||
};
|
||||
use system_configuration_sys::{
|
||||
libc,
|
||||
network_reachability::{
|
||||
kSCNetworkReachabilityFlagsConnectionOnDemand,
|
||||
kSCNetworkReachabilityFlagsConnectionOnTraffic,
|
||||
kSCNetworkReachabilityFlagsConnectionRequired,
|
||||
kSCNetworkReachabilityFlagsInterventionRequired, kSCNetworkReachabilityFlagsIsDirect,
|
||||
kSCNetworkReachabilityFlagsIsLocalAddress, kSCNetworkReachabilityFlagsIsWWAN,
|
||||
kSCNetworkReachabilityFlagsReachable, kSCNetworkReachabilityFlagsTransientConnection,
|
||||
SCNetworkReachabilityContext, SCNetworkReachabilityCreateWithAddress,
|
||||
SCNetworkReachabilityCreateWithAddressPair, SCNetworkReachabilityCreateWithName,
|
||||
SCNetworkReachabilityFlags, SCNetworkReachabilityGetFlags, SCNetworkReachabilityGetTypeID,
|
||||
SCNetworkReachabilityRef, SCNetworkReachabilityScheduleWithRunLoop,
|
||||
SCNetworkReachabilitySetCallback, SCNetworkReachabilityUnscheduleFromRunLoop,
|
||||
},
|
||||
};
|
||||
|
||||
use std::{
|
||||
error::Error,
|
||||
ffi::{c_void, CStr},
|
||||
fmt::{self, Display},
|
||||
net::SocketAddr,
|
||||
ptr,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
/// Failure to determine reachability
|
||||
#[derive(Debug)]
|
||||
pub enum ReachabilityError {
|
||||
/// `SCNetworkReachabilityGetFlags` call failed.
|
||||
FailedToDetermineReachability,
|
||||
/// `SCNetworkReachabilityGetFlags` call returned unrecognized flags.
|
||||
UnrecognizedFlags(u32),
|
||||
}
|
||||
|
||||
/// Failure to schedule a reachability callback on a runloop.
|
||||
#[derive(Debug)]
|
||||
pub struct SchedulingError(());
|
||||
|
||||
impl Display for SchedulingError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Failed to schedule a reachability callback on a runloop")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for SchedulingError {}
|
||||
|
||||
/// Failure to unschedule a reachability callback on a runloop.
|
||||
#[derive(Debug)]
|
||||
pub struct UnschedulingError(());
|
||||
|
||||
impl Display for UnschedulingError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"Failed to unschedule a reachability callback on a runloop"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for UnschedulingError {}
|
||||
|
||||
/// Failure to set a callback for changes in reachability.
|
||||
#[derive(Debug)]
|
||||
pub struct SetCallbackError {}
|
||||
|
||||
impl Display for SetCallbackError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Failed to set a callback for reachability")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for SetCallbackError {}
|
||||
|
||||
bitflags::bitflags! {
|
||||
/// Rustier interface for [`SCNetworkReachabilityFlags`].
|
||||
///
|
||||
/// [`SCNetworkReachability`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkreachabilityflags
|
||||
pub struct ReachabilityFlags: u32 {
|
||||
/// The specified node name or address can be reached via a transient connection, such as
|
||||
/// PPP.
|
||||
const TRANSIENT_CONNECTION = kSCNetworkReachabilityFlagsTransientConnection;
|
||||
/// The specified node name or address can be reached using the current network
|
||||
/// configuration.
|
||||
const REACHABLE = kSCNetworkReachabilityFlagsReachable;
|
||||
/// The specified node name or address can be reached using the current network
|
||||
/// configuration, but a connection must first be established. If this flag is set, the
|
||||
/// `CONNECTION_ON_TRAFFIC` flag, `CONNECTION_ON_DEMAND` flag, or `IS_WANN` flag is also
|
||||
/// typically set to indicate the type of connection required. If the user must manually
|
||||
/// make the connection, the `INTERVENTION_REQUIRED` flag is also set.
|
||||
const CONNECTION_REQUIRED = kSCNetworkReachabilityFlagsConnectionRequired;
|
||||
/// The specified node name or address can be reached using the current network
|
||||
/// configuration, but a connection must first be established. Any traffic directed to the
|
||||
/// specified name or address will initiate the connection.
|
||||
const CONNECTION_ON_TRAFFIC = kSCNetworkReachabilityFlagsConnectionOnTraffic;
|
||||
/// The specified node name or address can be reached using the current network
|
||||
/// configuration, but a connection must first be established.
|
||||
const INTERVENTION_REQUIRED = kSCNetworkReachabilityFlagsInterventionRequired;
|
||||
/// The specified node name or address can be reached using the current network
|
||||
/// configuration, but a connection must first be established.
|
||||
const CONNECTION_ON_DEMAND = kSCNetworkReachabilityFlagsConnectionOnDemand;
|
||||
/// The specified node name or address is one that is associated with a network interface on the current system.
|
||||
const IS_LOCAL_ADDRESS = kSCNetworkReachabilityFlagsIsLocalAddress;
|
||||
/// Network traffic to the specified node name or address will not go through a gateway, but
|
||||
/// is routed directly to one of the interfaces in the system.
|
||||
const IS_DIRECT = kSCNetworkReachabilityFlagsIsDirect;
|
||||
/// The specified node name or address can be reached via a cellular connection, such as EDGE or GPRS.
|
||||
const IS_WWAN = kSCNetworkReachabilityFlagsIsWWAN;
|
||||
}
|
||||
}
|
||||
|
||||
core_foundation::declare_TCFType!(
|
||||
/// A network address or host for which the connectivity can be determined.
|
||||
///
|
||||
/// See [`SCNetworkReachability`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachability`]: https://developer.apple.com/documentation/systemconfiguration/scnetworkreachability-g7d
|
||||
SCNetworkReachability,
|
||||
SCNetworkReachabilityRef
|
||||
);
|
||||
|
||||
core_foundation::impl_TCFType!(
|
||||
SCNetworkReachability,
|
||||
SCNetworkReachabilityRef,
|
||||
SCNetworkReachabilityGetTypeID
|
||||
);
|
||||
|
||||
impl SCNetworkReachability {
|
||||
/// Construct a SCNetworkReachability struct with a local and a remote socket address.
|
||||
///
|
||||
/// See [`SCNetworkReachabilityCreateWithAddressPair`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityCreateWithAddressPair`]: https://developer.apple.com/documentation/systemconfiguration/1514908-scnetworkreachabilitycreatewitha?language=objc
|
||||
pub fn from_addr_pair(local: SocketAddr, remote: SocketAddr) -> SCNetworkReachability {
|
||||
let ptr = unsafe {
|
||||
SCNetworkReachabilityCreateWithAddressPair(
|
||||
std::ptr::null(),
|
||||
&*to_c_sockaddr(local),
|
||||
&*to_c_sockaddr(remote),
|
||||
)
|
||||
};
|
||||
|
||||
unsafe { Self::wrap_under_create_rule(ptr) }
|
||||
}
|
||||
|
||||
/// Construct a Reachability from either a hostname or a network node
|
||||
///
|
||||
/// See [`SCNetworkReachabilityCreateWithName`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityCreateWithName`]: https://developer.apple.com/documentation/systemconfiguration/1514904-scnetworkreachabilitycreatewithn?language=objc
|
||||
pub fn from_host(host: &CStr) -> Option<Self> {
|
||||
let ptr = unsafe { SCNetworkReachabilityCreateWithName(ptr::null(), host.as_ptr()) };
|
||||
if ptr.is_null() {
|
||||
None
|
||||
} else {
|
||||
unsafe { Some(Self::wrap_under_create_rule(ptr)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a flag indicating whether the specified network address is reachable.
|
||||
///
|
||||
/// See [`SCNetworkReachabilityGetFlags`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityGetFlags`]: https://developer.apple.com/documentation/systemconfiguration/1514924-scnetworkreachabilitygetflags?language=objc
|
||||
pub fn reachability(&self) -> Result<ReachabilityFlags, ReachabilityError> {
|
||||
let mut raw_flags = 0u32;
|
||||
if unsafe { SCNetworkReachabilityGetFlags(self.0, &mut raw_flags) } == 0u8 {
|
||||
return Err(ReachabilityError::FailedToDetermineReachability);
|
||||
}
|
||||
|
||||
ReachabilityFlags::from_bits(raw_flags)
|
||||
.ok_or(ReachabilityError::UnrecognizedFlags(raw_flags))
|
||||
}
|
||||
|
||||
/// Schedule callback with runloop.
|
||||
///
|
||||
/// See [`SCNetworkReachabilityScheduleFromRunLoop`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityScheduleFromRunLoop`]: https://developer.apple.com/documentation/systemconfiguration/1514894-scnetworkreachabilityschedulewit?language=objc
|
||||
pub fn schedule_with_runloop(
|
||||
&self,
|
||||
run_loop: &CFRunLoop,
|
||||
run_loop_mode: CFStringRef,
|
||||
) -> Result<(), SchedulingError> {
|
||||
if unsafe {
|
||||
SCNetworkReachabilityScheduleWithRunLoop(
|
||||
self.0,
|
||||
run_loop.to_void() as *mut _,
|
||||
run_loop_mode,
|
||||
)
|
||||
} == 0u8
|
||||
{
|
||||
Err(SchedulingError(()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Unschedule from run loop.
|
||||
///
|
||||
/// See [`SCNetworkReachabilityUnscheduleFromRunLoop`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityUnscheduleFromRunLoop`]: https://developer.apple.com/documentation/systemconfiguration/1514899-scnetworkreachabilityunschedulef?language=objc
|
||||
pub fn unschedule_from_runloop(
|
||||
&self,
|
||||
run_loop: &CFRunLoop,
|
||||
run_loop_mode: CFStringRef,
|
||||
) -> Result<(), UnschedulingError> {
|
||||
if unsafe {
|
||||
SCNetworkReachabilityUnscheduleFromRunLoop(
|
||||
self.0,
|
||||
run_loop.to_void() as *mut _,
|
||||
run_loop_mode,
|
||||
)
|
||||
} == 0u8
|
||||
{
|
||||
Err(UnschedulingError(()))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets callback that is run whenever network connectivity changes. For the callback to be
|
||||
/// invoked, the `SCNetworkReachability` has to be registered on a run loop. Calling this
|
||||
/// function multiple times will clear the subsequently set callback.
|
||||
///
|
||||
/// See [`SCNetworkReachabilityContext`] for details.
|
||||
///
|
||||
/// [`SCNetworkReachabilityContext`]: https://developer.apple.com/documentation/systemconfiguration/1514903-scnetworkreachabilitysetcallback?language=objc
|
||||
pub fn set_callback<F: Fn(ReachabilityFlags) + Sync + Send>(
|
||||
&mut self,
|
||||
callback: F,
|
||||
) -> Result<(), SetCallbackError> {
|
||||
let callback = Arc::new(NetworkReachabilityCallbackContext::new(
|
||||
self.clone(),
|
||||
callback,
|
||||
));
|
||||
|
||||
let mut callback_context = SCNetworkReachabilityContext {
|
||||
version: 0,
|
||||
info: Arc::into_raw(callback) as *mut _,
|
||||
retain: Some(NetworkReachabilityCallbackContext::<F>::retain_context),
|
||||
release: Some(NetworkReachabilityCallbackContext::<F>::release_context),
|
||||
copyDescription: Some(NetworkReachabilityCallbackContext::<F>::copy_ctx_description),
|
||||
};
|
||||
|
||||
if unsafe {
|
||||
SCNetworkReachabilitySetCallback(
|
||||
self.0,
|
||||
Some(NetworkReachabilityCallbackContext::<F>::callback),
|
||||
&mut callback_context,
|
||||
)
|
||||
} == 0u8
|
||||
{
|
||||
Err(SetCallbackError {})
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SocketAddr> for SCNetworkReachability {
|
||||
fn from(addr: SocketAddr) -> Self {
|
||||
unsafe {
|
||||
let ptr =
|
||||
SCNetworkReachabilityCreateWithAddress(std::ptr::null(), &*to_c_sockaddr(addr));
|
||||
SCNetworkReachability::wrap_under_create_rule(ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct NetworkReachabilityCallbackContext<T: Fn(ReachabilityFlags) + Sync + Send> {
|
||||
_host: SCNetworkReachability,
|
||||
callback: T,
|
||||
}
|
||||
|
||||
impl<T: Fn(ReachabilityFlags) + Sync + Send> NetworkReachabilityCallbackContext<T> {
|
||||
fn new(host: SCNetworkReachability, callback: T) -> Self {
|
||||
Self {
|
||||
_host: host,
|
||||
callback,
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn callback(
|
||||
_target: SCNetworkReachabilityRef,
|
||||
flags: SCNetworkReachabilityFlags,
|
||||
context: *mut c_void,
|
||||
) {
|
||||
let context: &mut Self = unsafe { &mut (*(context as *mut _)) };
|
||||
(context.callback)(unsafe { ReachabilityFlags::from_bits_unchecked(flags) });
|
||||
}
|
||||
|
||||
extern "C" fn copy_ctx_description(_ctx: *const c_void) -> CFStringRef {
|
||||
let description = CFString::from_static_string("NetworkRechability's callback context");
|
||||
let description_ref = description.as_concrete_TypeRef();
|
||||
std::mem::forget(description);
|
||||
description_ref
|
||||
}
|
||||
|
||||
extern "C" fn release_context(ctx: *const c_void) {
|
||||
unsafe {
|
||||
let _ = Arc::from_raw(ctx as *mut Self);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn retain_context(ctx_ptr: *const c_void) -> *const c_void {
|
||||
unsafe {
|
||||
let ctx_ref: Arc<Self> = Arc::from_raw(ctx_ptr as *const Self);
|
||||
let new_ctx = ctx_ref.clone();
|
||||
std::mem::forget(ctx_ref);
|
||||
Arc::into_raw(new_ctx) as *const c_void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocates a libc::sockaddr compatible struct and fills it with either a libc::sockaddr_in or a
|
||||
/// libc::sockaddr_in6, depending on the passed in standard library SocketAddr.
|
||||
fn to_c_sockaddr(addr: SocketAddr) -> Box<libc::sockaddr> {
|
||||
let ptr = match addr {
|
||||
SocketAddr::V4(addr) => Box::into_raw(Box::new(libc::sockaddr_in {
|
||||
sin_len: std::mem::size_of::<libc::sockaddr_in>() as u8,
|
||||
sin_family: libc::AF_INET as u8,
|
||||
sin_port: addr.port(),
|
||||
sin_addr: libc::in_addr {
|
||||
s_addr: u32::from(*addr.ip()),
|
||||
},
|
||||
sin_zero: [0i8; 8],
|
||||
})) as *mut c_void,
|
||||
SocketAddr::V6(addr) => Box::into_raw(Box::new(libc::sockaddr_in6 {
|
||||
sin6_len: std::mem::size_of::<libc::sockaddr_in6>() as u8,
|
||||
sin6_family: libc::AF_INET6 as u8,
|
||||
sin6_port: addr.port(),
|
||||
sin6_flowinfo: 0,
|
||||
sin6_addr: libc::in6_addr {
|
||||
s6_addr: addr.ip().octets(),
|
||||
},
|
||||
sin6_scope_id: 0,
|
||||
})) as *mut c_void,
|
||||
};
|
||||
|
||||
unsafe { Box::from_raw(ptr as *mut _) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
use core_foundation::runloop::{kCFRunLoopCommonModes, CFRunLoop};
|
||||
use std::ffi::CString;
|
||||
|
||||
#[test]
|
||||
fn test_network_reachability_from_addr() {
|
||||
let sockaddrs = vec![
|
||||
"0.0.0.0:0".parse::<SocketAddr>().unwrap(),
|
||||
"[::0]:0".parse::<SocketAddr>().unwrap(),
|
||||
];
|
||||
|
||||
for addr in sockaddrs {
|
||||
let mut reachability = SCNetworkReachability::from(addr);
|
||||
assert!(
|
||||
!reachability.0.is_null(),
|
||||
"Failed to construct a SCNetworkReachability struct with {}",
|
||||
addr
|
||||
);
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
reachability
|
||||
.schedule_with_runloop(&CFRunLoop::get_current(), unsafe { kCFRunLoopCommonModes })
|
||||
.unwrap();
|
||||
reachability
|
||||
.unschedule_from_runloop(&CFRunLoop::get_current(), unsafe {
|
||||
kCFRunLoopCommonModes
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sockaddr_pair_reachability() {
|
||||
let pairs = vec![
|
||||
("0.0.0.0:0", "[::0]:0"),
|
||||
("[::0]:0", "0.0.0.0:0"),
|
||||
("[::0]:0", "[::0]:0"),
|
||||
("0.0.0.0:0", "0.0.0.0:0"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(a, b)| (a.parse().unwrap(), b.parse().unwrap()));
|
||||
|
||||
for (local, remote) in pairs {
|
||||
let mut reachability = SCNetworkReachability::from_addr_pair(local, remote);
|
||||
assert!(
|
||||
!reachability.0.is_null(),
|
||||
"Failed to construct a SCNetworkReachability struct with address pair {} - {}",
|
||||
local,
|
||||
remote
|
||||
);
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
reachability
|
||||
.schedule_with_runloop(&CFRunLoop::get_current(), unsafe { kCFRunLoopCommonModes })
|
||||
.unwrap();
|
||||
reachability
|
||||
.unschedule_from_runloop(&CFRunLoop::get_current(), unsafe {
|
||||
kCFRunLoopCommonModes
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reachability_ref_from_host() {
|
||||
let valid_inputs = vec!["example.com", "host-in-local-network", "en0"];
|
||||
|
||||
let get_cstring = |input: &str| CString::new(input).unwrap();
|
||||
|
||||
for input in valid_inputs.into_iter().map(get_cstring) {
|
||||
match SCNetworkReachability::from_host(&input) {
|
||||
Some(mut reachability) => {
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
reachability
|
||||
.schedule_with_runloop(&CFRunLoop::get_current(), unsafe {
|
||||
kCFRunLoopCommonModes
|
||||
})
|
||||
.unwrap();
|
||||
reachability
|
||||
.unschedule_from_runloop(&CFRunLoop::get_current(), unsafe {
|
||||
kCFRunLoopCommonModes
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
None => {
|
||||
panic!(
|
||||
"Failed to construct a SCNetworkReachability from {}",
|
||||
input.to_string_lossy(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Can only testify that an empty string is invalid, everything else seems to work
|
||||
assert!(
|
||||
!SCNetworkReachability::from_host(&get_cstring("")).is_some(),
|
||||
"Constructed valid SCNetworkReachability from empty string"
|
||||
);
|
||||
}
|
||||
|
||||
unsafe impl Send for SCNetworkReachability {}
|
||||
|
||||
#[test]
|
||||
fn assert_infallibility_of_setting_a_callback() {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut reachability =
|
||||
SCNetworkReachability::from("0.0.0.0:0".parse::<SocketAddr>().unwrap());
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
reachability
|
||||
.schedule_with_runloop(&CFRunLoop::get_current(), unsafe { kCFRunLoopCommonModes })
|
||||
.unwrap();
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
let _ = tx.send(reachability);
|
||||
CFRunLoop::run_current();
|
||||
});
|
||||
let mut reachability = rx.recv().unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
reachability.set_callback(|_| {}).unwrap();
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
// Copyright 2017 Amagicom AB.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
||||
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
||||
// option. This file may not be copied, modified, or distributed
|
||||
// except according to those terms.
|
||||
|
||||
//! Bindings to [`SCPreferences`].
|
||||
//!
|
||||
//! See the examples directory for examples how to use this module.
|
||||
//!
|
||||
//! [`SCPreferences`]: https://developer.apple.com/documentation/systemconfiguration/scpreferences-ft8
|
||||
|
||||
use crate::sys::preferences::{SCPreferencesCreate, SCPreferencesGetTypeID, SCPreferencesRef};
|
||||
use core_foundation::base::{CFAllocator, TCFType};
|
||||
use core_foundation::string::CFString;
|
||||
use std::ptr;
|
||||
|
||||
declare_TCFType! {
|
||||
/// The handle to an open preferences session for accessing system configuration preferences.
|
||||
SCPreferences, SCPreferencesRef
|
||||
}
|
||||
|
||||
impl_TCFType!(SCPreferences, SCPreferencesRef, SCPreferencesGetTypeID);
|
||||
|
||||
impl SCPreferences {
|
||||
/// Initiates access to the default system preferences using the default allocator.
|
||||
pub fn default(calling_process_name: &CFString) -> Self {
|
||||
Self::new(None, calling_process_name, None)
|
||||
}
|
||||
|
||||
/// Initiates access to the given (`prefs_id`) group of configuration preferences using the
|
||||
/// default allocator. To access the default system preferences, use the [`default`]
|
||||
/// constructor.
|
||||
///
|
||||
/// [`default`]: #method.default
|
||||
pub fn group(calling_process_name: &CFString, prefs_id: &CFString) -> Self {
|
||||
Self::new(None, calling_process_name, Some(prefs_id))
|
||||
}
|
||||
|
||||
/// Initiates access to the per-system set of configuration preferences with a given
|
||||
/// allocator and preference group to access. See the underlying [SCPreferencesCreate] function
|
||||
/// documentation for details. Use the helper constructors [`default`] and [`group`] to easier
|
||||
/// create an instance using the default allocator.
|
||||
///
|
||||
/// [SCPreferencesCreate]: https://developer.apple.com/documentation/systemconfiguration/1516807-scpreferencescreate?language=objc
|
||||
/// [`default`]: #method.default
|
||||
/// [`group`]: #method.group
|
||||
pub fn new(
|
||||
allocator: Option<&CFAllocator>,
|
||||
calling_process_name: &CFString,
|
||||
prefs_id: Option<&CFString>,
|
||||
) -> Self {
|
||||
let allocator_ref = match allocator {
|
||||
Some(allocator) => allocator.as_concrete_TypeRef(),
|
||||
None => ptr::null(),
|
||||
};
|
||||
let prefs_id_ref = match prefs_id {
|
||||
Some(prefs_id) => prefs_id.as_concrete_TypeRef(),
|
||||
None => ptr::null(),
|
||||
};
|
||||
|
||||
unsafe {
|
||||
SCPreferences::wrap_under_create_rule(SCPreferencesCreate(
|
||||
allocator_ref,
|
||||
calling_process_name.as_concrete_TypeRef(),
|
||||
prefs_id_ref,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn retain_count() {
|
||||
let preferences = SCPreferences::default(&CFString::new("test"));
|
||||
assert_eq!(preferences.retain_count(), 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user