Initial MeshPort SDK and cross-platform client

This commit is contained in:
shenlei
2026-10-10 15:16:32 +09:00
commit e73e599165
664 changed files with 209894 additions and 0 deletions
+17
View File
@@ -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"]
+25
View File
@@ -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
}
+104
View File
@@ -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" }}),
)
}
}
+59
View File
@@ -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")}
}))
}
}
+44
View File
@@ -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"}),
)
}
+121
View File
@@ -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;
}
}