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
+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"}),
)
}