Initial MeshPort SDK and cross-platform client
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "meshport-easytier"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
easytier.workspace = true
|
||||
easytier-core.workspace = true
|
||||
anyhow.workspace = true
|
||||
toml.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
serde.workspace = true
|
||||
cidr = "0.3"
|
||||
network-interface = "2.0.5"
|
||||
async-trait = "0.1"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
system-vpn = ["easytier/tun", "easytier/proxy-cidr-monitor"]
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Isolated USB/adb-reverse fixture, not a production relay or user network.
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
|
||||
use easytier_core::instance::CoreInstanceConfig;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, UdpSocket},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let config = TomlConfig::new_from_str(
|
||||
"ipv4 = '10.253.83.2/24'\nlisteners = ['tcp://127.0.0.1:18080']\nstun_servers = []\nstun_servers_v6 = []\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n[network_identity]\nnetwork_name = 'android-validation'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true",
|
||||
)?;
|
||||
let server = create_native_instance(config.clone())?;
|
||||
server.start().await?;
|
||||
let tcp = TcpListener::bind("127.0.0.1:17007").await?;
|
||||
let udp = UdpSocket::bind("127.0.0.1:17007").await?;
|
||||
let control = TcpListener::bind("127.0.0.1:18081").await?;
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut stream, _)) = tcp.accept().await {
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 4096];
|
||||
while let Ok(n) = stream.read(&mut buffer).await {
|
||||
if n == 0 || stream.write_all(&buffer[..n]).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 4096];
|
||||
while let Ok((n, peer)) = udp.recv_from(&mut buffer).await {
|
||||
let _ = udp.send_to(&buffer[..n], peer).await;
|
||||
}
|
||||
});
|
||||
let gateway = server.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut stream, _)) = control.accept().await {
|
||||
let mut buffer = [0; 32];
|
||||
if stream.read(&mut buffer).await.is_ok() {
|
||||
config.clear_proxy_cidrs();
|
||||
let updated = CoreInstanceConfig::from_toml(&config).unwrap();
|
||||
gateway
|
||||
.update_runtime_config(
|
||||
easytier_core::config::runtime::CoreInstanceRuntimeConfig {
|
||||
services: updated.connectivity.runtime,
|
||||
peer: std::sync::Arc::new(updated.peer.snapshot),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = stream.write_all(b"withdrawn\n").await;
|
||||
}
|
||||
}
|
||||
});
|
||||
println!("Android validation fixture ready on localhost:18080; echo subnet 10.253.79.0/24");
|
||||
tokio::signal::ctrl_c().await?;
|
||||
server.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use easytier::socket_protector::{NativeSocketProtector, set_native_socket_protector};
|
||||
use std::{io, sync::Arc};
|
||||
|
||||
pub type ProtectSocket = extern "C" fn(i32) -> bool;
|
||||
struct AndroidProtector(ProtectSocket);
|
||||
#[async_trait::async_trait]
|
||||
impl NativeSocketProtector for AndroidProtector {
|
||||
async fn protect(&self, socket_handle: u64) -> io::Result<()> {
|
||||
let fd = i32::try_from(socket_handle)
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid socket fd"))?;
|
||||
if (self.0)(fd) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"Android VPN socket protection failed",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn install_socket_protector(callback: ProtectSocket) {
|
||||
set_native_socket_protector(Some(Arc::new(AndroidProtector(callback))));
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
//! Pinned EasyTier adapter with strict application and opt-in macOS system VPN modes.
|
||||
use anyhow::{Context, Result, bail};
|
||||
use easytier::common::global_ctx::{EventBusSubscriber, GlobalCtxEvent};
|
||||
use easytier::instance::factory::{
|
||||
NativeCoreInstance, create_native_instance, subscribe_native_instance_event,
|
||||
};
|
||||
pub use easytier_core::config::toml::ConfigLoader;
|
||||
use easytier_core::config::toml::TomlConfig;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
pub use easytier_core::peers::meshport_optimization::{Mode, OptimizationPolicy};
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub mod android;
|
||||
mod system_routes;
|
||||
|
||||
pub const REVISION: &str = "7af7bdc16a41d64d58743d15023a63b3eed2102c";
|
||||
|
||||
/// Strict mode-aware allowlist. Unknown options fail rather than disappear.
|
||||
pub fn parse_config(input: &str) -> Result<TomlConfig> {
|
||||
if input.len() > 65536 {
|
||||
bail!("configuration exceeds 64 KiB");
|
||||
}
|
||||
let value: toml::Value =
|
||||
toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?;
|
||||
let table = value
|
||||
.as_table()
|
||||
.context("configuration must be a TOML table")?;
|
||||
let allowed = [
|
||||
"runtime",
|
||||
"optimization",
|
||||
"hostname",
|
||||
"instance_name",
|
||||
"ipv4",
|
||||
"dhcp",
|
||||
"network_identity",
|
||||
"peer",
|
||||
"listeners",
|
||||
"mapped_listeners",
|
||||
"flags",
|
||||
"stun_servers",
|
||||
"stun_servers_v6",
|
||||
];
|
||||
let system_vpn = runtime_mode(&value)? == RuntimeMode::SystemVpn;
|
||||
for key in table.keys() {
|
||||
if !allowed.contains(&key.as_str()) {
|
||||
bail!("unsupported application-mode option: {key}");
|
||||
}
|
||||
}
|
||||
if let Some(flags) = table.get("flags") {
|
||||
let flags = flags.as_table().context("flags must be a table")?;
|
||||
let allowed = [
|
||||
"default_protocol",
|
||||
"latency_first",
|
||||
"enable_ipv6",
|
||||
"disable_p2p",
|
||||
"p2p_only",
|
||||
"lazy_p2p",
|
||||
"need_p2p",
|
||||
"disable_tcp_hole_punching",
|
||||
"disable_udp_hole_punching",
|
||||
"disable_sym_hole_punching",
|
||||
"private_mode",
|
||||
"foreign_relay_bps_limit",
|
||||
"no_tun",
|
||||
"use_smoltcp",
|
||||
"enable_encryption",
|
||||
];
|
||||
for key in flags.keys() {
|
||||
if !allowed.contains(&key.as_str()) {
|
||||
bail!("unsupported application-mode flag: {key}");
|
||||
}
|
||||
}
|
||||
if flags
|
||||
.get("enable_encryption")
|
||||
.is_some_and(|v| v.as_bool() != Some(true))
|
||||
{
|
||||
bail!("enable_encryption must be true");
|
||||
}
|
||||
}
|
||||
if let Some(identity) = table.get("network_identity") {
|
||||
let identity = identity
|
||||
.as_table()
|
||||
.context("network_identity must be a table")?;
|
||||
for key in identity.keys() {
|
||||
if !["network_name", "network_secret"].contains(&key.as_str()) {
|
||||
bail!("unsupported identity field: {key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(peers) = table.get("peer") {
|
||||
for peer in peers
|
||||
.as_array()
|
||||
.context("peer must be an array of tables")?
|
||||
{
|
||||
let peer = peer.as_table().context("peer must be a table")?;
|
||||
for key in peer.keys() {
|
||||
if key != "uri" {
|
||||
bail!("unsupported peer field: {key}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(flags) = table.get("flags").and_then(|v| v.as_table()) {
|
||||
for key in ["no_tun", "use_smoltcp"] {
|
||||
if flags
|
||||
.get(key)
|
||||
.is_some_and(|v| v.as_bool() != Some(!system_vpn))
|
||||
{
|
||||
bail!("{key} contradicts runtime mode");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Upstream errors may contain input/credentials, so do not forward raw parser errors.
|
||||
let optimization = optimization_config(input)?;
|
||||
let mut upstream = value.clone();
|
||||
upstream.as_table_mut().unwrap().remove("optimization");
|
||||
upstream.as_table_mut().unwrap().remove("runtime");
|
||||
let config = TomlConfig::new_from_str(
|
||||
&toml::to_string(&upstream).map_err(|_| anyhow::anyhow!("invalid configuration"))?,
|
||||
)
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!("invalid EasyTier configuration; check field types and addresses")
|
||||
})?;
|
||||
if config.get_ipv4().is_none() && !config.get_dhcp() {
|
||||
bail!("ipv4 or dhcp = true is required");
|
||||
}
|
||||
if config.get_ipv4().is_some() && config.get_dhcp() {
|
||||
bail!("choose static ipv4 or dhcp, not both");
|
||||
}
|
||||
if config.get_network_identity().network_name.trim().is_empty() {
|
||||
bail!("network_name must not be empty");
|
||||
}
|
||||
let mut flags = config.get_flags();
|
||||
if !["tcp", "udp"].contains(&flags.default_protocol.as_str()) {
|
||||
bail!("this build supports only tcp and udp transports");
|
||||
}
|
||||
for uri in config
|
||||
.get_peers()
|
||||
.iter()
|
||||
.map(|p| &p.uri)
|
||||
.chain(config.get_listener_uris().iter())
|
||||
{
|
||||
if !["tcp", "udp"].contains(&uri.scheme()) {
|
||||
bail!("unsupported transport: {}", uri.scheme());
|
||||
}
|
||||
}
|
||||
if table.contains_key("optimization") {
|
||||
flags.latency_first = matches!(optimization.mode, Mode::Adaptive | Mode::Latency);
|
||||
}
|
||||
if system_vpn {
|
||||
let ip = config
|
||||
.get_ipv4()
|
||||
.context("system_vpn requires a static private ipv4 in this stage")?;
|
||||
if !(16..=30).contains(&ip.network_length())
|
||||
|| !ip.address().is_private()
|
||||
|| ip.address() == ip.first_address()
|
||||
|| ip.address() == ip.last_address()
|
||||
{
|
||||
bail!("system_vpn requires a private IPv4 host with prefix /16 through /30");
|
||||
}
|
||||
}
|
||||
config.set_routes(None);
|
||||
flags.no_tun = !system_vpn;
|
||||
flags.use_smoltcp = !system_vpn;
|
||||
flags.enable_encryption = true;
|
||||
flags.accept_dns = false;
|
||||
flags.enable_exit_node = false;
|
||||
flags.proxy_forward_by_system = false;
|
||||
flags.disable_upnp = true;
|
||||
flags.relay_network_whitelist.clear();
|
||||
config.set_flags(flags);
|
||||
if config.get_listeners().is_none() {
|
||||
config.set_listeners(vec![]);
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum RuntimeMode {
|
||||
Application,
|
||||
SystemVpn,
|
||||
}
|
||||
fn runtime_mode(value: &toml::Value) -> Result<RuntimeMode> {
|
||||
let Some(runtime) = value.get("runtime") else {
|
||||
return Ok(RuntimeMode::Application);
|
||||
};
|
||||
let table = runtime.as_table().context("runtime must be a table")?;
|
||||
if table.keys().any(|k| !["mode"].contains(&k.as_str())) {
|
||||
bail!("unsupported runtime setting");
|
||||
}
|
||||
match table.get("mode").and_then(|v| v.as_str()) {
|
||||
Some("application") => Ok(RuntimeMode::Application),
|
||||
Some("system_vpn") => Ok(RuntimeMode::SystemVpn),
|
||||
_ => bail!("runtime.mode must be application or system_vpn"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn optimization_config(input: &str) -> Result<OptimizationPolicy> {
|
||||
let value: toml::Value =
|
||||
toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?;
|
||||
let policy: OptimizationPolicy = match value.get("optimization") {
|
||||
Some(value) => value
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("invalid optimization settings"))?,
|
||||
None => OptimizationPolicy {
|
||||
mode: if value
|
||||
.get("flags")
|
||||
.and_then(|f| f.get("latency_first"))
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
Mode::Adaptive
|
||||
} else {
|
||||
Mode::Hop
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
policy
|
||||
.validate()
|
||||
.map_err(|message| anyhow::anyhow!(message))?;
|
||||
Ok(policy)
|
||||
}
|
||||
|
||||
// Upstream directly_connected_conns deliberately excludes hole-punched links.
|
||||
// A default connection belongs to the local peer map; foreign logical peers have none.
|
||||
fn has_direct_transport(peer: &easytier_core::peers::peer_manager::PeerSnapshot) -> bool {
|
||||
peer.default_conn_id.is_some()
|
||||
&& peer.conns.iter().any(|conn| {
|
||||
!conn.is_closed
|
||||
&& conn
|
||||
.tunnel
|
||||
.as_ref()
|
||||
.is_some_and(|t| matches!(t.tunnel_type.as_str(), "tcp" | "udp"))
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
pub instance: Arc<NativeCoreInstance>,
|
||||
pub config: TomlConfig,
|
||||
pub mode: RuntimeMode,
|
||||
interface_name: Mutex<Option<String>>,
|
||||
optimization: OptimizationPolicy,
|
||||
traffic: Mutex<Traffic>,
|
||||
events: Mutex<Option<EventBusSubscriber>>,
|
||||
journal: Mutex<Vec<serde_json::Value>>,
|
||||
event_sequence: Mutex<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Traffic {
|
||||
previous: HashMap<String, (u64, u64)>,
|
||||
sampled_at: Option<Instant>,
|
||||
rx_bytes: u64,
|
||||
tx_bytes: u64,
|
||||
}
|
||||
impl Engine {
|
||||
pub async fn start(input: &str) -> Result<Self> {
|
||||
let config = parse_config(input)?;
|
||||
let mode = if config.get_flags().no_tun {
|
||||
RuntimeMode::Application
|
||||
} else {
|
||||
RuntimeMode::SystemVpn
|
||||
};
|
||||
if mode == RuntimeMode::SystemVpn
|
||||
&& !(cfg!(feature = "system-vpn")
|
||||
&& cfg!(any(target_os = "macos", target_os = "android")))
|
||||
{
|
||||
bail!("system_vpn requires a platform VPN build and platform authorization");
|
||||
}
|
||||
let optimization = optimization_config(input)?;
|
||||
let instance = create_native_instance(config.clone())?;
|
||||
instance
|
||||
.peer_manager()
|
||||
.configure_optimization(optimization.clone());
|
||||
let policy_config = config.clone();
|
||||
instance
|
||||
.packet_plane()
|
||||
.set_proxy_route_filter(Arc::new(move |route| {
|
||||
policy_config.get_ipv4().is_some_and(|overlay| {
|
||||
system_routes::allowed(route, overlay.address(), overlay.network_length())
|
||||
})
|
||||
}));
|
||||
let events = subscribe_native_instance_event(&instance);
|
||||
if let Err(error) = instance.start().await {
|
||||
instance.stop().await;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(Self {
|
||||
instance,
|
||||
config,
|
||||
mode,
|
||||
interface_name: Mutex::new(None),
|
||||
optimization,
|
||||
traffic: Mutex::new(Traffic::default()),
|
||||
events: Mutex::new(events),
|
||||
journal: Mutex::new(Vec::new()),
|
||||
event_sequence: Mutex::new(0),
|
||||
})
|
||||
}
|
||||
pub fn redact_diagnostic(&self, text: &str) -> String {
|
||||
let secret = self
|
||||
.config
|
||||
.get_network_identity()
|
||||
.network_secret
|
||||
.unwrap_or_default();
|
||||
if secret.is_empty() {
|
||||
text.to_owned()
|
||||
} else {
|
||||
text.replace(&secret, "[redacted]")
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn attach_tun_fd(&self, fd: i32) -> Result<()> {
|
||||
if self.mode != RuntimeMode::SystemVpn || fd < 0 {
|
||||
bail!("TUN attachment requires system VPN mode and a valid fd");
|
||||
}
|
||||
*self.interface_name.lock().unwrap() = None;
|
||||
self.instance.attach_tun_fd(fd)
|
||||
}
|
||||
pub async fn stop(&self) {
|
||||
self.instance.stop().await;
|
||||
*self.interface_name.lock().unwrap() = None;
|
||||
}
|
||||
pub async fn snapshot(&self) -> serde_json::Value {
|
||||
if let Some(receiver) = self.events.lock().unwrap().as_mut() {
|
||||
loop {
|
||||
let message = match receiver.try_recv() {
|
||||
Ok(event) => match event {
|
||||
GlobalCtxEvent::TunDeviceReady(name) => {
|
||||
*self.interface_name.lock().unwrap() = Some(name.clone());
|
||||
Some(format!("虚拟网卡就绪 {name}"))
|
||||
}
|
||||
GlobalCtxEvent::TunDeviceError(_) => {
|
||||
*self.interface_name.lock().unwrap() = None;
|
||||
Some("虚拟网卡创建失败".to_owned())
|
||||
}
|
||||
GlobalCtxEvent::PeerAdded(id) => Some(format!("节点加入 {id}")),
|
||||
GlobalCtxEvent::PeerRemoved(id) => Some(format!("节点离开 {id}")),
|
||||
GlobalCtxEvent::PeerConnAdded(info) => Some(format!(
|
||||
"连接建立 节点 {} 协议 {}",
|
||||
info.peer_id,
|
||||
info.tunnel
|
||||
.as_ref()
|
||||
.map(|t| t.tunnel_type.as_str())
|
||||
.unwrap_or("unknown")
|
||||
)),
|
||||
GlobalCtxEvent::PeerConnRemoved(info) => {
|
||||
Some(format!("连接断开 节点 {}", info.peer_id))
|
||||
}
|
||||
GlobalCtxEvent::ListenerAdded(url) => Some(format!(
|
||||
"监听建立 {}://{}:{}",
|
||||
url.scheme(),
|
||||
url.host_str().unwrap_or(""),
|
||||
url.port().unwrap_or(0)
|
||||
)),
|
||||
GlobalCtxEvent::ListenerAddFailed(_, error) => {
|
||||
Some(format!("监听失败 {error}"))
|
||||
}
|
||||
GlobalCtxEvent::ListenerAcceptFailed(_, error) => {
|
||||
Some(format!("接收连接失败 {error}"))
|
||||
}
|
||||
GlobalCtxEvent::ConnectError(_, family, error) => {
|
||||
Some(format!("连接失败 {family} {error}"))
|
||||
}
|
||||
GlobalCtxEvent::ConnectionError(_, _, error) => {
|
||||
Some(format!("连接错误 {error}"))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::TryRecvError::Lagged(count)) => {
|
||||
Some(format!("原生事件溢出,丢失 {count} 条"))
|
||||
}
|
||||
Err(_) => break,
|
||||
};
|
||||
if let Some(mut message) = message {
|
||||
let secret = self
|
||||
.config
|
||||
.get_network_identity()
|
||||
.network_secret
|
||||
.unwrap_or_default();
|
||||
if !secret.is_empty() {
|
||||
message = message.replace(&secret, "[redacted]");
|
||||
}
|
||||
let mut sequence = self.event_sequence.lock().unwrap();
|
||||
*sequence += 1;
|
||||
let mut journal = self.journal.lock().unwrap();
|
||||
journal.push(serde_json::json!({"sequence": *sequence, "message": message.chars().take(1000).collect::<String>()}));
|
||||
if journal.len() > 100 {
|
||||
journal.remove(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let node = self.instance.node_snapshot().await;
|
||||
let peers = self.instance.peer_manager().list_peer_snapshots().await;
|
||||
let routes = self.instance.peer_manager().list_route_snapshots().await;
|
||||
let mut effective_hops = HashMap::new();
|
||||
for route in &routes {
|
||||
effective_hops.insert(
|
||||
route.peer_id,
|
||||
self.instance
|
||||
.peer_manager()
|
||||
.effective_next_hop(route.peer_id)
|
||||
.await,
|
||||
);
|
||||
}
|
||||
let subnet_routes = self
|
||||
.instance
|
||||
.packet_plane()
|
||||
.proxy_cidr_diff(&Default::default())
|
||||
.await
|
||||
.map(|d| {
|
||||
d.current
|
||||
.into_iter()
|
||||
.map(|r| r.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut traffic = self.traffic.lock().unwrap();
|
||||
let now = Instant::now();
|
||||
let seconds = traffic
|
||||
.sampled_at
|
||||
.map(|t| now.duration_since(t).as_secs_f64());
|
||||
let mut current = HashMap::new();
|
||||
let mut total_rx_delta = 0u64;
|
||||
let mut total_tx_delta = 0u64;
|
||||
let peer_stats = peers.iter().map(|p| {
|
||||
let mut rx = 0u64;
|
||||
let mut tx = 0u64;
|
||||
let mut rx_delta = 0u64;
|
||||
let mut tx_delta = 0u64;
|
||||
for conn in &p.conns {
|
||||
if let Some(stats) = &conn.stats {
|
||||
let key = format!("{}:{}", p.peer_id, conn.conn_id);
|
||||
let previous = traffic.previous.get(&key).copied().unwrap_or((0, 0));
|
||||
rx += stats.rx_bytes;
|
||||
tx += stats.tx_bytes;
|
||||
rx_delta += stats.rx_bytes.saturating_sub(previous.0);
|
||||
tx_delta += stats.tx_bytes.saturating_sub(previous.1);
|
||||
current.insert(key, (stats.rx_bytes, stats.tx_bytes));
|
||||
}
|
||||
}
|
||||
total_rx_delta += rx_delta;
|
||||
total_tx_delta += tx_delta;
|
||||
let latency_us = p.conns.iter()
|
||||
.filter(|c| p.default_conn_id.as_ref().is_some_and(|id| id.to_string() == c.conn_id))
|
||||
.filter_map(|c| c.stats.as_ref()).map(|s| s.latency_us).find(|v| *v > 0);
|
||||
serde_json::json!({
|
||||
"peer_id": p.peer_id, "connections": p.conns.len(),
|
||||
"direct": has_direct_transport(p),
|
||||
"hole_punched": has_direct_transport(p) && p.conns.iter().any(|c| !c.is_closed && !p.directly_connected_conns.iter().any(|id| id.to_string() == c.conn_id)),
|
||||
"selected_transport": p.conns.iter().find(|c| p.default_conn_id.as_ref().is_some_and(|id| id.to_string() == c.conn_id)).and_then(|c| c.tunnel.as_ref()).map(|t| &t.tunnel_type),
|
||||
"transports": p.conns.iter().filter_map(|c| c.tunnel.as_ref().map(|t| t.tunnel_type.clone())).collect::<Vec<_>>(),
|
||||
"latency_ms": latency_us.map(|v| v as f64 / 1000.0),
|
||||
"rx_bytes": rx, "tx_bytes": tx,
|
||||
"rx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| rx_delta as f64 / s),
|
||||
"tx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| tx_delta as f64 / s)
|
||||
})
|
||||
}).collect::<Vec<_>>();
|
||||
traffic.rx_bytes += total_rx_delta;
|
||||
traffic.tx_bytes += total_tx_delta;
|
||||
traffic.previous = current;
|
||||
traffic.sampled_at = Some(now);
|
||||
let flags = self.config.get_flags();
|
||||
let latency_first = flags.latency_first;
|
||||
let interface_name = self.interface_name.lock().unwrap().clone();
|
||||
serde_json::json!({
|
||||
"state": format!("{:?}", self.instance.state()),
|
||||
"ipv4": node.ipv4_addr.map(|ip| ip.to_string()),
|
||||
"network_name": self.config.get_network_identity().network_name,
|
||||
"local_peer": {
|
||||
"peer_id": node.peer_id, "hostname": node.hostname,
|
||||
"ipv4": node.ipv4_addr.map(|ip| ip.to_string()),
|
||||
"state": format!("{:?}", self.instance.state()),
|
||||
"version": node.version,
|
||||
"udp_nat_type": format!("{:?}", easytier::proto::common::NatType::try_from(node.stun_info.udp_nat_type).unwrap_or_default())
|
||||
},
|
||||
"optimization": self.optimization,
|
||||
"optimization_basis": "link_rtt_and_route_estimate",
|
||||
"peer_count": peers.len(), "peers": peer_stats,
|
||||
"instance_id": node.instance_id.to_string(),
|
||||
"native_events": self.journal.lock().unwrap().clone(),
|
||||
"connectivity": {
|
||||
"udp_nat_type": format!("{:?}", easytier::proto::common::NatType::try_from(node.stun_info.udp_nat_type).unwrap_or_default()),
|
||||
"tcp_nat_type": format!("{:?}", easytier::proto::common::NatType::try_from(node.stun_info.tcp_nat_type).unwrap_or_default()),
|
||||
"stun_last_update": node.stun_info.last_update_time,
|
||||
"listeners": node.listeners.iter().filter(|v| matches!(v.scheme(), "tcp" | "udp")).map(|v| v.to_string()).collect::<Vec<_>>(),
|
||||
"stun_servers": self.config.get_stun_servers(),
|
||||
"stun_servers_v6": self.config.get_stun_servers_v6(),
|
||||
"disable_p2p": flags.disable_p2p,
|
||||
"disable_udp_hole_punching": flags.disable_udp_hole_punching,
|
||||
"disable_tcp_hole_punching": flags.disable_tcp_hole_punching,
|
||||
"disable_sym_hole_punching": flags.disable_sym_hole_punching,
|
||||
"lazy_p2p": flags.lazy_p2p, "need_p2p": flags.need_p2p,
|
||||
"upnp_enabled": false,
|
||||
"bind_device": flags.bind_device,
|
||||
"interface_ipv4s": node.ip_list.interface_ipv4s.iter().map(|ip| std::net::Ipv4Addr::from(*ip).to_string()).collect::<Vec<_>>(),
|
||||
"interface_ipv6s": node.ip_list.interface_ipv6s.iter().map(|ip| std::net::Ipv6Addr::from(*ip).to_string()).collect::<Vec<_>>(),
|
||||
"tcp_hole_punch_compiled": true,
|
||||
"latency_first": latency_first
|
||||
},
|
||||
"traffic": {
|
||||
"rx_bytes": traffic.rx_bytes, "tx_bytes": traffic.tx_bytes,
|
||||
"rx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| total_rx_delta as f64 / s),
|
||||
"tx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| total_tx_delta as f64 / s),
|
||||
"scope": "tunnel_including_control"
|
||||
},
|
||||
"routes": routes.iter().map(|r| {
|
||||
let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency};
|
||||
serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname,
|
||||
"ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()),
|
||||
"advertised_subnets": r.proxy_cidrs,
|
||||
"cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}),
|
||||
"version": r.version,
|
||||
"udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())),
|
||||
"disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p),
|
||||
"need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p),
|
||||
"next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(),
|
||||
"candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id },
|
||||
"estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None}
|
||||
})
|
||||
}).collect::<Vec<_>>(),
|
||||
"application_only": self.mode == RuntimeMode::Application,
|
||||
"runtime_mode": self.mode,
|
||||
"platform_network": {
|
||||
"interface_name": interface_name,
|
||||
"ready": interface_name.is_some(),
|
||||
"route_scope": if !subnet_routes.is_empty() { "overlay_and_remote_subnets" } else { "overlay_only" },
|
||||
"subnet_route_mode": "automatic",
|
||||
"route_installation": if self.mode == RuntimeMode::SystemVpn { "system" } else { "sdk_only" },
|
||||
"subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false
|
||||
}, "upstream_revision": REVISION
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
// Run explicitly on a Mac with another TUN VPN already active. Uses an
|
||||
// isolated network identity and never changes the host routing table.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires an active physical macOS network interface"]
|
||||
async fn physical_bootstrap_with_existing_tun() {
|
||||
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
|
||||
let interfaces = NetworkInterface::show().unwrap();
|
||||
let physical = interfaces.iter().find(|iface| {
|
||||
iface.name.starts_with("en") && iface.addr.iter().any(|addr| {
|
||||
matches!(addr.ip(), std::net::IpAddr::V4(ip) if !ip.is_link_local() && !ip.is_loopback())
|
||||
})
|
||||
}).expect("active physical interface");
|
||||
let ip = physical
|
||||
.addr
|
||||
.iter()
|
||||
.find_map(|addr| match addr.ip() {
|
||||
std::net::IpAddr::V4(ip) if !ip.is_link_local() && !ip.is_loopback() => Some(ip),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let listener = std::net::TcpListener::bind((ip, 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
drop(listener);
|
||||
let shared = "[network_identity]\nnetwork_name = 'physical-bootstrap-test'\nnetwork_secret = 'test-only'\n";
|
||||
let server = Engine::start(&format!(
|
||||
"stun_servers = []\nstun_servers_v6 = []\nipv4 = '10.253.83.2'\nlisteners = ['tcp://{ip}:{port}']\n{shared}"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let client = Engine::start(&format!(
|
||||
"stun_servers = []\nstun_servers_v6 = []\nipv4 = '10.253.83.11'\nlisteners = []\n[[peer]]\nuri = 'tcp://{ip}:{port}'\n{shared}"
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
loop {
|
||||
let snapshot = client.snapshot().await;
|
||||
if snapshot["peer_count"].as_u64().unwrap_or_default() > 0 {
|
||||
assert_eq!(snapshot["connectivity"]["bind_device"], true);
|
||||
let candidates = snapshot["connectivity"]["interface_ipv4s"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert!(candidates.iter().any(|value| value == &ip.to_string()));
|
||||
for iface in interfaces
|
||||
.iter()
|
||||
.filter(|iface| iface.name.starts_with("utun"))
|
||||
{
|
||||
for addr in &iface.addr {
|
||||
assert!(
|
||||
!candidates
|
||||
.iter()
|
||||
.any(|value| value == &addr.ip().to_string()),
|
||||
"TUN leaked into physical candidates"
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
client.stop().await;
|
||||
server.stop().await;
|
||||
result.expect("physical-interface bootstrap timed out");
|
||||
}
|
||||
#[test]
|
||||
fn hole_punched_udp_is_direct_but_foreign_or_closed_connections_are_not() {
|
||||
let mut peer = easytier_core::peers::peer_manager::PeerSnapshot {
|
||||
peer_id: 3157594741,
|
||||
default_conn_id: Some("8c653a79-f814-4f92-9030-b86c93e1017d".parse().unwrap()),
|
||||
directly_connected_conns: vec![],
|
||||
conns: vec![Default::default()],
|
||||
};
|
||||
peer.conns[0].tunnel.get_or_insert_default().tunnel_type = "udp".into();
|
||||
assert!(
|
||||
has_direct_transport(&peer),
|
||||
"UDP punch is a physical direct link"
|
||||
);
|
||||
peer.conns[0].is_closed = true;
|
||||
assert!(!has_direct_transport(&peer));
|
||||
peer.conns[0].is_closed = false;
|
||||
peer.default_conn_id = None;
|
||||
assert!(
|
||||
!has_direct_transport(&peer),
|
||||
"foreign logical connections are not direct"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn optimization_configuration_is_strict_and_controls_effective_flags() {
|
||||
let input = format!(
|
||||
"{BASE}\n[optimization]\nmode = 'adaptive'\nmin_improvement_ms = 20\nrelay_peer_ids = [10,20]"
|
||||
);
|
||||
assert!(parse_config(&input).unwrap().get_flags().latency_first);
|
||||
assert_eq!(
|
||||
optimization_config(&input).unwrap().relay_peer_ids,
|
||||
vec![10, 20]
|
||||
);
|
||||
assert!(parse_config(&format!("{BASE}\n[optimization]\ntypo = true")).is_err());
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn udp_preference_and_tcp_backup_use_real_connections() {
|
||||
let tcp = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = tcp.local_addr().unwrap().port();
|
||||
let udp = std::net::UdpSocket::bind(("127.0.0.1", port)).unwrap();
|
||||
drop(tcp);
|
||||
drop(udp);
|
||||
let shared = "[network_identity]\nnetwork_name = 'transport-test'\nnetwork_secret = 'test-only'\n[optimization]\nmode = 'adaptive'\nprefer_udp = true\n";
|
||||
let server = Engine::start(&format!("stun_servers = []\nstun_servers_v6 = []\nipv4 = '10.81.0.2'\nlisteners = ['tcp://127.0.0.1:{port}', 'udp://127.0.0.1:{port}']\n{shared}")).await.unwrap();
|
||||
let client = Engine::start(&format!("stun_servers = []\nstun_servers_v6 = []\nipv4 = '10.81.0.11'\nlisteners = []\n[[peer]]\nuri = 'tcp://127.0.0.1:{port}'\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{shared}")).await.unwrap();
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
let snapshot = client.snapshot().await;
|
||||
if snapshot["peers"].as_array().is_some_and(|p| {
|
||||
p.iter().any(|v| {
|
||||
v["transports"].as_array().is_some_and(|t| t.len() >= 2)
|
||||
&& v["selected_transport"] == "udp"
|
||||
})
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
assert!(started.elapsed().as_secs() < 15, "UDP selection timed out");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
let peers = client.instance.peer_manager().list_peer_snapshots().await;
|
||||
let peer = &peers[0];
|
||||
let conn = peer
|
||||
.conns
|
||||
.iter()
|
||||
.find(|c| c.tunnel.as_ref().is_some_and(|t| t.tunnel_type == "udp"))
|
||||
.unwrap();
|
||||
client
|
||||
.instance
|
||||
.peer_manager()
|
||||
.close_peer_conn(peer.peer_id, &conn.conn_id.parse().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
if client.snapshot().await["peers"][0]["selected_transport"] == "tcp" {
|
||||
break;
|
||||
}
|
||||
assert!(started.elapsed().as_secs() < 5, "TCP backup timed out");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
client.stop().await;
|
||||
server.stop().await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn application_learns_filters_and_withdraws_advertised_subnets() {
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let port = std::net::UdpSocket::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let identity = "[network_identity]\nnetwork_name = 'auto-subnets-test'\nnetwork_secret = 'test-only'\n";
|
||||
let server_config = TomlConfig::new_from_str(&format!("ipv4 = '10.253.81.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n{identity}[flags]\nno_tun = true\nuse_smoltcp = true")).unwrap();
|
||||
let server = create_native_instance(server_config.clone()).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let client = Engine::start(&format!("ipv4 = '10.253.80.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}")).await.unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(20), async {
|
||||
loop {
|
||||
let snapshot = client.snapshot().await;
|
||||
let routes = snapshot["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap();
|
||||
if routes.iter().any(|r| r == "10.253.79.0/24") {
|
||||
assert_eq!(routes.len(), 1, "unfiltered advertisements: {routes:?}");
|
||||
assert_eq!(snapshot["platform_network"]["ready"], false);
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let tcp_port = listener.local_addr().unwrap().port();
|
||||
let echo = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut bytes = [0; 4];
|
||||
stream.read_exact(&mut bytes).await.unwrap();
|
||||
stream.write_all(&bytes).await.unwrap();
|
||||
let _ = stream.read(&mut bytes).await;
|
||||
});
|
||||
let mut tcp = client
|
||||
.instance
|
||||
.data_plane_tcp_connect(
|
||||
format!("10.253.79.1:{tcp_port}").parse().unwrap(),
|
||||
Duration::from_secs(3),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
tcp.write_all(b"auto").await.unwrap();
|
||||
let mut bytes = [0; 4];
|
||||
tcp.read_exact(&mut bytes).await.unwrap();
|
||||
assert_eq!(&bytes, b"auto");
|
||||
drop(tcp);
|
||||
echo.abort();
|
||||
let _ = echo.await;
|
||||
let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let udp_port = receiver.local_addr().unwrap().port();
|
||||
let sender = client
|
||||
.instance
|
||||
.data_plane_udp_bind(7009, Duration::from_secs(3))
|
||||
.await
|
||||
.unwrap();
|
||||
sender
|
||||
.send_to(
|
||||
b"udp-auto",
|
||||
format!("10.253.79.1:{udp_port}").parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut bytes = [0; 32];
|
||||
let (n, source) = receiver.recv_from(&mut bytes).await.unwrap();
|
||||
assert_eq!(&bytes[..n], b"udp-auto");
|
||||
receiver.send_to(&bytes[..n], source).await.unwrap();
|
||||
loop {
|
||||
let (n, _) = sender.recv_from(&mut bytes).await.unwrap();
|
||||
if &bytes[..n] == b"warm" {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(&bytes[..n], b"udp-auto");
|
||||
break;
|
||||
}
|
||||
server_config.clear_proxy_cidrs();
|
||||
let config =
|
||||
easytier_core::instance::CoreInstanceConfig::from_toml(&server_config).unwrap();
|
||||
server
|
||||
.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
|
||||
services: config.connectivity.runtime,
|
||||
peer: Arc::new(config.peer.snapshot),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
while !client.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
{
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
client.stop().await;
|
||||
server.stop().await;
|
||||
assert!(result.is_ok(), "automatic subnet test timed out");
|
||||
}
|
||||
|
||||
const BASE: &str = "ipv4 = '10.77.0.11'\n[network_identity]\nnetwork_name = 'test'\nnetwork_secret = 'never-log-me'\n";
|
||||
#[test]
|
||||
fn system_mode_learns_routes_automatically() {
|
||||
let input = format!("{BASE}\n[runtime]\nmode = 'system_vpn'");
|
||||
let config = parse_config(&input).unwrap();
|
||||
assert!(!config.get_flags().no_tun && !config.get_flags().use_smoltcp);
|
||||
assert_eq!(config.get_routes(), None);
|
||||
assert!(parse_config(&format!("{input}\nsubnet_routes = ['192.168.21.0/24']")).is_err());
|
||||
assert!(!config.get_flags().accept_dns && !config.get_flags().enable_exit_node);
|
||||
assert!(parse_config(&format!("{input}\n[flags]\nno_tun = true")).is_err());
|
||||
assert!(parse_config(&input.replace("10.77.0.11", "8.8.8.8")).is_err());
|
||||
assert!(parse_config(&input.replace("10.77.0.11", "10.77.0.11/8")).is_err());
|
||||
assert!(parse_config(&input.replace("10.77.0.11", "10.77.0.0/24")).is_err());
|
||||
assert!(parse_config(&input.replace("ipv4 = '10.77.0.11'", "dhcp = true")).is_err());
|
||||
assert!(parse_config(&format!("{input}\nroutes = ['0.0.0.0/0']")).is_err());
|
||||
assert!(parse_config(&format!("{BASE}\n[runtime]\nmode = 'typo'")).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn application_invariants() {
|
||||
let c = parse_config(BASE).unwrap();
|
||||
let f = c.get_flags();
|
||||
assert!(f.no_tun && f.use_smoltcp && f.disable_upnp && f.enable_encryption);
|
||||
assert!(!f.accept_dns && !f.proxy_forward_by_system && !f.enable_exit_node);
|
||||
}
|
||||
#[test]
|
||||
fn reject_system_and_unknown_options() {
|
||||
for field in ["exit_nodes = []", "proxy_network = []", "typo = true"] {
|
||||
assert!(parse_config(&format!("{field}\n{BASE}")).is_err());
|
||||
}
|
||||
assert!(parse_config(&format!("{BASE}\n[flags]\nno_tun = false")).is_err());
|
||||
assert!(parse_config(&format!("{BASE}\n[flags]\naccept_dns = true")).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn secrets_do_not_leak_in_parse_errors() {
|
||||
let input = "ipv4 = 'secret-address'\n[network_identity]\nnetwork_secret = 'never-log-me'";
|
||||
assert!(
|
||||
!parse_config(input)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("never-log-me")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)]
|
||||
#[path = "../../../vendor/easytier/easytier-core/src/peers/meshport_optimization.rs"]
|
||||
mod routing_policy_tests;
|
||||
@@ -0,0 +1,100 @@
|
||||
use cidr::Ipv4Cidr;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn overlaps(base: Ipv4Addr, prefix: u8, other: Ipv4Addr, other_mask: u32) -> bool {
|
||||
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0) & other_mask;
|
||||
u32::from(base) & mask == u32::from(other) & mask
|
||||
}
|
||||
|
||||
fn permitted(route: &Ipv4Cidr, overlay: Ipv4Addr, prefix: u8) -> bool {
|
||||
(16..=32).contains(&route.network_length())
|
||||
&& route.first_address().is_private()
|
||||
&& !overlaps(
|
||||
route.first_address(),
|
||||
route.network_length(),
|
||||
overlay,
|
||||
u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn allowed(route: &Ipv4Cidr, overlay: Ipv4Addr, prefix: u8) -> bool {
|
||||
if !permitted(route, overlay, prefix) {
|
||||
return false;
|
||||
}
|
||||
local_interfaces_allow(route)
|
||||
}
|
||||
|
||||
type InterfaceNetworks = Vec<(Ipv4Addr, u32)>;
|
||||
type InterfaceCache = Option<(std::time::Instant, Option<InterfaceNetworks>)>;
|
||||
fn local_interfaces_allow(route: &Ipv4Cidr) -> bool {
|
||||
use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static CACHE: OnceLock<Mutex<InterfaceCache>> = OnceLock::new();
|
||||
let mut cache = CACHE.get_or_init(|| Mutex::new(None)).lock().unwrap();
|
||||
if cache
|
||||
.as_ref()
|
||||
.is_none_or(|(time, _)| time.elapsed().as_secs() >= 2)
|
||||
{
|
||||
let networks = NetworkInterface::show().ok().map(|interfaces| {
|
||||
interfaces
|
||||
.into_iter()
|
||||
.flat_map(|iface| iface.addr)
|
||||
.filter_map(|addr| match addr {
|
||||
Addr::V4(v4) => Some((v4.ip, u32::from(v4.netmask?))),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
*cache = Some((std::time::Instant::now(), networks));
|
||||
}
|
||||
cache
|
||||
.as_ref()
|
||||
.and_then(|(_, networks)| networks.as_ref())
|
||||
.is_some_and(|networks| {
|
||||
networks.iter().all(|(ip, mask)| {
|
||||
!overlaps(route.first_address(), route.network_length(), *ip, *mask)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn rejects_defaults_public_broad_and_overlay_routes() {
|
||||
let overlay = "192.168.20.4".parse().unwrap();
|
||||
for text in [
|
||||
"0.0.0.0/0",
|
||||
"8.8.8.0/24",
|
||||
"10.0.0.0/8",
|
||||
"192.168.20.0/24",
|
||||
"192.168.0.0/16",
|
||||
] {
|
||||
assert!(!permitted(&text.parse().unwrap(), overlay, 24), "{text}");
|
||||
}
|
||||
assert!(permitted(&"192.168.21.0/24".parse().unwrap(), overlay, 24));
|
||||
assert!(permitted(&"10.5.0.1/32".parse().unwrap(), overlay, 24));
|
||||
}
|
||||
#[test]
|
||||
fn detects_physical_subnet_overlap() {
|
||||
let local = "10.10.8.54".parse().unwrap();
|
||||
assert!(overlaps(
|
||||
"10.10.0.0".parse().unwrap(),
|
||||
16,
|
||||
local,
|
||||
0xffffff00
|
||||
));
|
||||
assert!(overlaps(
|
||||
"10.10.8.201".parse().unwrap(),
|
||||
32,
|
||||
local,
|
||||
0xffffff00
|
||||
));
|
||||
assert!(!overlaps(
|
||||
"192.168.21.0".parse().unwrap(),
|
||||
24,
|
||||
local,
|
||||
0xffffff00
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "meshport-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "staticlib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
meshport.workspace = true
|
||||
meshport-easytier.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", default-features = false, features = ["std", "fmt", "registry"] }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
system-vpn = ["meshport/system-vpn"]
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef MESHPORT_H
|
||||
#define MESHPORT_H
|
||||
#include <stdint.h>
|
||||
#include <stdbool.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
uint32_t meshport_abi_version(void);
|
||||
uint64_t meshport_context_new(void);
|
||||
void meshport_context_free(uint64_t context);
|
||||
/* Blocking; run off the UI thread. Owned JSON result, free exactly once. */
|
||||
char *meshport_call(uint64_t context, const char *request_json);
|
||||
void meshport_string_free(char *response);
|
||||
#ifdef __ANDROID__
|
||||
/* Process-wide callback; keep valid until all native contexts have stopped.
|
||||
* Invoked on native workers. Return VpnService.protect(fd)'s result. */
|
||||
void meshport_set_android_socket_protector(bool (*callback)(int fd));
|
||||
#endif
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Optional, process-wide capture for the lab. SDK hosts retain their subscriber.
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io::{self, Write},
|
||||
sync::{LazyLock, Mutex},
|
||||
};
|
||||
use tracing_subscriber::{Layer, layer::SubscriberExt, util::SubscriberInitExt};
|
||||
|
||||
static RECORDS: LazyLock<Mutex<(u64, VecDeque<Value>)>> =
|
||||
LazyLock::new(|| Mutex::new((0, VecDeque::new())));
|
||||
static ENABLED: LazyLock<bool> = LazyLock::new(|| {
|
||||
let layer = tracing_subscriber::fmt::layer()
|
||||
.with_ansi(false)
|
||||
.with_writer(|| Capture(Vec::new()))
|
||||
.with_filter(tracing_subscriber::filter::filter_fn(|metadata| {
|
||||
metadata
|
||||
.target()
|
||||
.starts_with("easytier_core::connectivity::hole_punch")
|
||||
&& *metadata.level() <= tracing::Level::DEBUG
|
||||
}));
|
||||
tracing_subscriber::registry()
|
||||
.with(layer)
|
||||
.try_init()
|
||||
.is_ok()
|
||||
});
|
||||
|
||||
pub fn enable() -> bool {
|
||||
*ENABLED
|
||||
}
|
||||
pub fn snapshot() -> Vec<Value> {
|
||||
RECORDS.lock().unwrap().1.iter().cloned().collect()
|
||||
}
|
||||
struct Capture(Vec<u8>);
|
||||
impl Write for Capture {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
let remaining = 4096usize.saturating_sub(self.0.len());
|
||||
self.0
|
||||
.extend_from_slice(&bytes[..bytes.len().min(remaining)]);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Capture {
|
||||
fn drop(&mut self) {
|
||||
if self.0.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut records = RECORDS.lock().unwrap();
|
||||
records.0 += 1;
|
||||
let sequence = records.0;
|
||||
records.1.push_back(
|
||||
json!({"sequence": sequence, "message": String::from_utf8_lossy(&self.0).trim()}),
|
||||
);
|
||||
if records.1.len() > 200 {
|
||||
records.1.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn capture_is_opt_in_and_excludes_other_modules() {
|
||||
assert!(super::enable());
|
||||
tracing::warn!(target: "unrelated_application", "private unrelated log");
|
||||
tracing::warn!(target: "easytier_core::connectivity::hole_punch::test", dst_peer_id = 42, "diagnostic capture check");
|
||||
let records = super::snapshot();
|
||||
let text = serde_json::to_string(&records).unwrap();
|
||||
assert!(text.contains("diagnostic capture check"));
|
||||
assert!(text.contains("42"));
|
||||
assert!(!text.contains("private unrelated log"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
//! ABI v1: opaque numeric contexts and owned UTF-8 JSON responses.
|
||||
//! Blocking calls must execute on a foreign worker thread/isolate.
|
||||
mod diagnostics;
|
||||
use meshport::Network;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
ffi::{CStr, CString, c_char},
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
sync::{
|
||||
Arc, LazyLock, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::runtime::Runtime;
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
#[cfg(target_os = "android")]
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn meshport_set_android_socket_protector(
|
||||
callback: meshport_easytier::android::ProtectSocket,
|
||||
) {
|
||||
meshport_easytier::android::install_socket_protector(callback);
|
||||
}
|
||||
static CONTEXTS: LazyLock<Mutex<HashMap<u64, Arc<Context>>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
struct Context {
|
||||
runtime: Runtime,
|
||||
network: Mutex<Option<Network>>,
|
||||
tcp: tokio::sync::Mutex<HashMap<u64, meshport::TcpStream>>,
|
||||
udp: tokio::sync::Mutex<HashMap<u64, meshport::UdpSocket>>,
|
||||
}
|
||||
impl Drop for Context {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(slot) = self.network.get_mut()
|
||||
&& let Some(n) = slot.take()
|
||||
{
|
||||
self.runtime.block_on(n.stop());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn meshport_abi_version() -> u32 {
|
||||
1
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn meshport_context_new() -> u64 {
|
||||
catch_unwind(|| {
|
||||
let runtime = match tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(v) => v,
|
||||
Err(_) => return 0,
|
||||
};
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
CONTEXTS.lock().unwrap().insert(
|
||||
id,
|
||||
Arc::new(Context {
|
||||
runtime,
|
||||
network: Mutex::new(None),
|
||||
tcp: tokio::sync::Mutex::new(HashMap::new()),
|
||||
udp: tokio::sync::Mutex::new(HashMap::new()),
|
||||
}),
|
||||
);
|
||||
id
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn meshport_context_free(id: u64) {
|
||||
// Drop outside registry lock; in-flight calls retain an Arc until completion.
|
||||
let _ = catch_unwind(|| {
|
||||
let context = CONTEXTS.lock().unwrap().remove(&id);
|
||||
drop(context);
|
||||
});
|
||||
}
|
||||
fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
let op = request["op"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing op"))?;
|
||||
if op == "diagnostics_enable" {
|
||||
return Ok(json!({"enabled": diagnostics::enable(), "scope": "process"}));
|
||||
}
|
||||
if op == "validate" {
|
||||
use meshport_easytier::ConfigLoader;
|
||||
let input = request["toml"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
|
||||
let config = meshport::validate_config(input)?;
|
||||
let flags = config.get_flags();
|
||||
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"}});
|
||||
// Only return credentials when the local caller explicitly requests a
|
||||
// form projection. Ordinary validation remains free of credentials.
|
||||
if request["include_profile"].as_bool() == Some(true) {
|
||||
let identity = config.get_network_identity();
|
||||
let optimization = meshport_easytier::optimization_config(input)?;
|
||||
result["profile"] = json!({
|
||||
"network_name": identity.network_name,
|
||||
"network_secret": identity.network_secret.unwrap_or_default(),
|
||||
"hostname": config.get_hostname(),
|
||||
"ipv4": config.get_ipv4().map(|ip| ip.to_string()).unwrap_or_default(),
|
||||
"dhcp": config.get_dhcp(),
|
||||
"peers": config.get_peers().iter().map(|peer| peer.uri.to_string()).collect::<Vec<_>>(),
|
||||
"enable_ipv6": flags.enable_ipv6,
|
||||
"latency_first": flags.latency_first,
|
||||
"optimization": optimization
|
||||
});
|
||||
}
|
||||
return Ok(result);
|
||||
}
|
||||
let mut network = context
|
||||
.network
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("context lock poisoned"))?;
|
||||
match op {
|
||||
#[cfg(target_os = "android")]
|
||||
"attach_tun" => {
|
||||
let fd = i32::try_from(
|
||||
request["fd"]
|
||||
.as_i64()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing fd"))?,
|
||||
)?;
|
||||
network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("not started"))?
|
||||
.attach_tun_fd(fd)?;
|
||||
Ok(json!({"attached": true}))
|
||||
}
|
||||
"start" => {
|
||||
anyhow::ensure!(
|
||||
network.is_none(),
|
||||
"already started; stop before applying a new configuration"
|
||||
);
|
||||
let config = request["toml"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
|
||||
*network = Some(context.runtime.block_on(Network::start(config))?);
|
||||
Ok(json!({"engine_started": true}))
|
||||
}
|
||||
"stop" => {
|
||||
context.tcp.blocking_lock().clear();
|
||||
context.udp.blocking_lock().clear();
|
||||
if let Some(n) = network.take() {
|
||||
context.runtime.block_on(n.stop());
|
||||
}
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"status" => match network.as_ref() {
|
||||
Some(n) => {
|
||||
let mut snapshot = context.runtime.block_on(n.snapshot());
|
||||
let traces = diagnostics::snapshot()
|
||||
.into_iter()
|
||||
.map(|mut trace| {
|
||||
if let Some(message) = trace["message"].as_str() {
|
||||
trace["message"] = json!(n.redact_diagnostic(message));
|
||||
}
|
||||
trace
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
snapshot["diagnostic_traces"] = json!(traces);
|
||||
Ok(snapshot)
|
||||
}
|
||||
None => Ok(json!({"state": "Stopped", "peer_count": 0, "application_only": true})),
|
||||
},
|
||||
"quality_sample" => {
|
||||
let network = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
let id = request["resource"]
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing resource"))?;
|
||||
let target = request["target"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing target"))?
|
||||
.parse::<std::net::SocketAddr>()?;
|
||||
anyhow::ensure!(target.is_ipv4(), "IPv4 required");
|
||||
let sequence = request["sequence"]
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing sequence"))?;
|
||||
let timeout = request["timeout_ms"].as_u64().unwrap_or(1000);
|
||||
anyhow::ensure!(
|
||||
(100..=5000).contains(&timeout),
|
||||
"quality timeout must be 100-5000 ms"
|
||||
);
|
||||
context.runtime.block_on(async {
|
||||
let sockets = context.udp.lock().await;
|
||||
let socket = sockets
|
||||
.get(&id)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid UDP resource"))?;
|
||||
network
|
||||
.sample_udp_quality(socket, target, sequence, Duration::from_millis(timeout))
|
||||
.await
|
||||
})
|
||||
}
|
||||
"tcp_connect" | "udp_bind" => {
|
||||
let n = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
let id = NEXT.fetch_add(1, Ordering::Relaxed);
|
||||
if op == "tcp_connect" {
|
||||
let target = request["target"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing target"))?
|
||||
.parse()?;
|
||||
let stream = context
|
||||
.runtime
|
||||
.block_on(n.connect_tcp(target, Duration::from_secs(5)))?;
|
||||
context.tcp.blocking_lock().insert(id, stream);
|
||||
} else {
|
||||
let port = request["port"].as_u64().unwrap_or(0);
|
||||
anyhow::ensure!(port <= 65535, "invalid UDP port");
|
||||
let socket = context
|
||||
.runtime
|
||||
.block_on(n.bind_udp(port as u16, Duration::from_secs(5)))?;
|
||||
context.udp.blocking_lock().insert(id, socket);
|
||||
}
|
||||
Ok(json!({"resource": id}))
|
||||
}
|
||||
"resource_close" => {
|
||||
let id = request["resource"]
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing resource"))?;
|
||||
let tcp = context.tcp.blocking_lock().remove(&id).is_some();
|
||||
let udp = context.udp.blocking_lock().remove(&id).is_some();
|
||||
anyhow::ensure!(tcp || udp, "invalid resource");
|
||||
Ok(json!({"closed": true}))
|
||||
}
|
||||
"tcp_read" | "tcp_write" | "udp_send" | "udp_receive" => {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
anyhow::ensure!(network.is_some(), "network is stopped");
|
||||
let id = request["resource"]
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing resource"))?;
|
||||
let timeout = request["timeout_ms"].as_u64().unwrap_or(5000);
|
||||
anyhow::ensure!((1..=30000).contains(&timeout), "invalid timeout");
|
||||
let mut bytes = Vec::new();
|
||||
if op.ends_with("write") || op == "udp_send" {
|
||||
let data = request["bytes"]
|
||||
.as_array()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing bytes array"))?;
|
||||
anyhow::ensure!(data.len() <= 65507, "payload too large");
|
||||
for b in data {
|
||||
let b = b
|
||||
.as_u64()
|
||||
.filter(|b| *b <= 255)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid byte"))?;
|
||||
bytes.push(b as u8);
|
||||
}
|
||||
}
|
||||
context.runtime.block_on(async {
|
||||
tokio::time::timeout(Duration::from_millis(timeout), async {
|
||||
if op.starts_with("tcp") {
|
||||
let mut streams = context.tcp.lock().await;
|
||||
let stream = streams
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid TCP resource"))?;
|
||||
if op == "tcp_write" {
|
||||
stream.write_all(&bytes).await?;
|
||||
Ok(json!({"written": bytes.len()}))
|
||||
} else {
|
||||
let max = request["max_bytes"].as_u64().unwrap_or(16384);
|
||||
anyhow::ensure!((1..=65535).contains(&max), "invalid read size");
|
||||
let mut buffer = vec![0; max as usize];
|
||||
let size = stream.read(&mut buffer).await?;
|
||||
buffer.truncate(size);
|
||||
Ok(json!({"bytes": buffer, "eof": size == 0}))
|
||||
}
|
||||
} else {
|
||||
let sockets = context.udp.lock().await;
|
||||
let socket = sockets
|
||||
.get(&id)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid UDP resource"))?;
|
||||
if op == "udp_send" {
|
||||
let addr = request["target"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing target"))?
|
||||
.parse()?;
|
||||
let written = socket.send_to(&bytes, addr).await?;
|
||||
Ok(json!({"written": written}))
|
||||
} else {
|
||||
let mut buffer = vec![0; 65535];
|
||||
let (size, source) = socket.recv_from(&mut buffer).await?;
|
||||
buffer.truncate(size);
|
||||
Ok(json!({"bytes": buffer, "source": source.to_string()}))
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
})?
|
||||
}
|
||||
"probe" => {
|
||||
let n = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
let target = request["target"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing target"))?
|
||||
.parse()?;
|
||||
let protocol = request["protocol"].as_str().unwrap_or("TCP");
|
||||
anyhow::ensure!(
|
||||
["TCP", "UDP"].contains(&protocol),
|
||||
"protocol must be TCP or UDP"
|
||||
);
|
||||
let timeout_ms = request["timeout_ms"].as_u64().unwrap_or(5000);
|
||||
anyhow::ensure!(
|
||||
(1..=30000).contains(&timeout_ms),
|
||||
"timeout must be 1..30000 ms"
|
||||
);
|
||||
context.runtime.block_on(n.probe(
|
||||
target,
|
||||
protocol == "UDP",
|
||||
request["echo"].as_bool().unwrap_or(false),
|
||||
Duration::from_millis(timeout_ms),
|
||||
))
|
||||
}
|
||||
_ => anyhow::bail!("unknown operation"),
|
||||
}
|
||||
}
|
||||
/// # Safety
|
||||
/// request must be a valid NUL-terminated UTF-8 C string for the duration of the call.
|
||||
/// Return is owned by MeshPort; release exactly once with meshport_string_free.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn meshport_call(id: u64, request: *const c_char) -> *mut c_char {
|
||||
let response = catch_unwind(AssertUnwindSafe(|| -> anyhow::Result<Value> {
|
||||
anyhow::ensure!(!request.is_null(), "request is null");
|
||||
let text = unsafe { CStr::from_ptr(request) }.to_str()?;
|
||||
anyhow::ensure!(text.len() <= 131072, "request exceeds 128 KiB");
|
||||
let parsed: Value =
|
||||
serde_json::from_str(text).map_err(|_| anyhow::anyhow!("invalid JSON request"))?;
|
||||
let context = CONTEXTS
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&id)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid context"))?;
|
||||
dispatch(&context, parsed)
|
||||
}));
|
||||
let value = match response {
|
||||
Ok(Ok(v)) => json!({"ok": true, "data": v}),
|
||||
Ok(Err(e)) => json!({"ok": false, "error": e.to_string()}),
|
||||
Err(_) => json!({"ok": false, "error": "internal panic"}),
|
||||
};
|
||||
CString::new(value.to_string()).unwrap().into_raw()
|
||||
}
|
||||
/// # Safety
|
||||
/// ptr must be null or an unfreed pointer returned by meshport_call.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn meshport_string_free(ptr: *mut c_char) {
|
||||
if !ptr.is_null() {
|
||||
drop(unsafe { CString::from_raw(ptr) });
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn call(id: u64, s: &str) -> Value {
|
||||
let q = CString::new(s).unwrap();
|
||||
unsafe {
|
||||
let p = meshport_call(id, q.as_ptr());
|
||||
let result = serde_json::from_str(CStr::from_ptr(p).to_str().unwrap()).unwrap();
|
||||
meshport_string_free(p);
|
||||
result
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn abi_invalid_handle_and_lifecycle() {
|
||||
let id = meshport_context_new();
|
||||
assert_ne!(id, 0);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"probe","target":"10.0.0.2:1234"}"#)["ok"],
|
||||
false
|
||||
);
|
||||
meshport_context_free(id);
|
||||
meshport_context_free(id);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["ok"], false);
|
||||
}
|
||||
#[test]
|
||||
fn validation_only_projects_credentials_when_requested() {
|
||||
let id = meshport_context_new();
|
||||
let config = "hostname = 'saved-node'\nipv4 = '10.79.0.11/24'\nlisteners = []\n[[peer]]\nuri = 'tcp://127.0.0.1:1234'\n[network_identity]\nnetwork_name = 'saved-network'\nnetwork_secret = 'test-only-secret'\n";
|
||||
let ordinary = call(id, &json!({"op": "validate", "toml": config}).to_string());
|
||||
assert_eq!(ordinary["ok"], true);
|
||||
assert!(!ordinary.to_string().contains("test-only-secret"));
|
||||
let projected = call(
|
||||
id,
|
||||
&json!({"op": "validate", "toml": config, "include_profile": true}).to_string(),
|
||||
);
|
||||
assert_eq!(projected["ok"], true);
|
||||
assert_eq!(
|
||||
projected["data"]["profile"]["network_secret"],
|
||||
"test-only-secret"
|
||||
);
|
||||
assert_eq!(projected["data"]["profile"]["ipv4"], "10.79.0.11/24");
|
||||
assert_eq!(
|
||||
projected["data"]["profile"]["peers"][0],
|
||||
"tcp://127.0.0.1:1234"
|
||||
);
|
||||
meshport_context_free(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "meshport-netstack"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
easytier-core.workspace = true
|
||||
anyhow.workspace = true
|
||||
tokio.workspace = true
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Reuse EasyTier's instance-scoped smoltcp plane rather than creating a second stack.
|
||||
use anyhow::{Result, ensure};
|
||||
pub use easytier_core::gateway::{
|
||||
DataPlaneTcpListener as TcpListener, DataPlaneTcpStream as TcpStream,
|
||||
DataPlaneUdpSocket as UdpSocket,
|
||||
};
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
pub async fn tcp_echo(
|
||||
stream: &mut TcpStream,
|
||||
payload: &[u8],
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<u8>> {
|
||||
tokio::time::timeout(timeout, async {
|
||||
stream.write_all(payload).await?;
|
||||
let mut received = vec![0; payload.len()];
|
||||
stream.read_exact(&mut received).await?;
|
||||
ensure!(received == payload, "TCP echo data mismatch");
|
||||
Ok(received)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
pub async fn udp_echo(
|
||||
socket: &UdpSocket,
|
||||
target: SocketAddr,
|
||||
payload: &[u8],
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<u8>> {
|
||||
ensure!(
|
||||
payload.len() <= 65507,
|
||||
"UDP payload exceeds IPv4 datagram limit"
|
||||
);
|
||||
tokio::time::timeout(timeout, async {
|
||||
socket.send_to(payload, target).await?;
|
||||
let mut buffer = vec![0; 65535];
|
||||
loop {
|
||||
let (len, source) = socket.recv_from(&mut buffer).await?;
|
||||
if source != target {
|
||||
continue;
|
||||
}
|
||||
ensure!(&buffer[..len] == payload, "UDP echo data mismatch");
|
||||
return Ok(buffer[..len].to_vec());
|
||||
}
|
||||
})
|
||||
.await?
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "meshport"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
meshport-easytier.workspace = true
|
||||
meshport-netstack.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
system-vpn = ["meshport-easytier/system-vpn"]
|
||||
@@ -0,0 +1,25 @@
|
||||
use meshport::Network;
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
anyhow::ensure!(
|
||||
args.len() == 3,
|
||||
"usage: tcp_client <config.toml> <virtual-ip:port>"
|
||||
);
|
||||
let config = std::fs::read_to_string(&args[1])?;
|
||||
let target: SocketAddr = args[2].parse()?;
|
||||
let network = Network::start(&config).await?;
|
||||
let result = async {
|
||||
let mut stream = network.connect_tcp(target, Duration::from_secs(10)).await?;
|
||||
stream.write_all(b"MeshPort TCP example").await?;
|
||||
let mut buffer = [0; 256];
|
||||
let n = tokio::time::timeout(Duration::from_secs(5), stream.read(&mut buffer)).await??;
|
||||
println!("Received {n} bytes: {:?}", &buffer[..n]);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
network.stop().await;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//! EasyTier networking SDK: application sockets by default, opt-in macOS system VPN.
|
||||
mod quality;
|
||||
mod system_probe;
|
||||
use anyhow::{Result, ensure};
|
||||
use meshport_easytier::Engine;
|
||||
pub use meshport_easytier::parse_config as validate_config;
|
||||
pub use meshport_netstack::{TcpListener, TcpStream, UdpSocket};
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub struct Network {
|
||||
engine: Engine,
|
||||
}
|
||||
impl Network {
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn attach_tun_fd(&self, fd: i32) -> Result<()> {
|
||||
self.engine.attach_tun_fd(fd)
|
||||
}
|
||||
/// Running means the engine is started, not that a remote peer is reachable.
|
||||
pub async fn start(toml: &str) -> Result<Self> {
|
||||
Ok(Self {
|
||||
engine: Engine::start(toml).await?,
|
||||
})
|
||||
}
|
||||
pub async fn stop(&self) {
|
||||
self.engine.stop().await;
|
||||
}
|
||||
/// Removes this network's secret from diagnostic text before export.
|
||||
pub fn redact_diagnostic(&self, text: &str) -> String {
|
||||
self.engine.redact_diagnostic(text)
|
||||
}
|
||||
pub async fn snapshot(&self) -> serde_json::Value {
|
||||
self.engine.snapshot().await
|
||||
}
|
||||
pub async fn connect_tcp(&self, target: SocketAddr, timeout: Duration) -> Result<TcpStream> {
|
||||
self.require_application_mode()?;
|
||||
ensure!(
|
||||
target.is_ipv4(),
|
||||
"IPv6 data plane is not supported in this prototype"
|
||||
);
|
||||
Ok(self
|
||||
.engine
|
||||
.instance
|
||||
.data_plane_tcp_connect(target, timeout)
|
||||
.await?)
|
||||
}
|
||||
pub async fn listen_tcp(&self, port: u16, timeout: Duration) -> Result<TcpListener> {
|
||||
self.require_application_mode()?;
|
||||
Ok(self
|
||||
.engine
|
||||
.instance
|
||||
.data_plane_tcp_bind(port, timeout)
|
||||
.await?)
|
||||
}
|
||||
pub async fn bind_udp(&self, port: u16, timeout: Duration) -> Result<UdpSocket> {
|
||||
self.require_application_mode()?;
|
||||
Ok(self
|
||||
.engine
|
||||
.instance
|
||||
.data_plane_udp_bind(port, timeout)
|
||||
.await?)
|
||||
}
|
||||
fn require_application_mode(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.engine.mode == meshport_easytier::RuntimeMode::Application,
|
||||
"use ordinary OS sockets in system_vpn mode"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub async fn probe(
|
||||
&self,
|
||||
target: SocketAddr,
|
||||
udp: bool,
|
||||
echo: bool,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value> {
|
||||
if self.engine.mode == meshport_easytier::RuntimeMode::SystemVpn {
|
||||
return system_probe::probe(target, udp, echo, timeout).await;
|
||||
}
|
||||
ensure!(!udp || echo, "UDP tests require a cooperating echo server");
|
||||
let started = Instant::now();
|
||||
let payload = b"MeshPort echo verification v1";
|
||||
let bytes = if udp {
|
||||
let socket = self.bind_udp(0, timeout).await?;
|
||||
meshport_netstack::udp_echo(&socket, target, payload, timeout)
|
||||
.await?
|
||||
.len()
|
||||
} else {
|
||||
let mut stream = self.connect_tcp(target, timeout).await?;
|
||||
if echo {
|
||||
meshport_netstack::tcp_echo(&mut stream, payload, timeout)
|
||||
.await?
|
||||
.len()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
Ok(
|
||||
serde_json::json!({"protocol": if udp { "UDP" } else { "TCP" }, "target": target.to_string(), "elapsed_ms": started.elapsed().as_secs_f64()*1000.0, "verified_bytes": bytes, "kind": if echo { "echo_roundtrip" } else { "tcp_connect" }}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use crate::{Network, UdpSocket};
|
||||
use anyhow::Result;
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
impl Network {
|
||||
/// Samples a reusable UDP echo socket. Ignores late/foreign replies.
|
||||
pub async fn sample_udp_quality(
|
||||
&self,
|
||||
socket: &UdpSocket,
|
||||
target: SocketAddr,
|
||||
sequence: u64,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value> {
|
||||
let before = self.snapshot().await;
|
||||
let destination = before["routes"]
|
||||
.as_array()
|
||||
.and_then(|routes| {
|
||||
routes.iter().find(|r| {
|
||||
r["ipv4"].as_str().is_some_and(|ip| {
|
||||
ip.split('/').next() == Some(target.ip().to_string().as_str())
|
||||
})
|
||||
})
|
||||
})
|
||||
.cloned();
|
||||
let payload = format!("MeshPort quality v1 {sequence}").into_bytes();
|
||||
let started = Instant::now();
|
||||
let result = tokio::time::timeout(timeout, async {
|
||||
socket.send_to(&payload, target).await?;
|
||||
let mut bytes = [0; 2048];
|
||||
loop {
|
||||
let (n, source) = socket.recv_from(&mut bytes).await?;
|
||||
if source == target && bytes[..n] == payload {
|
||||
return Ok::<_, anyhow::Error>(());
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let success = matches!(result, Ok(Ok(())));
|
||||
let elapsed_ms = success.then(|| started.elapsed().as_secs_f64() * 1000.0);
|
||||
let after = self.snapshot().await;
|
||||
let peer_id = destination.as_ref().and_then(|d| d["peer_id"].as_u64());
|
||||
let after_hop = after["routes"]
|
||||
.as_array()
|
||||
.and_then(|rows| rows.iter().find(|r| r["peer_id"].as_u64() == peer_id))
|
||||
.and_then(|r| r["next_hop_peer_id"].as_u64());
|
||||
let before_hop = destination
|
||||
.as_ref()
|
||||
.and_then(|d| d["next_hop_peer_id"].as_u64());
|
||||
Ok(serde_json::json!({"success": success, "sequence": sequence,
|
||||
"elapsed_ms": elapsed_ms,
|
||||
"next_hop_peer_id": before_hop,
|
||||
"next_hop_after": after_hop, "route_changed": before_hop != after_hop,
|
||||
"target_peer_id": destination.as_ref().and_then(|d| d["peer_id"].as_u64()),
|
||||
"kind": "udp_echo_roundtrip", "error": if success {None} else {Some("timeout_or_io_error")}
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use anyhow::{Result, ensure};
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
pub async fn probe(
|
||||
target: SocketAddr,
|
||||
udp: bool,
|
||||
echo: bool,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value> {
|
||||
ensure!(target.is_ipv4(), "IPv4 required");
|
||||
ensure!(!udp || echo, "UDP tests require a cooperating echo server");
|
||||
let started = Instant::now();
|
||||
let payload = b"MeshPort system socket echo v1";
|
||||
let bytes = tokio::time::timeout(timeout, async {
|
||||
if udp {
|
||||
let socket = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
||||
socket.connect(target).await?;
|
||||
socket.send(payload).await?;
|
||||
let mut bytes = [0; 2048];
|
||||
let n = socket.recv(&mut bytes).await?;
|
||||
ensure!(&bytes[..n] == payload, "echo data mismatch");
|
||||
Ok::<usize, anyhow::Error>(n)
|
||||
} else {
|
||||
let mut socket = tokio::net::TcpStream::connect(target).await?;
|
||||
if !echo {
|
||||
return Ok(0);
|
||||
}
|
||||
socket.write_all(payload).await?;
|
||||
let mut bytes = vec![0; payload.len()];
|
||||
socket.read_exact(&mut bytes).await?;
|
||||
ensure!(bytes == payload, "echo data mismatch");
|
||||
Ok(bytes.len())
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
Ok(
|
||||
serde_json::json!({"protocol": if udp {"UDP"} else {"TCP"}, "target": target.to_string(),
|
||||
"elapsed_ms": started.elapsed().as_secs_f64()*1000.0, "verified_bytes": bytes,
|
||||
"kind": if echo {"echo_roundtrip"} else {"tcp_connect"}, "socket_scope": "system"}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use meshport::Network;
|
||||
use std::{net::SocketAddr, time::Duration};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
fn config(ip: &str, port: u16, server: bool) -> String {
|
||||
let transport = if server {
|
||||
format!("listeners = ['udp://127.0.0.1:{port}']\n")
|
||||
} else {
|
||||
format!("listeners = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n")
|
||||
};
|
||||
format!(
|
||||
"ipv4 = '{ip}'\nstun_servers = []\nstun_servers_v6 = []\n{transport}\n[network_identity]\nnetwork_name = 'meshport-test'\nnetwork_secret = 'test-only'\n[flags]\ndefault_protocol = 'udp'\n"
|
||||
)
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn real_overlay_tcp_udp_and_restart() {
|
||||
let port = std::net::UdpSocket::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let server = Network::start(&config("10.77.0.2", port, true))
|
||||
.await
|
||||
.unwrap();
|
||||
let client = Network::start(&config("10.77.0.11", port, false))
|
||||
.await
|
||||
.unwrap();
|
||||
let timeout = Duration::from_secs(10);
|
||||
let mut listener = server.listen_tcp(7007, timeout).await.unwrap();
|
||||
let tcp_echo = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let mut bytes = [0; 128];
|
||||
let n = stream.read(&mut bytes).await.unwrap();
|
||||
stream.write_all(&bytes[..n]).await.unwrap();
|
||||
// Keep the connection alive until the client consumes its echo.
|
||||
let _ = stream.read(&mut bytes).await;
|
||||
});
|
||||
let udp = server.bind_udp(7007, timeout).await.unwrap();
|
||||
let client_udp = client.bind_udp(0, timeout).await.unwrap();
|
||||
// Upstream UDP is outbound-flow scoped; register the known remote first.
|
||||
udp.send_to(b"warmup", client_udp.local_addr())
|
||||
.await
|
||||
.unwrap();
|
||||
let udp_echo = tokio::spawn(async move {
|
||||
let mut bytes = [0; 128];
|
||||
for _ in 0..4 {
|
||||
let (n, addr) = udp.recv_from(&mut bytes).await.unwrap();
|
||||
udp.send_to(&bytes[..n], addr).await.unwrap();
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
});
|
||||
let target: SocketAddr = "10.77.0.2:7007".parse().unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
while client.snapshot().await["peer_count"].as_u64().unwrap() == 0 {
|
||||
assert!(started.elapsed() < timeout, "peer discovery timed out");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
let before = client.snapshot().await;
|
||||
assert_eq!(before["connectivity"]["disable_p2p"], false);
|
||||
assert_eq!(before["connectivity"]["disable_udp_hole_punching"], false);
|
||||
assert_eq!(before["connectivity"]["disable_tcp_hole_punching"], false);
|
||||
assert_eq!(before["connectivity"]["listeners"], serde_json::json!([]));
|
||||
assert!(
|
||||
!before["peers"][0]["transports"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let tcp = client.probe(target, false, true, timeout).await.unwrap();
|
||||
assert!(tcp["verified_bytes"].as_u64().unwrap() > 0);
|
||||
let received = meshport_netstack::udp_echo(&client_udp, target, b"udp-echo", timeout)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(received, b"udp-echo");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
let after = client.snapshot().await;
|
||||
assert!(!after["native_events"].as_array().unwrap().is_empty());
|
||||
assert!(!after.to_string().contains("test-only"));
|
||||
assert!(
|
||||
after["traffic"]["rx_bytes"].as_u64().unwrap()
|
||||
> before["traffic"]["rx_bytes"].as_u64().unwrap()
|
||||
);
|
||||
assert!(
|
||||
after["traffic"]["tx_bytes"].as_u64().unwrap()
|
||||
> before["traffic"]["tx_bytes"].as_u64().unwrap()
|
||||
);
|
||||
assert!(after["traffic"]["rx_bytes_per_second"].as_f64().unwrap() > 0.0);
|
||||
assert!(after["peers"][0]["rx_bytes"].as_u64().unwrap() > 0);
|
||||
let started = std::time::Instant::now();
|
||||
while client.snapshot().await["peers"][0]["latency_ms"]
|
||||
.as_f64()
|
||||
.is_none()
|
||||
{
|
||||
assert!(
|
||||
started.elapsed() < timeout,
|
||||
"link RTT measurement timed out"
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
for sequence in 0..3 {
|
||||
let sample = client
|
||||
.sample_udp_quality(&client_udp, target, sequence, timeout)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(sample["success"], true);
|
||||
assert!(sample["elapsed_ms"].as_f64().unwrap() > 0.0);
|
||||
assert_eq!(sample["next_hop_peer_id"], sample["target_peer_id"]);
|
||||
}
|
||||
tcp_echo.abort();
|
||||
udp_echo.abort();
|
||||
client.stop().await;
|
||||
server.stop().await;
|
||||
client.stop().await;
|
||||
for _ in 0..3 {
|
||||
let client = Network::start(&config("10.77.0.11", port, false))
|
||||
.await
|
||||
.unwrap();
|
||||
client.stop().await;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user