Merge main into feature/ava2-unlock
Conflicts resolved by keeping both sides: AVA2 attribute lock materials (50348/50349) and battle pass tickets from main alongside the unlock branch's costume enchants, talismans and new rings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+14
@@ -44,3 +44,17 @@ __pycache__/
|
||||
/android/app/build/
|
||||
/android/build/
|
||||
/android/local.properties
|
||||
|
||||
/Client/autohunt.cfg
|
||||
|
||||
# MeshPort private network identity; SDK build output normally lives under /build.
|
||||
/config/meshport.private.toml
|
||||
/third_party/meshport/target/
|
||||
|
||||
# Local build outputs, caches and legacy restructure leftovers
|
||||
/build_*/
|
||||
/.codex/
|
||||
/android-native/
|
||||
/extension/
|
||||
/script/
|
||||
/test/
|
||||
|
||||
@@ -30,6 +30,7 @@ endif()
|
||||
add_subdirectory(third_party)
|
||||
add_subdirectory(src/codepage)
|
||||
if(MT_BUILD_PORT OR MT_BUILD_NATIVE_RENDER)
|
||||
add_subdirectory(src/meshport)
|
||||
add_subdirectory(src/port)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
|
||||
## macOS
|
||||
|
||||
需要 CMake、SDL3、Vulkan loader、MoltenVK、glslc(第三方库均已随仓库提供源码,无需子模块):
|
||||
需要 Rust 1.95+、protoc、CMake、SDL3、Vulkan loader、MoltenVK、glslc(第三方库均已随仓库提供源码,无需子模块):
|
||||
|
||||
```sh
|
||||
./scripts/build_meshport.sh macos
|
||||
cmake -S . -B build/release -DCMAKE_BUILD_TYPE=Release \
|
||||
-DMT_BUILD_NATIVE_RENDER=ON -DCMAKE_PREFIX_PATH=/opt/homebrew
|
||||
cmake --build build/release --target mt_native_render -j8
|
||||
@@ -14,6 +15,8 @@ cmake --build build/release --target mt_native_render -j8
|
||||
--live-client "/path/to/40250/Client" --login-screen --width 1024 --height 768
|
||||
```
|
||||
|
||||
MeshPort SDK 源码在 `third_party/meshport`,无需单独检出 MeshPort 项目。频道查询、登录、注册、地图/公会连接及 UDP 都在公共网络层判断:同网段直连,跨网段组网,使用 DHCP 动态 IP;远端连接验证成功后提示“组网成功”。私有配置与构建说明见 [docs/MESHPORT.md](docs/MESHPORT.md)。
|
||||
|
||||
详见 [src/host/README.md](src/host/README.md)。
|
||||
|
||||
## Android
|
||||
|
||||
@@ -74,11 +74,15 @@ if [ ! -f "$OUT/sdl3/lib/libSDL3.so" ] || [ ! -f "$OUT/sdl3/.page16k" ]; then
|
||||
touch "$OUT/sdl3/.page16k"
|
||||
fi
|
||||
|
||||
# --- Embedded application-only networking SDK (source lives in this repository) ---
|
||||
"$REPO/scripts/build_meshport.sh" android
|
||||
|
||||
# --- libmain.so (src/host + port_platform + embedded Python) and its assets ---
|
||||
cmake -S . -B "$OUT/app-build" -G "Unix Makefiles" -Wno-deprecated \
|
||||
-DCMAKE_TOOLCHAIN_FILE="$TOOLCHAIN" -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM="android-$API" "$PAGE_SIZES" \
|
||||
-DCMAKE_BUILD_TYPE="$CONFIG" -DMT_BUILD_TOOLS=OFF -DBUILD_TESTING=OFF \
|
||||
-DMT_BUILD_NATIVE_RENDER=ON -DSDL3_DIR="$OUT/sdl3/lib/cmake/SDL3" \
|
||||
-DMT_MESHPORT_LIBRARY="${MT_MESHPORT_LIBRARY:-$REPO/build/meshport-runtime/aarch64-linux-android/release/libmetin2_meshport.a}" \
|
||||
-DCMAKE_FIND_ROOT_PATH="$OUT/sdl3" -DGLSLC="$GLSLC" >/dev/null
|
||||
cmake --build "$OUT/app-build" --target main mt_native_android_assets -j "$JOBS"
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
# 客户端内置 MeshPort:同网段直连,跨网段统一组网
|
||||
|
||||
SDK 源码在 `third_party/meshport/`;客户端的后台运行时在 `src/meshport/runtime/`,TCP/UDP 平台适配在 `src/meshport/transport.cpp`。不依赖相邻的 MeshPort 工程或另行安装的 MeshPort 应用。
|
||||
|
||||
## 统一路径
|
||||
|
||||
组网按每一个目标 IPv4 地址决定,位于原生网络层,不依赖登录窗口或按钮。首次跨网段请求(包括登录前频道查询、先注册、先发送 UDP、命令行自动登录)都可触发后台启动。
|
||||
|
||||
| 请求 | 接入点 |
|
||||
|---|---|
|
||||
| 登录前频道状态查询 | `CServerStateChecker` → `CNetworkStream`;当前实现是 TCP |
|
||||
| 账号认证、游戏连接 | `CAccountConnector`、`CPythonNetworkStream` → `CNetworkStream` |
|
||||
| 换地图、换线、断线后的新连接 | 每次 `CNetworkStream::Connect` 重新判断目标地址 |
|
||||
| 公会图标/标志上传和下载 | `CGuildMarkUploader`、`CGuildMarkDownloader` → `CNetworkStream` |
|
||||
| 注册账号 HTTP | `PythonAccountRegister.cpp` 的工作线程使用相同 TCP 连接与 SOCKS 协商 |
|
||||
| 通用 UDP | `CNetworkDatagram`、`CNetDatagramSender`、`CNetDatagramReceiver` → 统一 SOCKS5 UDP ASSOCIATE |
|
||||
|
||||
百科、洗练、拾取、战令等服务端命令复用游戏连接,自动跟随该连接的路径。域名沿用系统 IPv4 解析,解析后的地址进入相同判断;纯数字开头的域名不会再被误当成 IP。游戏现有封包、加密、原始数据内容保持不变。
|
||||
|
||||
## 路由与生命周期
|
||||
|
||||
- 使用本机已启用网卡的实际 IPv4 地址、子网掩码判断,不假定 `/24`。排除回环、点对点及 TUN/TAP 网卡;回环目标直接连接,便于本地测试。
|
||||
- 同网段直接使用系统 TCP/UDP,不为了本地请求启动 MeshPort。一个客户端可以同时访问同网段与跨网段目标。
|
||||
- 跨网段只使用 MeshPort;没有配置、引导连接失败、路由缺失或 SOCKS 被拒绝时返回失败,**不退回系统直连**。
|
||||
- 首次需要时才后台启动 SDK。复用保存配置中的网络身份、密钥、引导节点及传输选项,强制应用模式、`dhcp=true`、清空固定 IPv4 和监听端口。
|
||||
- 等待动态 IP 和 SDK 接受的公告子网就绪。引擎启动、发现节点或仅获取 IP 均不算连接成功;TCP 的远端 SOCKS 建连成功或收到有效 UDP 回包后才提示“组网成功”,约 6 秒。
|
||||
- 同一 SDK 由全部请求共享,多个请求不会重复启动,也不会因另一次登录停止现有连接。运行期间刷新健康状态和子网,后续新目标、重连均重新检查路由。
|
||||
- 地址/路由准备最多 60 秒,SOCKS 建连最多 10 秒;原生 TCP 给整个准备流程最多 75 秒。UDP 发送队列有数量、字节和时限上限,防止断网时无限积压。
|
||||
- UDP 保留原始来源 IP/端口、数据报边界及 `MSG_PEEK`,直连和组网回包可由同一接收 API 读取。TCP 控制连接、UDP relay 与原始 socket 一起回收。
|
||||
- 关闭注册窗口会取消路由等待和 HTTP I/O,已发送到服务器的请求无法撤回,不做自动重发。退出时先取消并等待注册线程,再停止 SDK;关闭普通连接会移除其待完成协商。登录窗口的取消/退出也只取消尚在准备的账号及游戏连接,不中断独立频道查询或已建立的连接。
|
||||
- 网卡变化后,新连接和每次发送都重新判断;排队的 UDP 若变为同网段,则改走直连。已经建立的 TCP 会话不能迁移到另一条路径:断线后沿原客户端流程返回登录/建立新连接,新连接重新判断;没有新增自动登录或自动重放业务请求。
|
||||
|
||||
使用应用内桥接,不创建系统 VPN、不安装 OS 路由。MeshPort 自己的引导/打洞连接仍使用系统网络,避免组网递归。
|
||||
|
||||
## SDK 的 DHCP 子网修复
|
||||
|
||||
原 SDK 的公告子网过滤器捕获 `TomlConfig.get_ipv4()`。DHCP 启动时它为空,动态地址分配后也不会更新,造成“有 IP、有节点,但无法接受服务器网段”。本地修复从运行中的节点快照更新过滤器,再投影接受的子网;变更记录在 `third_party/meshport/UPSTREAM.md`。
|
||||
|
||||
## 私有配置
|
||||
|
||||
当前开发机默认读取 `~/Library/Application Support/MeshPort/network-profile.toml`。其他电脑可将同一网络的配置放入忽略规则覆盖的 `config/meshport.private.toml`,或设置 CMake 参数:
|
||||
|
||||
```sh
|
||||
cmake -S . -B build/release -DMT_BUILD_NATIVE_RENDER=ON \
|
||||
-DMT_MESHPORT_CONFIG="/path/to/network-profile.toml"
|
||||
```
|
||||
|
||||
配置在构建时读入生成头文件;开发运行时可用环境变量 `MT_MESHPORT_CONFIG` 覆盖。私有配置不进入 Git;包含配置的 APK/可执行文件应按私有客户端分发。错误提示不输出密钥。
|
||||
|
||||
## 构建
|
||||
|
||||
需要 Rust 1.95+(`cargo` 在 PATH 内)和 protoc(在 PATH 内或通过 `PROTOC` 指定)。依赖固定在 Cargo.lock,首次构建需要下载注册表依赖。编译产物默认放在 `build/meshport-runtime`;运行时及其 SDK 作为一份静态库链接,不依赖动态 MeshPort 库。
|
||||
|
||||
```sh
|
||||
./scripts/build_meshport.sh macos
|
||||
cmake -S . -B build/release -DCMAKE_BUILD_TYPE=Release \
|
||||
-DMT_BUILD_NATIVE_RENDER=ON -DCMAKE_PREFIX_PATH=/opt/homebrew
|
||||
cmake --build build/release --target mt_native_render -j8
|
||||
```
|
||||
|
||||
Android arm64:`./android/build.sh Release --no-deploy` 会先编译运行时和 SDK,再构建客户端和 APK。独立构建可执行 `./scripts/build_meshport.sh android`;最低 API 24,链接对齐 16 KB 页面。
|
||||
|
||||
`MT_MESHPORT_LIBRARY` 可覆盖静态库路径,`MT_MESHPORT_ROOT` 可覆盖 CMake 中 SDK 头文件路径。组网关闭的专项测试可设置 `-DMT_ENABLE_MESHPORT=OFF`。
|
||||
|
||||
## 验证
|
||||
|
||||
本地真实 SDK 网关将公告网段映射到回环 TCP/UDP 测试服务,测试安装零条 OS 路由,无需管理员权限。构建测试网关时使用与运行时相同的 Cargo target 目录:
|
||||
|
||||
```sh
|
||||
CARGO_TARGET_DIR="$PWD/build/meshport-runtime" cargo build \
|
||||
--manifest-path src/meshport/runtime/Cargo.toml \
|
||||
--example gateway_fixture --release --locked
|
||||
cmake -S . -B build/native -DBUILD_TESTING=ON
|
||||
cmake --build build/native --target meshport_transport_test meshport_network_paths_test -j4
|
||||
ctest --test-dir build/native -R '^meshport\.' --output-on-failure
|
||||
python3 tests/meshport/test_network_paths.py \
|
||||
build/native/src/meshport/meshport_network_paths_test --client
|
||||
```
|
||||
|
||||
测试包括:实际子网掩码、同网段零组网启动、UDP 首次请求触发 DHCP、真实公告子网 TCP/UDP 转发、UDP 来源与 peek、并发账号/游戏类型连接、HTTP、缺失路由不直连、取消协商、SOCKS 分片/拒绝、失败提示与成功提示生命周期。`--client` 还启动真实 Python 2.7 原生客户端,调用实际注册接口验证取消后重新注册。
|
||||
|
||||
跨公网到正式服务器的完整游戏登录、Android 真机切换 Wi-Fi/移动网络需要相应网络与设备验收;本地回环网关测试不能代替这些现场验证。
|
||||
|
||||
本次本机验证记录(2026-10-16):
|
||||
|
||||
- macOS 原生客户端和 Android arm64 APK 构建成功。
|
||||
- `meshport.transport`、`meshport.login`、`meshport.network_paths`、`meshport.dhcp`、`port.net` 共 5 组通过:`build/meshport-final-tests.log`。
|
||||
- 真实 Python 2.7 客户端验证了登录前路由、取消待完成登录、实际 HTTP 注册、取消后重新注册:`build/meshport-path-client-tests.log`、`build/meshport-registration-runtime.log`。
|
||||
- 完整 `port.login_flow` 的账号/加密登录及前段网络检查通过,后段 NPC 商店/任务/仓库点击检查仍有 27 项失败。用关闭组网模块的对照程序复验,失败数量和源码行号完全相同;此项不记为整体通过。日志:`build/meshport-regression-tests.log`、`build/meshport-baseline/test.log`。
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build only MeshPort's application-mode SDK; no VPN or internet proxy engine.
|
||||
set -euo pipefail
|
||||
repo="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
mesh="${MT_MESHPORT_ROOT:-$repo/third_party/meshport}"
|
||||
platform="${1:-macos}"
|
||||
export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$repo/build/meshport-runtime}"
|
||||
command -v cargo >/dev/null || { echo "Rust 1.95+ is required (cargo not found)" >&2; exit 1; }
|
||||
cd "$mesh"
|
||||
if [ "$platform" = android ]; then
|
||||
sdk="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}"
|
||||
ndk="${ANDROID_NDK_ROOT:-${ANDROID_NDK_HOME:-}}"
|
||||
if [ -z "$ndk" ]; then ndk="$sdk/ndk/$(ls "$sdk/ndk" | sort -V | tail -1)"; fi
|
||||
tools="$ndk/toolchains/llvm/prebuilt/darwin-x86_64/bin"
|
||||
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$tools/aarch64-linux-android24-clang"
|
||||
export CC_aarch64_linux_android="$CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER"
|
||||
export AR_aarch64_linux_android="$tools/llvm-ar"
|
||||
export CARGO_TARGET_AARCH64_LINUX_ANDROID_RUSTFLAGS='-C link-arg=-Wl,-z,max-page-size=16384'
|
||||
exec cargo build --manifest-path "$repo/src/meshport/runtime/Cargo.toml" --target aarch64-linux-android --release --locked
|
||||
elif [ "$platform" = macos ]; then
|
||||
exec cargo build --manifest-path "$repo/src/meshport/runtime/Cargo.toml" --release --locked
|
||||
fi
|
||||
printf 'usage: %s [macos|android]\n' "$0" >&2
|
||||
exit 2
|
||||
@@ -435,10 +435,12 @@ def build_ava2_items(output: Path, pack_tool: Path):
|
||||
"""AVA2 drop items missing on the server, layered over the biolog item table (see tools/server/ava2-items)."""
|
||||
import importlib.util
|
||||
root = REPO / "tools/server/ava2-items"
|
||||
ava = REPO.parent / "AVA2/TEST"
|
||||
ava = REPO.parent / "AVA2"
|
||||
if not (ava / "1. Client DEV/pack_maker").is_dir():
|
||||
ava = ava / "TEST"
|
||||
reader = REPO.parent / "metin2-server/src/server/db/src/ProtoReader.cpp"
|
||||
if not (ava / "1. Client DEV/pack_maker").is_dir() or not reader.is_file():
|
||||
raise ValueError("AVA2 items need ../AVA2/TEST (pack_maker + server db) and ../metin2-server")
|
||||
raise ValueError("AVA2 items need ../AVA2 (pack_maker + FILES+SRC.tgz or server db) and ../metin2-server")
|
||||
proto_tool = tool("item_proto_patch")
|
||||
if not proto_tool.is_file():
|
||||
raise ValueError("build item_proto_patch before generating the Chinese client")
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
set(mt_mesh_default OFF)
|
||||
if(APPLE OR ANDROID)
|
||||
set(mt_mesh_default ON)
|
||||
endif()
|
||||
option(MT_ENABLE_MESHPORT "Embed MeshPort application networking" ${mt_mesh_default})
|
||||
if(NOT MT_ENABLE_MESHPORT)
|
||||
return()
|
||||
endif()
|
||||
set(MT_MESHPORT_ROOT "${PROJECT_SOURCE_DIR}/third_party/meshport" CACHE PATH "MeshPort source checkout")
|
||||
if(ANDROID)
|
||||
set(mt_mesh_library "${PROJECT_SOURCE_DIR}/build/meshport-runtime/aarch64-linux-android/release/libmetin2_meshport.a")
|
||||
else()
|
||||
set(mt_mesh_library "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/libmetin2_meshport.a")
|
||||
endif()
|
||||
set(MT_MESHPORT_LIBRARY "${mt_mesh_library}" CACHE FILEPATH "MeshPort static library for this target")
|
||||
if(NOT EXISTS "${MT_MESHPORT_LIBRARY}")
|
||||
message(FATAL_ERROR "Build MeshPort first: scripts/build_meshport.sh (or set MT_MESHPORT_LIBRARY)")
|
||||
endif()
|
||||
# A private build input, never copy network credentials into the source tree.
|
||||
set(mt_mesh_config "${PROJECT_SOURCE_DIR}/config/meshport.private.toml")
|
||||
if(EXISTS "$ENV{HOME}/Library/Application Support/MeshPort/network-profile.toml")
|
||||
set(mt_mesh_config "$ENV{HOME}/Library/Application Support/MeshPort/network-profile.toml")
|
||||
endif()
|
||||
set(MT_MESHPORT_CONFIG "${mt_mesh_config}"
|
||||
CACHE FILEPATH "Saved MeshPort network configuration to embed")
|
||||
set(MT_MESHPORT_TOML "")
|
||||
if(EXISTS "${MT_MESHPORT_CONFIG}")
|
||||
file(READ "${MT_MESHPORT_CONFIG}" MT_MESHPORT_TOML)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${MT_MESHPORT_CONFIG}")
|
||||
else()
|
||||
message(WARNING "MeshPort network profile missing: LAN login works, remote login requires MT_MESHPORT_CONFIG")
|
||||
endif()
|
||||
configure_file(config.h.in "${CMAKE_CURRENT_BINARY_DIR}/MeshPortConfig.h" @ONLY)
|
||||
add_library(mt_meshport STATIC transport.cpp)
|
||||
target_include_directories(mt_meshport PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
PRIVATE "${MT_MESHPORT_ROOT}/crates/meshport-ffi/include")
|
||||
target_compile_definitions(mt_meshport PUBLIC MT_HAS_MESHPORT=1)
|
||||
target_link_libraries(mt_meshport PUBLIC "${MT_MESHPORT_LIBRARY}")
|
||||
if(APPLE)
|
||||
target_link_libraries(mt_meshport PUBLIC "-framework Security" "-framework SystemConfiguration"
|
||||
"-framework CoreFoundation" resolv iconv)
|
||||
elseif(ANDROID)
|
||||
target_link_libraries(mt_meshport PUBLIC log android dl m)
|
||||
endif()
|
||||
if(BUILD_TESTING AND NOT ANDROID)
|
||||
add_executable(meshport_transport_test "${PROJECT_SOURCE_DIR}/tests/meshport/transport_test.cpp")
|
||||
target_link_libraries(meshport_transport_test PRIVATE mt_meshport)
|
||||
add_test(NAME meshport.transport COMMAND meshport_transport_test)
|
||||
add_executable(meshport_network_paths_test "${PROJECT_SOURCE_DIR}/tests/meshport/network_paths_test.cpp")
|
||||
target_link_libraries(meshport_network_paths_test PRIVATE mt_meshport)
|
||||
find_package(Python3 COMPONENTS Interpreter)
|
||||
if(Python3_FOUND)
|
||||
add_test(NAME meshport.login COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tests/meshport/test_login.py")
|
||||
if(EXISTS "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/examples/gateway_fixture")
|
||||
add_test(NAME meshport.network_paths COMMAND "${Python3_EXECUTABLE}"
|
||||
"${PROJECT_SOURCE_DIR}/tests/meshport/test_network_paths.py" "$<TARGET_FILE:meshport_network_paths_test>")
|
||||
set_tests_properties(meshport.network_paths PROPERTIES TIMEOUT 120)
|
||||
endif()
|
||||
if(APPLE AND EXISTS "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/libmetin2_meshport.dylib")
|
||||
add_test(NAME meshport.dhcp COMMAND "${Python3_EXECUTABLE}"
|
||||
"${PROJECT_SOURCE_DIR}/tests/meshport/sdk_smoke.py")
|
||||
set_tests_properties(meshport.dhcp PROPERTIES TIMEOUT 55)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
// Generated private build input. Network credentials are intentionally not logged.
|
||||
static const char* const kMeshPortConfig = R"MESHCONFIG(@MT_MESHPORT_TOML@)MESHCONFIG";
|
||||
Generated
+4911
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "metin2-meshport"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "cdylib"]
|
||||
|
||||
[dependencies]
|
||||
meshport-ffi = { path = "../../../third_party/meshport/crates/meshport-ffi" }
|
||||
serde_json = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { path = "../../../third_party/meshport/vendor/easytier/easytier", default-features = false, features = ["aes-gcm", "ffi-dataplane", "proxy-cidr-monitor", "dhcp-ipv4", "tcp-hole-punch", "proxy-packet"] }
|
||||
easytier-core = { path = "../../../third_party/meshport/vendor/easytier/easytier-core", default-features = false, features = ["proxy-smoltcp-stack"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time"] }
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Isolated test gateway. Maps a private advertised subnet to loopback; no OS routes/TUN.
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
|
||||
use tokio::{net::{TcpListener,UdpSocket},io::{AsyncReadExt,AsyncWriteExt}};
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let tcp=TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let tcp_port=tcp.local_addr().unwrap().port();
|
||||
let udp=UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let udp_port=udp.local_addr().unwrap().port();
|
||||
let reserve=std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mesh_port=reserve.local_addr().unwrap().port();drop(reserve);
|
||||
let name=format!("metin2-gateway-test-{}",std::process::id());
|
||||
let config=format!("ipv4='10.253.85.1/24'\nlisteners=['tcp://127.0.0.1:{mesh_port}']\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='{name}'\nnetwork_secret='isolated-test-only'\n[flags]\nno_tun=true\nuse_smoltcp=true\nenable_encryption=true\n");
|
||||
let parsed=TomlConfig::new_from_str(&config).unwrap();
|
||||
eprintln!("fixture proxy networks: {:?}",parsed.get_proxy_cidrs());
|
||||
let server=create_native_instance(parsed).unwrap();
|
||||
server.start().await.unwrap();
|
||||
println!("{{\"mesh_port\":{mesh_port},\"tcp_port\":{tcp_port},\"udp_port\":{udp_port},\"network_name\":\"{name}\"}}");
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut stream,_))=tcp.accept().await {
|
||||
tokio::spawn(async move {
|
||||
let mut data=[0u8;16384];
|
||||
while let Ok(size)=stream.read(&mut data).await {
|
||||
if size==0 {break}
|
||||
if data[..size].starts_with(b"POST /register") {
|
||||
let _=stream.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n").await;break
|
||||
}
|
||||
if stream.write_all(&data[..size]).await.is_err(){break}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut data=[0u8;65536];
|
||||
loop {
|
||||
if let Ok((size,peer))=udp.recv_from(&mut data).await {let _=udp.send_to(&data[..size],peer).await;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Metin2 host policy around the vendored MeshPort SDK. No sockets or OS routes are intercepted.
|
||||
use serde_json::{json, Value};
|
||||
use std::{collections::HashMap, ffi::{c_char, CStr, CString}, net::Ipv4Addr,
|
||||
sync::{Arc, Condvar, Mutex, OnceLock}, thread::{self, JoinHandle}, time::{Duration, Instant}};
|
||||
|
||||
struct Target { since: Instant, touched: Instant }
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
config: String, targets: HashMap<u32, Target>, routes: Vec<String>, port: u16,
|
||||
stop: bool, failed: bool, retry: bool, event: i32, connected: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Runtime { state: Arc<(Mutex<State>, Condvar)>, worker: Option<JoinHandle<()>> }
|
||||
static RUNTIME: OnceLock<Mutex<Runtime>> = OnceLock::new();
|
||||
fn runtime() -> &'static Mutex<Runtime> { RUNTIME.get_or_init(|| Mutex::new(Runtime::default())) }
|
||||
|
||||
fn matches(cidr: &str, address: u32) -> bool {
|
||||
let Some((ip, bits)) = cidr.split_once('/') else { return false };
|
||||
let (Ok(ip), Ok(bits)) = (ip.parse::<Ipv4Addr>(), bits.parse::<u32>()) else { return false };
|
||||
if !(1..=32).contains(&bits) { return false }
|
||||
let mask = u32::MAX << (32 - bits);
|
||||
(u32::from(ip) & mask) == (address & mask)
|
||||
}
|
||||
fn call(context: u64, request: Value) -> Result<Value, ()> {
|
||||
let text = CString::new(request.to_string()).map_err(|_| ())?;
|
||||
let pointer = unsafe { meshport_ffi::meshport_call(context, text.as_ptr()) };
|
||||
if pointer.is_null() { return Err(()) }
|
||||
let decoded = unsafe { serde_json::from_slice::<Value>(CStr::from_ptr(pointer).to_bytes()) };
|
||||
unsafe { meshport_ffi::meshport_string_free(pointer) };
|
||||
let decoded = decoded.map_err(|_| ())?;
|
||||
if decoded["ok"] != true {
|
||||
if std::env::var_os("MT_MESHPORT_TRACE").is_some() { eprintln!("MeshPort SDK operation failed: {}",request["op"]); }
|
||||
return Err(())
|
||||
}
|
||||
Ok(decoded["data"].clone())
|
||||
}
|
||||
fn start(context: u64, config: &str) -> Result<u16, ()> {
|
||||
let info = call(context, json!({"op":"abi_info"}))?;
|
||||
if info["abi"] != 1 || info["revision"].as_u64().unwrap_or(0) < 2 { return Err(()) }
|
||||
let migrated = call(context, json!({"op":"migrate_config","toml":config}))?;
|
||||
let mut profile = call(context, json!({"op":"validate","toml":migrated["toml"],"include_profile":true}))?["profile"].clone();
|
||||
profile["runtime_mode"] = json!("application");
|
||||
profile["dhcp"] = json!(true); profile["ipv4"] = json!("");
|
||||
profile["hostname"] = json!("Metin2"); profile["listeners"] = json!([]);
|
||||
let built = call(context, json!({"op":"build_config","profile":profile}))?;
|
||||
let started = call(context, json!({"op":"start_bridged","toml":built["toml"],"check_local_overlap":true}))?;
|
||||
let listen = started["listen"].as_str().ok_or(())?;
|
||||
let port = listen.strip_prefix("127.0.0.1:").ok_or(())?.parse::<u16>().map_err(|_| ())?;
|
||||
if port == 0 { return Err(()) }
|
||||
Ok(port)
|
||||
}
|
||||
fn run(shared: Arc<(Mutex<State>, Condvar)>) {
|
||||
let (lock, wake) = &*shared;
|
||||
let mut context = 0;
|
||||
let mut last_projection = String::new();
|
||||
loop {
|
||||
let mut state = lock.lock().unwrap();
|
||||
if state.stop { break }
|
||||
if state.failed && !state.retry || context == 0 && state.targets.is_empty() {
|
||||
drop(wake.wait_timeout(state, Duration::from_secs(1)).unwrap());
|
||||
continue
|
||||
}
|
||||
if state.retry {
|
||||
state.retry = false; state.failed = false; state.routes.clear(); state.port = 0;
|
||||
state.connected = false; state.event = 1;
|
||||
drop(state);
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); context = 0; }
|
||||
continue
|
||||
}
|
||||
if context == 0 {
|
||||
state.event = 1; state.connected = false;
|
||||
let config = state.config.clone(); drop(state);
|
||||
context = meshport_ffi::meshport_context_new();
|
||||
let prepared = if context == 0 { Err(()) } else { start(context, &config) };
|
||||
state = lock.lock().unwrap();
|
||||
match prepared {
|
||||
Ok(port) => state.port = port,
|
||||
Err(_) => {
|
||||
state.failed = true; state.event = 3; state.port = 0;
|
||||
drop(state);
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); context = 0; }
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
let snapshot = call(context, json!({"op":"status"}));
|
||||
state = lock.lock().unwrap();
|
||||
match snapshot {
|
||||
Ok(data) if data["health"]["engine_running"] == true && data["health"]["bridge_running"] == true => {
|
||||
let ready = data["health"]["mesh_routable"] == true && data["platform_network"]["overlay"]["address"].as_str().is_some_and(|ip| ip != "0.0.0.0");
|
||||
if std::env::var_os("MT_MESHPORT_TRACE").is_some() {
|
||||
let projection = format!("ready={ready} overlay={} routes={}",data["platform_network"]["overlay"]["address"],data["platform_network"]["mesh_cidrs"]);
|
||||
if projection != last_projection { eprintln!("MeshPort {projection}"); last_projection = projection; }
|
||||
}
|
||||
state.routes = if ready { data["platform_network"]["mesh_cidrs"].as_array()
|
||||
.map(|items| items.iter().filter_map(|v|v.as_str().map(String::from)).collect()).unwrap_or_default() } else { vec![] };
|
||||
}
|
||||
_ => { state.routes.clear(); state.port = 0; state.failed = true; state.event = 3; }
|
||||
}
|
||||
state.targets.retain(|_,target| target.touched.elapsed() < Duration::from_secs(120));
|
||||
let interval = if state.connected { 1000 } else { 250 };
|
||||
drop(wake.wait_timeout(state, Duration::from_millis(interval)).unwrap());
|
||||
}
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); }
|
||||
}
|
||||
|
||||
/// Store a private profile; no network starts until a remote socket asks for a route.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn mt_mesh_configure(config: *const c_char) {
|
||||
if config.is_null() { return }
|
||||
let Ok(config) = unsafe { CStr::from_ptr(config) }.to_str() else { return };
|
||||
let rt = runtime().lock().unwrap();
|
||||
rt.state.0.lock().unwrap().config = config.to_owned();
|
||||
}
|
||||
/// Host-order IPv4. Positive = healthy bridge port, zero = waiting, -1 = unavailable.
|
||||
/// fresh=true only on a new operation; polling must not restart its timeout or retry.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_route(address: u32, fresh: bool) -> i32 {
|
||||
let mut rt = runtime().lock().unwrap();
|
||||
let mut state = rt.state.0.lock().unwrap();
|
||||
if state.stop { return -1 }
|
||||
let now = Instant::now();
|
||||
if fresh && state.failed { state.retry = true; }
|
||||
let target = state.targets.entry(address).or_insert(Target { since: now, touched: now });
|
||||
if fresh { target.since = now; }
|
||||
target.touched = now;
|
||||
let expired = target.since.elapsed() > Duration::from_secs(60);
|
||||
let answer = if state.failed && !state.retry || expired { -1 }
|
||||
else if !state.retry && state.port != 0 && state.routes.iter().any(|cidr|matches(cidr,address)) { state.port as i32 }
|
||||
else { 0 };
|
||||
if expired && !state.connected { state.event = 3; }
|
||||
drop(state);
|
||||
if rt.worker.is_none() {
|
||||
let shared = rt.state.clone(); rt.worker = Some(thread::spawn(move ||run(shared)));
|
||||
}
|
||||
if fresh { rt.state.1.notify_one(); }
|
||||
answer
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_connected() {
|
||||
let rt = runtime().lock().unwrap(); let mut state = rt.state.0.lock().unwrap();
|
||||
if !state.connected { state.connected = true; state.event = 2; }
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_event() -> i32 {
|
||||
let rt = runtime().lock().unwrap(); let mut state = rt.state.0.lock().unwrap();
|
||||
let event = state.event; state.event = 0; event
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_shutdown() {
|
||||
let worker = {
|
||||
let mut rt = runtime().lock().unwrap();
|
||||
rt.state.0.lock().unwrap().stop = true; rt.state.1.notify_all(); rt.worker.take()
|
||||
};
|
||||
if let Some(worker) = worker { let _ = worker.join(); }
|
||||
let mut rt = runtime().lock().unwrap(); rt.state = Arc::new((Mutex::new(State::default()), Condvar::new()));
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
#include "transport.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <net/if.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <stdexcept>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <set>
|
||||
#include <array>
|
||||
#include <fcntl.h>
|
||||
#include <algorithm>
|
||||
|
||||
extern "C" {
|
||||
void mt_mesh_configure(const char*);
|
||||
int mt_mesh_route(uint32_t, bool);
|
||||
void mt_mesh_connected();
|
||||
int mt_mesh_event();
|
||||
void mt_mesh_shutdown();
|
||||
}
|
||||
|
||||
namespace mt::meshport {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Handshake {
|
||||
sockaddr_in target{};
|
||||
const void* owner = nullptr;
|
||||
int stage = -1;
|
||||
size_t offset = 0;
|
||||
unsigned char bytes[10] = {5, 1, 0};
|
||||
unsigned char command = 1;
|
||||
Clock::time_point deadline = Clock::now() + std::chrono::seconds(75);
|
||||
};
|
||||
struct Packet { sockaddr_in target{}; std::vector<unsigned char> bytes; Clock::time_point deadline; };
|
||||
struct Udp {
|
||||
int control = -1, relay = -1;
|
||||
uint16_t port = 0;
|
||||
Handshake handshake;
|
||||
bool ready = false;
|
||||
std::deque<Packet> outgoing, incoming;
|
||||
std::set<std::pair<uint32_t,uint16_t>> peers;
|
||||
size_t queued_bytes = 0;
|
||||
};
|
||||
std::mutex transport_mutex;
|
||||
std::map<int, Handshake> handshakes;
|
||||
std::map<int, Udp> datagrams;
|
||||
std::vector<std::string> routes;
|
||||
sockaddr_in proxy{};
|
||||
bool fixture = false;
|
||||
std::atomic<int> transport_event{0};
|
||||
bool ipv4(const std::string& text, uint32_t& result) {
|
||||
in_addr ip{};
|
||||
if (inet_pton(AF_INET, text.c_str(), &ip) != 1) return false;
|
||||
result = ip.s_addr;
|
||||
return true;
|
||||
}
|
||||
std::string address(uint32_t ip) {
|
||||
char buf[INET_ADDRSTRLEN];
|
||||
in_addr value{}; value.s_addr = ip;
|
||||
return inet_ntop(AF_INET, &value, buf, sizeof(buf)) ? buf : "";
|
||||
}
|
||||
}
|
||||
bool in_subnet(uint32_t ip, uint32_t local, uint32_t mask) {
|
||||
return mask != 0 && (ip & mask) == (local & mask);
|
||||
}
|
||||
bool contains(const std::string& cidr, const std::string& ip) {
|
||||
const auto slash = cidr.find('/');
|
||||
if (slash == std::string::npos) return false;
|
||||
uint32_t network, target;
|
||||
if (!ipv4(cidr.substr(0, slash), network) || !ipv4(ip, target)) return false;
|
||||
const auto suffix = cidr.substr(slash + 1);
|
||||
if (suffix.empty() || suffix.find_first_not_of("0123456789") != std::string::npos) return false;
|
||||
if (suffix.size() > 2) return false;
|
||||
const int prefix = std::stoi(suffix);
|
||||
if (prefix < 1 || prefix > 32) return false;
|
||||
return in_subnet(target, network, htonl(0xffffffffu << (32 - prefix)));
|
||||
}
|
||||
bool same_subnet(const std::string& ip) {
|
||||
uint32_t target;
|
||||
if (!ipv4(ip, target)) return false;
|
||||
if ((ntohl(target) >> 24) == 127) return true;
|
||||
ifaddrs* interfaces = nullptr;
|
||||
if (getifaddrs(&interfaces) != 0) return false;
|
||||
bool local = false;
|
||||
for (auto* i = interfaces; i; i = i->ifa_next) {
|
||||
if (!i->ifa_addr || !i->ifa_netmask || i->ifa_addr->sa_family != AF_INET) continue;
|
||||
if (!(i->ifa_flags & IFF_UP) || (i->ifa_flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) continue;
|
||||
const std::string name = i->ifa_name;
|
||||
if (name.find("tun") == 0 || name.find("utun") == 0 || name.find("tap") == 0) continue;
|
||||
const auto* a = reinterpret_cast<sockaddr_in*>(i->ifa_addr);
|
||||
const auto* m = reinterpret_cast<sockaddr_in*>(i->ifa_netmask);
|
||||
if (in_subnet(target, a->sin_addr.s_addr, m->sin_addr.s_addr)) { local = true; break; }
|
||||
}
|
||||
freeifaddrs(interfaces);
|
||||
return local;
|
||||
}
|
||||
void set_routes(const std::string& listen, const std::vector<std::string>& cidrs) {
|
||||
sockaddr_in next{};
|
||||
if (!listen.empty()) {
|
||||
const auto colon = listen.find(':');
|
||||
if (colon == std::string::npos || listen.substr(0, colon) != "127.0.0.1")
|
||||
throw std::runtime_error("MeshPort bridge must listen on loopback");
|
||||
const auto port_text = listen.substr(colon + 1);
|
||||
if (port_text.empty() || port_text.size() > 5 || port_text.find_first_not_of("0123456789") != std::string::npos)
|
||||
throw std::runtime_error("Invalid MeshPort bridge port");
|
||||
int port = std::stoi(port_text);
|
||||
if (port < 1 || port > 65535) throw std::runtime_error("Invalid MeshPort bridge port");
|
||||
next.sin_family = AF_INET;
|
||||
next.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
next.sin_port = htons(port);
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
proxy = next;
|
||||
routes = cidrs;
|
||||
fixture = !listen.empty();
|
||||
}
|
||||
void configure(const std::string& config) { mt_mesh_configure(config.c_str()); }
|
||||
namespace {
|
||||
int route(const sockaddr_in& target, bool fresh) {
|
||||
if (fixture) {
|
||||
for (const auto& cidr : routes)
|
||||
if (contains(cidr, address(target.sin_addr.s_addr))) return ntohs(proxy.sin_port);
|
||||
return -1; // Missing routes never fall back to the OS network.
|
||||
}
|
||||
return mt_mesh_route(ntohl(target.sin_addr.s_addr), fresh);
|
||||
}
|
||||
sockaddr_in loopback(int port) {
|
||||
sockaddr_in value{}; value.sin_family = AF_INET;
|
||||
value.sin_addr.s_addr = htonl(INADDR_LOOPBACK); value.sin_port = htons(port); return value;
|
||||
}
|
||||
int fail(int error) { errno = error; transport_event = 3; return -1; }
|
||||
int advance(int fd, Handshake& h, sockaddr_in* bound = nullptr) {
|
||||
if (Clock::now() > h.deadline) return fail(ETIMEDOUT);
|
||||
if (h.stage == -1) {
|
||||
int port = route(h.target, false);
|
||||
if (port < 0) return fail(EHOSTUNREACH);
|
||||
if (!port) return 0;
|
||||
auto endpoint = loopback(port);
|
||||
int status = ::connect(fd, reinterpret_cast<const sockaddr*>(&endpoint), sizeof(endpoint));
|
||||
if (status < 0 && errno != EINPROGRESS && errno != EWOULDBLOCK) return fail(errno);
|
||||
h.stage = 0;
|
||||
h.deadline = Clock::now() + std::chrono::seconds(10);
|
||||
}
|
||||
if (h.stage == 0) {
|
||||
int error = 0; socklen_t len = sizeof(error);
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) return fail(errno);
|
||||
if (error) return fail(error);
|
||||
sockaddr_in peer{}; len = sizeof(peer);
|
||||
if (getpeername(fd, reinterpret_cast<sockaddr*>(&peer), &len) < 0) return 0;
|
||||
h.stage = 1;
|
||||
}
|
||||
const bool sending = h.stage == 1 || h.stage == 3;
|
||||
const size_t length = h.stage == 1 ? 3 : h.stage == 2 ? 2 : 10;
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int send_flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
constexpr int send_flags = 0;
|
||||
#endif
|
||||
const auto count = sending ? ::send(fd, h.bytes + h.offset, length - h.offset, send_flags)
|
||||
: ::recv(fd, h.bytes + h.offset, length - h.offset, 0);
|
||||
if (count < 0) return (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ? 0 : fail(errno);
|
||||
if (!count) return fail(ECONNRESET);
|
||||
h.offset += static_cast<size_t>(count);
|
||||
if (h.offset != length) return 0;
|
||||
h.offset = 0;
|
||||
if (h.stage == 2) {
|
||||
if (h.bytes[0] != 5 || h.bytes[1] != 0) return fail(EPROTO);
|
||||
h.bytes[0] = 5; h.bytes[1] = h.command; h.bytes[2] = 0; h.bytes[3] = 1;
|
||||
if (h.command == 1) {
|
||||
std::memcpy(h.bytes + 4, &h.target.sin_addr.s_addr, 4);
|
||||
std::memcpy(h.bytes + 8, &h.target.sin_port, 2);
|
||||
} else { std::memset(h.bytes + 4, 0, 6); }
|
||||
} else if (h.stage == 4) {
|
||||
if (h.bytes[0] != 5 || h.bytes[1] != 0 || h.bytes[2] != 0 || h.bytes[3] != 1) return fail(EPROTO);
|
||||
if (bound) {
|
||||
bound->sin_family = AF_INET;
|
||||
std::memcpy(&bound->sin_addr.s_addr, h.bytes + 4, 4);
|
||||
std::memcpy(&bound->sin_port, h.bytes + 8, 2);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
++h.stage; return 0;
|
||||
}
|
||||
void close_udp(Udp& udp) {
|
||||
if (udp.control >= 0) ::close(udp.control);
|
||||
if (udp.relay >= 0) ::close(udp.relay);
|
||||
udp.control = udp.relay = -1; udp.ready = false; udp.port = 0;
|
||||
}
|
||||
void pump_udp(int fd, Udp& udp) {
|
||||
const auto now = Clock::now();
|
||||
while (!udp.outgoing.empty() && udp.outgoing.front().deadline < now) {
|
||||
udp.queued_bytes -= udp.outgoing.front().bytes.size(); udp.outgoing.pop_front(); transport_event = 3;
|
||||
}
|
||||
// A queued request can become local while DHCP/peer discovery is pending.
|
||||
while (!udp.outgoing.empty() && same_subnet(address(udp.outgoing.front().target.sin_addr.s_addr))) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
auto count = ::sendto(fd,packet.bytes.data(),packet.bytes.size(),MSG_DONTWAIT,
|
||||
reinterpret_cast<sockaddr*>(&packet.target),sizeof(packet.target));
|
||||
if (count < 0 && (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)) break;
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front();
|
||||
}
|
||||
if (udp.control >= 0 && udp.ready) {
|
||||
char probe;
|
||||
auto result = ::recv(udp.control, &probe, 1, MSG_PEEK | MSG_DONTWAIT);
|
||||
if (result == 0 || (result < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) close_udp(udp);
|
||||
}
|
||||
if (udp.control < 0 && !udp.outgoing.empty()) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
const int port = route(packet.target, false);
|
||||
if (port < 0) {
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front(); transport_event = 3; return;
|
||||
}
|
||||
if (!port) return;
|
||||
udp.control = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (udp.control < 0) return;
|
||||
fcntl(udp.control, F_SETFL, O_NONBLOCK);
|
||||
#ifdef SO_NOSIGPIPE
|
||||
int one=1;setsockopt(udp.control,SOL_SOCKET,SO_NOSIGPIPE,&one,sizeof(one));
|
||||
#endif
|
||||
udp.port = port; udp.handshake = Handshake{};
|
||||
udp.handshake.target = packet.target; udp.handshake.command = 3;
|
||||
}
|
||||
if (udp.control < 0) return;
|
||||
if (!udp.ready) {
|
||||
sockaddr_in relay{};
|
||||
int result = advance(udp.control, udp.handshake, &relay);
|
||||
if (result < 0) { close_udp(udp); return; }
|
||||
if (!result) return;
|
||||
// The SDK bridge is IPv4 loopback-only. Do not accept a redirect to an external relay.
|
||||
if (relay.sin_addr.s_addr != htonl(INADDR_LOOPBACK) || !relay.sin_port) { close_udp(udp); transport_event=3;return; }
|
||||
udp.relay = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (udp.relay < 0) { close_udp(udp);return; }
|
||||
fcntl(udp.relay,F_SETFL,O_NONBLOCK);
|
||||
if (::connect(udp.relay,reinterpret_cast<sockaddr*>(&relay),sizeof(relay)) < 0) {close_udp(udp);return;}
|
||||
udp.ready = true;
|
||||
}
|
||||
for (size_t sent=0; !udp.outgoing.empty() && sent<32; ++sent) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
const int port = route(packet.target,false);
|
||||
if (port == 0) break;
|
||||
if (port < 0) {
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front(); transport_event=3;continue;
|
||||
}
|
||||
if (port != udp.port) {close_udp(udp);return;}
|
||||
std::vector<unsigned char> envelope(10+packet.bytes.size());
|
||||
envelope[3]=1;
|
||||
std::memcpy(envelope.data()+4,&packet.target.sin_addr.s_addr,4);
|
||||
std::memcpy(envelope.data()+8,&packet.target.sin_port,2);
|
||||
std::copy(packet.bytes.begin(),packet.bytes.end(),envelope.begin()+10);
|
||||
auto count = ::send(udp.relay,envelope.data(),envelope.size(),0);
|
||||
if (count < 0 && (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)) break;
|
||||
if (count < 0) {close_udp(udp);return;}
|
||||
if(udp.peers.size()<128)udp.peers.emplace(packet.target.sin_addr.s_addr,packet.target.sin_port);
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front();
|
||||
}
|
||||
for (int i=0;i<32;++i) {
|
||||
std::array<unsigned char,65536> envelope;
|
||||
auto count = ::recv(udp.relay,envelope.data(),envelope.size(),0);
|
||||
if (count < 0) break;
|
||||
if (count<10 || envelope[0] || envelope[1] || envelope[2] || envelope[3]!=1) continue;
|
||||
sockaddr_in source{};source.sin_family=AF_INET;
|
||||
std::memcpy(&source.sin_addr.s_addr,envelope.data()+4,4);
|
||||
std::memcpy(&source.sin_port,envelope.data()+8,2);
|
||||
if (!udp.peers.count({source.sin_addr.s_addr,source.sin_port})) continue;
|
||||
if (udp.incoming.size()>=64) continue;
|
||||
udp.incoming.push_back({source,{envelope.begin()+10,envelope.begin()+count},now});
|
||||
if (!fixture) mt_mesh_connected(); else transport_event=2;
|
||||
}
|
||||
}
|
||||
}
|
||||
int connect_socket(int fd, const sockaddr_in& target, const void* owner) {
|
||||
if (same_subnet(address(target.sin_addr.s_addr)))
|
||||
return ::connect(fd,reinterpret_cast<const sockaddr*>(&target),sizeof(target));
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
if (route(target,true)<0) return fail(EHOSTUNREACH);
|
||||
Handshake h; h.target=target; h.owner=owner; handshakes[fd]=h;
|
||||
errno=EINPROGRESS;return -1;
|
||||
}
|
||||
bool pending_owner(const void* owner) {
|
||||
if(!owner)return false;
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for(const auto& [fd,h]:handshakes)if(h.owner==owner)return true;
|
||||
return false;
|
||||
}
|
||||
bool pending(int fd) { std::lock_guard<std::mutex> guard(transport_mutex);return handshakes.count(fd)!=0; }
|
||||
int poll_socket(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=handshakes.find(fd);if(it==handshakes.end()) return 1;
|
||||
int result=advance(fd,it->second);
|
||||
if (result==1) {
|
||||
handshakes.erase(it);
|
||||
if(!fixture) mt_mesh_connected();else transport_event=2;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void forget_socket(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);handshakes.erase(fd);
|
||||
auto it=datagrams.find(fd);if(it!=datagrams.end()){close_udp(it->second);datagrams.erase(it);}
|
||||
}
|
||||
ssize_t send_datagram(int fd,const void* bytes,size_t size,int flags,const sockaddr_in& target) {
|
||||
if (same_subnet(address(target.sin_addr.s_addr)))
|
||||
return ::sendto(fd,bytes,size,flags,reinterpret_cast<const sockaddr*>(&target),sizeof(target));
|
||||
if (size>65497) {errno=EMSGSIZE;return -1;}
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
if (route(target,true)<0) return fail(EHOSTUNREACH);
|
||||
if(fcntl(fd,F_GETFD)<0)return -1;
|
||||
auto& udp=datagrams[fd];
|
||||
if (udp.outgoing.size()>=64 || udp.queued_bytes+size>1024*1024) {errno=EWOULDBLOCK;return -1;}
|
||||
const auto* begin=static_cast<const unsigned char*>(bytes);
|
||||
udp.outgoing.push_back({target,{begin,begin+size},Clock::now()+std::chrono::seconds(60)});
|
||||
udp.queued_bytes+=size;pump_udp(fd,udp);return static_cast<ssize_t>(size);
|
||||
}
|
||||
bool datagram_ready(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=datagrams.find(fd);if(it==datagrams.end())return false;
|
||||
pump_udp(fd,it->second);return !it->second.incoming.empty();
|
||||
}
|
||||
ssize_t recv_datagram(int fd,void* bytes,size_t size,int flags,sockaddr_in* source) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=datagrams.find(fd);
|
||||
if(it!=datagrams.end()) {
|
||||
auto& udp=it->second;pump_udp(fd,udp);
|
||||
if(!udp.incoming.empty()) {
|
||||
auto& packet=udp.incoming.front();
|
||||
const size_t count=std::min(size,packet.bytes.size());
|
||||
std::memcpy(bytes,packet.bytes.data(),count);if(source)*source=packet.target;
|
||||
const auto result=(flags&MSG_TRUNC)?packet.bytes.size():count;
|
||||
if(!(flags&MSG_PEEK))udp.incoming.pop_front();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
socklen_t length=sizeof(sockaddr_in);
|
||||
return ::recvfrom(fd,bytes,size,flags,reinterpret_cast<sockaddr*>(source),source?&length:nullptr);
|
||||
}
|
||||
void pump() {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for(auto& [fd,udp]:datagrams)pump_udp(fd,udp);
|
||||
}
|
||||
int take_event() { pump();int event=transport_event.exchange(0);int runtime=mt_mesh_event();return event?event:runtime; }
|
||||
|
||||
void shutdown() {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for (auto& [fd, udp] : datagrams) {
|
||||
if (udp.control >= 0) ::close(udp.control);
|
||||
if (udp.relay >= 0) ::close(udp.relay);
|
||||
}
|
||||
datagrams.clear(); handshakes.clear(); routes.clear(); proxy = {}; fixture = false;
|
||||
}
|
||||
mt_mesh_shutdown(); transport_event = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
namespace mt::meshport {
|
||||
bool in_subnet(uint32_t address, uint32_t local, uint32_t mask);
|
||||
bool same_subnet(const std::string& address);
|
||||
bool contains(const std::string& cidr, const std::string& address);
|
||||
void configure(const std::string& private_profile);
|
||||
// Explicit fixture bridge. Production obtains its routes exclusively from the native runtime.
|
||||
void set_routes(const std::string& listen, const std::vector<std::string>& cidrs);
|
||||
int connect_socket(int fd, const sockaddr_in& target, const void* owner = nullptr);
|
||||
bool pending_owner(const void* owner);
|
||||
int poll_socket(int fd); // 0 waiting; 1 ready; -1 failed. Includes preparation and SOCKS handshake.
|
||||
bool pending(int fd);
|
||||
void forget_socket(int fd);
|
||||
ssize_t send_datagram(int fd, const void* bytes, size_t size, int flags, const sockaddr_in& target);
|
||||
ssize_t recv_datagram(int fd, void* bytes, size_t size, int flags, sockaddr_in* source);
|
||||
bool datagram_ready(int fd);
|
||||
void pump();
|
||||
int take_event(); // 1 preparing; 2 remote transport verified; 3 failed.
|
||||
void shutdown();
|
||||
}
|
||||
@@ -21,3 +21,7 @@ if(TARGET mtpython)
|
||||
set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/ScriptLib/PythonBoot.cpp
|
||||
PROPERTY COMPILE_DEFINITIONS ${MT_PORT_DEFINES_UserInterface})
|
||||
endif()
|
||||
|
||||
if(TARGET mt_meshport)
|
||||
target_include_directories(port_platform PRIVATE "${PROJECT_BINARY_DIR}/src/meshport")
|
||||
endif()
|
||||
|
||||
@@ -11,6 +11,7 @@ import grp
|
||||
import item
|
||||
import net
|
||||
import nonplayer
|
||||
import player
|
||||
import ui
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
@@ -29,7 +30,8 @@ TYPES={1:('击杀怪物','击杀 ','mob'),2:('击杀 Boss','击杀 Boss ','mob')
|
||||
9:(None,'向 NPC 出售 ','item')}
|
||||
ERRORS={'loading':'数据加载中,请稍后再试','slot':'没有这个任务','claimed':'奖励已经领取过了','incomplete':'任务尚未完成',
|
||||
'space':'背包空间不足,请整理后再领取','config':'奖励配置有误,请联系管理员','db':'服务器繁忙,请稍后再试',
|
||||
'rate':'操作过快,请稍后再试','invalid':'参数无效'}
|
||||
'rate':'操作过快,请稍后再试','invalid':'参数无效','ticket':'请使用当月战令票激活','month':'这张战令票不属于当前月份',
|
||||
'activated':'本月战令已经激活过了','busy':'请先结束交易、商店、仓库或传送'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=10**12):
|
||||
@@ -86,7 +88,7 @@ class Pass(object):
|
||||
self.Clear()
|
||||
|
||||
def Clear(self):
|
||||
self.season=None;self.missions={};self.final=None;self.reading=None;self.none=False;self.error=None;self.claiming=None
|
||||
self.season=None;self.missions={};self.final=None;self.reading=None;self.none=False;self.error=None;self.claiming=None;self.access=None;self.month=None
|
||||
|
||||
def Ready(self):
|
||||
return self.waiting is None or self.now()>=self.waiting
|
||||
@@ -104,10 +106,15 @@ class Pass(object):
|
||||
return self.Post('/mt_bp 1 info')
|
||||
|
||||
def Claim(self,slot):
|
||||
if self.claiming is not None or not self.season:return False
|
||||
if self.claiming is not None or not self.season or self.access not in (None,1):return False
|
||||
if self.Post('/mt_bp 1 claim %d'%slot):self.claiming=slot;self.error=None;return True
|
||||
return False
|
||||
|
||||
def Activate(self,cell,vnum):
|
||||
if self.access!=0 or self.waiting is not None or not 25150<=vnum<=25161:return False
|
||||
if player.GetItemIndex(cell)!=vnum:return False
|
||||
return self.Post('/mt_bp 1 activate %d %d'%(cell,vnum))
|
||||
|
||||
def Close(self):
|
||||
self.send('/mt_bp 1 close')
|
||||
|
||||
@@ -135,7 +142,10 @@ class Pass(object):
|
||||
def Parse(self,kind,args):
|
||||
if kind=='season' and len(args)==5:
|
||||
seasonId,start,end,now=[Number(w,0,2**32-1) for w in args[:4]];count=Number(args[4],1,MAX_SLOT)
|
||||
self.reading=dict(season=(seasonId,start,end,now,self.now()),count=count,missions={},final=None)
|
||||
self.reading=dict(season=(seasonId,start,end,now,self.now()),count=count,missions={},final=None,access=None,month=None)
|
||||
elif kind=='access' and len(args) in (1,2) and self.reading is not None:
|
||||
self.reading['access']=Number(args[0],0,2)
|
||||
if len(args)==2:self.reading['month']=Number(args[1],1,12)
|
||||
elif kind=='mission' and self.reading is not None and len(args)>=6:
|
||||
slot=Number(args[0],1,MAX_SLOT);kind=Number(args[1],1,9)
|
||||
self.reading['missions'][slot]=dict(slot=slot,type=kind,sub=Number(args[2],0,2**32-1),target=Number(args[3],1),
|
||||
@@ -145,7 +155,7 @@ class Pass(object):
|
||||
elif kind=='end' and not args and self.reading is not None:
|
||||
r=self.reading;self.reading=None
|
||||
if len(r['missions'])!=r['count'] or r['final'] is None:return
|
||||
self.season=r['season'];self.missions=r['missions'];self.final=r['final'];self.none=False
|
||||
self.season=r['season'];self.missions=r['missions'];self.final=r['final'];self.access=r['access'];self.month=r['month'];self.none=False
|
||||
self.Answered('info')
|
||||
elif kind=='none' and not args:
|
||||
self.Clear();self.none=True;self.Answered('none')
|
||||
@@ -214,6 +224,8 @@ class BattlePassWindow(ui.Window):
|
||||
self.finalState=Text(self,330,y+4,'')
|
||||
self.finalReward=Text(self,18,y+26,'',0xffb3aa98)
|
||||
self.finalButton=Action(self,WIDTH-118,y,100,'领取',lambda:self.state.Claim(0) and self.Refresh())
|
||||
self.activateButton=Action(self,WIDTH-218,y,200,'使用当月战令票激活',self.AskActivate)
|
||||
self.activateButton.Hide();self.confirm=None;self.pendingTicket=None
|
||||
y=self.GetHeight()-56
|
||||
self.prev=Action(self,18,y,80,'上一页',lambda:self.Turn(-1))
|
||||
self.pageText=Text(self,140,y+24,'');self.pageText.SetHorizontalAlignCenter()
|
||||
@@ -232,8 +244,43 @@ class BattlePassWindow(ui.Window):
|
||||
def Hide(self):
|
||||
state=self.__dict__.get('state') # ui.Window.__init__ hides the window before state is set
|
||||
if self.IsShow() and state and state.season:state.Close()
|
||||
self.pendingTicket=None
|
||||
self.CloseConfirm()
|
||||
ui.Window.Hide(self)
|
||||
|
||||
def CloseConfirm(self):
|
||||
confirm=self.__dict__.get('confirm')
|
||||
if confirm:
|
||||
confirm.Close();confirm.SetAcceptEvent(None);confirm.SetCancelEvent(None);self.confirm=None
|
||||
|
||||
def OfferTicket(self,cell,vnum):
|
||||
self.pendingTicket=(cell,vnum)
|
||||
self.Open()
|
||||
|
||||
def AskTicket(self,cell,vnum):
|
||||
if self.state.access!=0 or player.GetItemIndex(cell)!=vnum:return
|
||||
item.SelectItem(vnum)
|
||||
if item.GetValue(0)!=self.state.month:self.state.error='month';self.Refresh();return
|
||||
import uiCommon
|
||||
self.CloseConfirm();self.confirm=uiCommon.QuestionDialog()
|
||||
self.confirm.SetText(L('消耗战令票并激活本月战令?'))
|
||||
self.confirm.SetAcceptEvent(lambda:self.ConfirmActivate(cell,vnum))
|
||||
self.confirm.SetCancelEvent(self.CloseConfirm);self.confirm.Open()
|
||||
|
||||
def AskActivate(self):
|
||||
if self.state.access!=0:return
|
||||
for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if not 25150<=vnum<=25161:continue
|
||||
item.SelectItem(vnum)
|
||||
# Display uses server time, not the phone's local month/time zone.
|
||||
if item.GetValue(0)!=self.state.month:continue
|
||||
self.AskTicket(cell,vnum);return
|
||||
self.state.error='ticket';self.Refresh()
|
||||
|
||||
def ConfirmActivate(self,cell,vnum):
|
||||
self.CloseConfirm();self.state.Activate(cell,vnum);self.Refresh()
|
||||
|
||||
def Slots(self):
|
||||
return sorted(self.state.missions)
|
||||
|
||||
@@ -264,7 +311,7 @@ class BattlePassWindow(ui.Window):
|
||||
if m['claimed']:row['button'].SetText('已领取')
|
||||
elif s.claiming==m['slot']:row['button'].SetText('领取中')
|
||||
else:row['button'].SetText('领取' if done else '未完成')
|
||||
row['button'].SetEnabled(done and not m['claimed'] and bool(m['rewards']) and s.claiming is None)
|
||||
row['button'].SetEnabled(s.access in (None,1) and done and not m['claimed'] and bool(m['rewards']) and s.claiming is None)
|
||||
f=s.final
|
||||
for w in (self.finalName,self.finalState,self.finalReward,self.finalButton):
|
||||
if f:w.Show()
|
||||
@@ -274,7 +321,11 @@ class BattlePassWindow(ui.Window):
|
||||
self.finalState.SetText(L('已领取' if f['claimed'] else '全部任务完成' if ready else '完成全部任务后可领取'))
|
||||
self.finalReward.SetText(L('奖励:')+RewardText(f['rewards']))
|
||||
self.finalButton.SetText('已领取' if f['claimed'] else '领取中' if s.claiming==0 else '领取')
|
||||
self.finalButton.SetEnabled(ready and not f['claimed'] and s.claiming is None)
|
||||
self.finalButton.SetEnabled(s.access in (None,1) and ready and not f['claimed'] and s.claiming is None)
|
||||
if s.access==0:
|
||||
self.finalButton.Hide();self.finalState.Hide();self.finalReward.Hide();self.activateButton.Show()
|
||||
self.activateButton.SetEnabled(s.waiting is None)
|
||||
else:self.activateButton.Hide()
|
||||
many=self.Pages()>1
|
||||
for w in (self.prev,self.next,self.pageText):
|
||||
if many and s.season:w.Show()
|
||||
@@ -288,6 +339,8 @@ class BattlePassWindow(ui.Window):
|
||||
elif s.none:note='当前没有进行中的战令赛季'
|
||||
elif not s.season:note='正在查询……'
|
||||
elif s.claiming is not None:note='正在领取……'
|
||||
elif s.access==0:note='激活后才开始累计进度'
|
||||
elif s.access==2:note='本月战令已完成'
|
||||
else:note='击杀、钓鱼、强化等都会自动计入进度'
|
||||
self.note.SetText(L(note))
|
||||
|
||||
@@ -305,7 +358,7 @@ class BattlePassWindow(ui.Window):
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide();self.closeButton.event=self.finalButton.event=self.prev.event=self.next.event=None
|
||||
self.Hide();self.closeButton.event=self.finalButton.event=self.activateButton.event=self.prev.event=self.next.event=None
|
||||
for row in self.rows:row['button'].event=None
|
||||
self.state=None
|
||||
|
||||
@@ -327,7 +380,10 @@ def OnPass(kind,value):
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L('战令任务完成:')+name+L(',按 F6 领取奖励'))
|
||||
elif kind=='claimed':chat.AppendChat(chat.CHAT_TYPE_INFO,L('战令奖励已放入背包' if value else '战令最终奖励已放入背包'))
|
||||
elif kind=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[s.error]))
|
||||
if g_window and g_window.IsShow():g_window.Refresh()
|
||||
if g_window and g_window.IsShow():
|
||||
if kind=='info' and g_window.pendingTicket:
|
||||
ticket=g_window.pendingTicket;g_window.pendingTicket=None;g_window.AskTicket(*ticket)
|
||||
g_window.Refresh()
|
||||
|
||||
|
||||
g_pass=Pass(net.SendChatPacket,app.GetTime,OnPass)
|
||||
|
||||
@@ -24,6 +24,20 @@ g_tick=None
|
||||
PAGE=8
|
||||
REFRESH=30.
|
||||
SHARED_CHANNEL=99
|
||||
TRAVEL_LEVELS={9844:(40,60),9836:(65,85),9838:(80,100),9840:(95,115),9842:(105,120),
|
||||
1093:(40,120),2092:(70,120),2493:(75,120),2598:(80,120),6091:(90,120),
|
||||
6191:(90,120),9018:(105,120),20442:(110,120)}
|
||||
|
||||
|
||||
def Travel(vnum,done=None):
|
||||
service=mt_feature_service.g_service
|
||||
if not service:return
|
||||
def received(data,error):
|
||||
errors={'unsupported':'服务器未启用此入口传送','level':'等级不符合入口要求',
|
||||
'busy':'当前状态不能传送,请稍后再试','unavailable':'服务器尚未开放该地图'}
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L(errors.get(error,'传送失败,请稍后重试') if error else '正在前往入口'))
|
||||
if done:done(data,error)
|
||||
service.Request('travel',vnum,0,received)
|
||||
# Server map index -> map directory (share/locale/<locale>/map/index), for localeInfo.MINIMAP_ZONE_NAME_DICT.
|
||||
MAPS={1:'metin2_map_a1',3:'metin2_map_a3',4:'metin2_map_guild_01',5:'metin2_map_monkey_dungeon_11',
|
||||
6:'metin2_guild_village_01',21:'metin2_map_b1',23:'metin2_map_b3',24:'metin2_map_guild_02',
|
||||
@@ -117,10 +131,11 @@ class BossWindow(ui.Window):
|
||||
self.lines=[Text(self,18,0,'',0xffefdfc3) for i in range(PAGE)]
|
||||
self.details=[Text(self,30,0,'',0xffb2aa9a) for i in range(PAGE)]
|
||||
self.remindButtons=[Action(self,0,0,92,'',lambda i=i:self.Remind(i)) for i in range(PAGE)]
|
||||
self.travelButtons=[Action(self,0,0,72,'传送',lambda i=i:self.Teleport(i)) for i in range(PAGE)]
|
||||
self.note=Text(self,18,0,'提醒:Boss 刷新后在聊天框提示;以服务器刷新为准。',0xffb2aa9a)
|
||||
self.Reflow();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons
|
||||
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons+self.travelButtons
|
||||
|
||||
def Open(self):
|
||||
self.Reflow();self.SetCenterPosition();self.Show();self.SetTop();self.Query()
|
||||
@@ -147,6 +162,12 @@ class BossWindow(ui.Window):
|
||||
rows=self.tracker.rows or [];index=self.page*PAGE+i
|
||||
if index<len(rows):self.tracker.Toggle(rows[index]);self.Render()
|
||||
|
||||
def Teleport(self,i):
|
||||
rows=self.tracker.rows or [];index=self.page*PAGE+i
|
||||
if index>=len(rows) or rows[index]['vnum'] not in TRAVEL_LEVELS:return
|
||||
self.travelButtons[i].SetEnabled(False)
|
||||
Travel(rows[index]['vnum'],lambda data,error:self.Render())
|
||||
|
||||
def Render(self):
|
||||
t=self.tracker;rows=t.rows or [];self.page=min(self.page,self.Pages()-1)
|
||||
if t.error:self.status.SetText(L('服务端未启用 Boss 追踪' if t.error=='unsupported' else '未同步,请稍后刷新'))
|
||||
@@ -156,6 +177,7 @@ class BossWindow(ui.Window):
|
||||
self.prevButton.SetEnabled(self.page>0);self.nextButton.SetEnabled(self.page+1<self.Pages())
|
||||
for i in range(PAGE):
|
||||
index=self.page*PAGE+i;line=self.lines[i];detail=self.details[i];button=self.remindButtons[i]
|
||||
travel=self.travelButtons[i];travel.Hide()
|
||||
if index>=len(rows):line.Hide();detail.Hide();button.Hide();continue
|
||||
r=rows[index];left=t.Left(r)
|
||||
channel='共享' if r['channel']==SHARED_CHANNEL else 'CH%d'%r['channel']
|
||||
@@ -169,6 +191,9 @@ class BossWindow(ui.Window):
|
||||
button.SetText(L('提醒:'+('开' if Key(r) in t.reminders else '关')))
|
||||
button.SetEnabled(bool(r['alive']==0 and r['next']) or Key(r) in t.reminders)
|
||||
line.Show();detail.Show();button.Show()
|
||||
service=mt_feature_service.g_service
|
||||
if r['vnum'] in TRAVEL_LEVELS and service and service.mask is not None and service.mask&512:
|
||||
travel.Show();travel.SetEnabled(not service.pending and not service.queue)
|
||||
|
||||
def Reflow(self):
|
||||
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
|
||||
@@ -179,6 +204,7 @@ class BossWindow(ui.Window):
|
||||
for i in range(PAGE):
|
||||
y=88+i*spacing
|
||||
self.lines[i].SetPosition(18,y);self.details[i].SetPosition(30,y+18);self.remindButtons[i].SetPosition(width-110,y)
|
||||
self.travelButtons[i].SetPosition(width-190,y)
|
||||
self.note.SetPosition(18,height-22);self.SetCenterPosition()
|
||||
|
||||
def OnUpdate(self):
|
||||
|
||||
@@ -21,18 +21,22 @@ LEVEL_HINTS=('显示所有角色的特效','隐藏其他玩家和NPC的特效,
|
||||
|
||||
|
||||
class Options(object):
|
||||
def __init__(self):self.effect=0;self.tree=True;self.cloud=True
|
||||
def __init__(self):self.effect=0;self.tree=True;self.cloud=True;self.shopRange=0;self.npcNames=True
|
||||
|
||||
def Load(self,text):
|
||||
words=text.split()
|
||||
if len(words)!=3 or not all(w.isdigit() and len(w)==1 for w in words):return
|
||||
effect,tree,cloud=[int(w) for w in words]
|
||||
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1):self.effect=effect;self.tree=tree==1;self.cloud=cloud==1
|
||||
if len(words) not in (3,5) or not all(w.isdigit() and len(w)==1 for w in words):return
|
||||
effect,tree,cloud=[int(w) for w in words[:3]]
|
||||
shop,names=[int(w) for w in words[3:]] if len(words)==5 else (0,1)
|
||||
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1) and shop<5 and names in (0,1):
|
||||
self.effect=effect;self.tree=tree==1;self.cloud=cloud==1;self.shopRange=shop;self.npcNames=names==1
|
||||
|
||||
def Dump(self):return '%d %d %d'%(self.effect,int(self.tree),int(self.cloud))
|
||||
def Dump(self):return '%d %d %d %d %d'%(self.effect,int(self.tree),int(self.cloud),self.shopRange,int(self.npcNames))
|
||||
|
||||
def Apply(self):
|
||||
systemSetting.SetEffectLevel(self.effect)
|
||||
systemSetting.SetShopNamesRange(self.shopRange)
|
||||
systemSetting.SetShopNameStatus(self.npcNames)
|
||||
background.SetVisiblePart(background.PART_TREE,int(self.tree))
|
||||
background.SetVisiblePart(background.PART_CLOUD,int(self.cloud))
|
||||
|
||||
@@ -55,7 +59,7 @@ def Mark(text,on):return L(B(u'【%s】'%text if on else text))
|
||||
class DisplayWindow(ui.Window):
|
||||
def __init__(self,options):
|
||||
ui.Window.__init__(self);self.SetWindowName('DisplayWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.options=options;self.SetSize(332,404)
|
||||
self.options=options;self.SetSize(332,456)
|
||||
self.heading=Text(self,18,18,'显示设置',0xffffd68b)
|
||||
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
|
||||
self.effectText=Text(self,18,54,'特效',0xffc3b7a1)
|
||||
@@ -65,10 +69,12 @@ class DisplayWindow(ui.Window):
|
||||
self.cloudButton=Action(self,170,260,144,'',self.ToggleCloud)
|
||||
self.nameButton=Action(self,18,312,144,'',self.ToggleName)
|
||||
self.damageButton=Action(self,170,312,144,'',self.ToggleDamage)
|
||||
self.status=Text(self,18,376,'',0xffc3b7a1)
|
||||
self.rangeButton=Action(self,18,364,144,'',self.NextRange)
|
||||
self.npcButton=Action(self,170,364,144,'',self.ToggleNPC)
|
||||
self.status=Text(self,18,428,'',0xffc3b7a1)
|
||||
self.Refresh();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton]+self.levelButtons
|
||||
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton,self.rangeButton,self.npcButton]+self.levelButtons
|
||||
|
||||
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
|
||||
|
||||
@@ -80,6 +86,10 @@ class DisplayWindow(ui.Window):
|
||||
|
||||
def ToggleCloud(self):self.options.cloud=not self.options.cloud;self.Changed()
|
||||
|
||||
def NextRange(self):self.options.shopRange=(self.options.shopRange+1)%5;self.Changed()
|
||||
|
||||
def ToggleNPC(self):self.options.npcNames=not self.options.npcNames;self.Changed()
|
||||
|
||||
# Names and damage numbers are the original game options (saved by the client config on exit).
|
||||
def ToggleName(self):systemSetting.SetAlwaysShowNameFlag(not systemSetting.IsAlwaysShowName());self.Refresh()
|
||||
|
||||
@@ -91,6 +101,8 @@ class DisplayWindow(ui.Window):
|
||||
self.treeButton.SetText(Mark(u'显示树木',o.tree));self.cloudButton.SetText(Mark(u'显示云',o.cloud))
|
||||
self.nameButton.SetText(Mark(u'总是显示名字',systemSetting.IsAlwaysShowName()))
|
||||
self.damageButton.SetText(Mark(u'显示伤害数字',systemSetting.IsShowDamage()))
|
||||
self.rangeButton.SetText(L(B(u'摊位范围 %d 米'%((100,60,40,20,10)[o.shopRange]))))
|
||||
self.npcButton.SetText(Mark(u'显示NPC名称',o.npcNames))
|
||||
self.status.SetText(L(LEVEL_HINTS[o.effect]))
|
||||
|
||||
def OnRender(self):
|
||||
|
||||
@@ -33,6 +33,7 @@ class DungeonWindow(ui.Window):
|
||||
self.rows=[Text(self,24,142+32*i,'',0xffefdfc3) for i in range(6)]
|
||||
self.remindButton=Action(self,18,0,146,'到期提醒:关',self.Remind)
|
||||
self.entryButton=Action(self,180,0,146,'查看入口',self.Entry)
|
||||
self.travelButton=Action(self,342,0,146,'传送到入口',self.Travel)
|
||||
self.note=Text(self,18,0,'当前仅接入已核实的龙穴及相关周任务。',0xffb2aa9a)
|
||||
self.Reflow();self.Hide()
|
||||
|
||||
@@ -92,6 +93,15 @@ class DungeonWindow(ui.Window):
|
||||
self.remindButton.SetText('到期提醒:'+('开' if self.reminder is not None and self.reminder[0]==self.tab else '关'))
|
||||
self.remindButton.SetEnabled(v is not None and not self.stale and (self.tab==0 or 'weekly_end' in v))
|
||||
self.entryButton.SetEnabled(v is not None and not self.stale and (self.tab==0 or 'weekly_npc' in v))
|
||||
service=mt_feature_service.g_service
|
||||
if self.tab==0 and service and service.mask is not None and service.mask&512:self.travelButton.Show()
|
||||
else:self.travelButton.Hide()
|
||||
self.travelButton.SetEnabled(v is not None and not self.stale)
|
||||
|
||||
def Travel(self):
|
||||
if self.values is None or self.stale or self.tab!=0:return
|
||||
import mt_boss
|
||||
mt_boss.Travel(2493)
|
||||
|
||||
def Entry(self):
|
||||
if self.values is None or self.stale:return
|
||||
@@ -124,6 +134,7 @@ class DungeonWindow(ui.Window):
|
||||
if dims==self.dimensions:return
|
||||
self.dimensions=dims;width=min(660,max(500,dims[0]-16));height=min(450,max(300,dims[1]-16));self.SetSize(width,height)
|
||||
self.closeButton.SetPosition(width-76,6)
|
||||
self.travelButton.SetPosition(342,height-74)
|
||||
spacing=min(32,max(16,(height-250)//5))
|
||||
for i,row in enumerate(self.rows):row.SetPosition(24,132+i*spacing)
|
||||
self.remindButton.SetPosition(18,height-74);self.entryButton.SetPosition(180,height-74);self.note.SetPosition(18,height-18)
|
||||
@@ -148,7 +159,7 @@ class DungeonWindow(ui.Window):
|
||||
|
||||
def Destroy(self):
|
||||
self.generation+=1;self.reminder=None;self.values=None;self.Hide()
|
||||
for b in (self.closeButton,self.lairButton,self.weeklyButton,self.refreshButton,self.remindButton,self.entryButton):b.event=None
|
||||
for b in (self.closeButton,self.lairButton,self.weeklyButton,self.refreshButton,self.remindButton,self.entryButton,self.travelButton):b.event=None
|
||||
|
||||
|
||||
class ReminderTick(ui.Window):
|
||||
|
||||
@@ -6,7 +6,7 @@ import net
|
||||
import ui
|
||||
from mt_wiki_data import Number
|
||||
|
||||
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256}
|
||||
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256,'travel':512}
|
||||
WHOLE=('stats','dungeons','bosses') # one reply with every row; no subject or page
|
||||
g_service=None
|
||||
g_tick=None
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// PORT: touch equivalents of AVA2's inventory preview / chest shortcuts.
|
||||
// Native touch selection invokes ShowInventory; no synthetic modifier keys.
|
||||
static const char c_szItemActionsScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import game
|
||||
import grp
|
||||
import player
|
||||
import ui
|
||||
import uiInventory
|
||||
import weakref
|
||||
import wndMgr
|
||||
from mt_biolog import Action
|
||||
|
||||
g_window=None
|
||||
|
||||
|
||||
class ItemActions(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self);self.AddFlag('float');self.SetWindowName('TouchItemActions')
|
||||
self.snapshot=None;self.buttons=[];self.Hide()
|
||||
|
||||
def Clear(self):
|
||||
self.Hide();self.snapshot=None
|
||||
for button in self.buttons:button.Hide();button.event=None
|
||||
self.buttons=[]
|
||||
|
||||
def Valid(self):
|
||||
if not self.snapshot:return False
|
||||
try:
|
||||
owner,page,cell,vnum,count=self.snapshot
|
||||
return (owner.IsShow() and owner.inventoryPageIndex==page and
|
||||
player.GetItemIndex(cell)==vnum and player.GetItemCount(cell)==count)
|
||||
except ReferenceError:return False
|
||||
|
||||
def Select(self,owner,cell):
|
||||
self.Clear()
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if not vnum:return
|
||||
self.snapshot=(weakref.proxy(owner),owner.inventoryPageIndex,cell,vnum,player.GetItemCount(cell))
|
||||
import mt_preview
|
||||
import mt_chest
|
||||
import mt_wiki
|
||||
choices=[('百科',lambda:mt_wiki.OpenItem(vnum))]
|
||||
if mt_preview.ItemSpec(vnum):choices.append(('模型预览',lambda:mt_preview.Preview('item',vnum)))
|
||||
if mt_chest.g_window and mt_chest.Batchable(vnum):
|
||||
choices.append(('批量开箱',lambda:mt_chest.g_window.Select(cell,vnum)))
|
||||
choices.append(('关闭',self.Clear))
|
||||
for i,(label,action) in enumerate(choices):
|
||||
self.buttons.append(Action(self,8+i*108,6,100,label,lambda action=action:self.Run(action)))
|
||||
self.SetSize(16+len(choices)*108,60)
|
||||
x,y=owner.GetGlobalPosition()
|
||||
self.SetPosition(max(0,min(x,wndMgr.GetScreenWidth()-self.GetWidth())),
|
||||
max(0,min(y+owner.GetHeight(),wndMgr.GetScreenHeight()-self.GetHeight())))
|
||||
self.Show();self.SetTop()
|
||||
|
||||
def Run(self,action):
|
||||
valid=self.Valid();self.Clear()
|
||||
if valid:action()
|
||||
|
||||
def OnUpdate(self):
|
||||
if self.IsShow() and not self.Valid():self.Clear()
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnPressEscapeKey(self):self.Clear();return True
|
||||
|
||||
|
||||
def ShowInventory(owner,cell):
|
||||
if g_window:g_window.Select(owner,cell)
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
|
||||
def Open(self):
|
||||
global g_window
|
||||
_open(self);g_window=ItemActions()
|
||||
|
||||
def Close(self):
|
||||
global g_window
|
||||
if g_window:g_window.Clear();g_window=None
|
||||
_close(self)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
|
||||
_use=uiInventory.InventoryWindow.UseItemSlot
|
||||
|
||||
def UseItemSlot(self,slot):
|
||||
cell=self._InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos(slot)
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if 25150<=vnum<=25161:
|
||||
import mt_battlepass
|
||||
if mt_battlepass.g_window:mt_battlepass.g_window.OfferTicket(cell,vnum)
|
||||
return
|
||||
if vnum in (50348,50349):
|
||||
import mt_switchbot
|
||||
if mt_switchbot.g_window:mt_switchbot.g_window.Open()
|
||||
return
|
||||
return _use(self,slot)
|
||||
|
||||
uiInventory.InventoryWindow.UseItemSlot=UseItemSlot
|
||||
)PY";
|
||||
@@ -0,0 +1,30 @@
|
||||
// PORT: networking is prepared by the native transport, independently of the login UI.
|
||||
#include <Python.h>
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h"
|
||||
#include "MeshPortConfig.h"
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
namespace {
|
||||
PyObject* event(PyObject*,PyObject*) { return PyInt_FromLong(mt::meshport::take_event()); }
|
||||
PyObject* local(PyObject*,PyObject* args) {
|
||||
const char* ip;if(!PyArg_ParseTuple(args,"s",&ip))return nullptr;
|
||||
return PyBool_FromLong(mt::meshport::same_subnet(ip));
|
||||
}
|
||||
PyMethodDef methods[]={
|
||||
{"event",event,METH_NOARGS,nullptr},{"same_subnet",local,METH_VARARGS,nullptr},
|
||||
{nullptr,nullptr,0,nullptr}
|
||||
};
|
||||
}
|
||||
void initMeshPort() {
|
||||
std::string config=kMeshPortConfig;
|
||||
if(const char* path=std::getenv("MT_MESHPORT_CONFIG")) {
|
||||
std::ifstream input(path,std::ios::binary);
|
||||
config.assign(std::istreambuf_iterator<char>(input),{});
|
||||
}
|
||||
if(config.size()>65536)config.clear();
|
||||
mt::meshport::configure(config);
|
||||
Py_InitModule("_mt_meshport",methods);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
// PORT: native transport owns routing; Python displays status and handles pending-login cancellation.
|
||||
static const char* c_szMeshPortScript = R"PY(# -*- coding: utf-8 -*-
|
||||
import app
|
||||
import ui
|
||||
import wndMgr
|
||||
import player
|
||||
import introLogin
|
||||
import net
|
||||
import _mt_meshport as native
|
||||
|
||||
|
||||
class NetworkNotice(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self)
|
||||
self.label = ui.TextLine()
|
||||
self.label.SetHorizontalAlignCenter()
|
||||
self.hideAt = 0
|
||||
self.Show()
|
||||
|
||||
def OnUpdate(self):
|
||||
event = native.event()
|
||||
if event:
|
||||
messages = {1: '正在组网,等待动态分配 IP...',
|
||||
2: '组网成功', 3: '组网连接失败,请检查网络后重试'}
|
||||
self.label.SetText(player.AutoHuntLocalize(messages[event]))
|
||||
self.label.SetPackedFontColor(0xff66ee88 if event == 2 else 0xffffdd77)
|
||||
self.label.SetPosition(wndMgr.GetScreenWidth() / 2, 32)
|
||||
self.label.Show()
|
||||
self.label.SetTop()
|
||||
self.hideAt = app.GetTime() + (65 if event == 1 else 6)
|
||||
if self.hideAt and app.GetTime() >= self.hideAt:
|
||||
self.label.Hide()
|
||||
self.hideAt = 0
|
||||
|
||||
|
||||
notice = NetworkNotice()
|
||||
|
||||
# Original login popup uses the focus callback for its Cancel button. Stop only
|
||||
# the account/game transports still preparing; leave established sessions and
|
||||
# background channel queries alone. No credentials or Connect methods are wrapped.
|
||||
def _wrap_cancel(method):
|
||||
def Cancel(self, *args):
|
||||
if net.CancelPendingLogin():
|
||||
notice.label.Hide()
|
||||
notice.hideAt = 0
|
||||
return method(self, *args)
|
||||
return Cancel
|
||||
|
||||
introLogin.LoginWindow.SetPasswordEditLineFocus = _wrap_cancel(introLogin.LoginWindow.SetPasswordEditLineFocus)
|
||||
introLogin.LoginWindow.OnPressExitKey = _wrap_cancel(introLogin.LoginWindow.OnPressExitKey)
|
||||
introLogin.LoginWindow.Close = _wrap_cancel(introLogin.LoginWindow.Close)
|
||||
)PY";
|
||||
@@ -56,6 +56,9 @@ def _Select(self, slot):
|
||||
_last_time = app.GetTime()
|
||||
if _last[3]:
|
||||
self.ShowToolTip(_last[2])
|
||||
import sys
|
||||
actions = sys.modules.get('mt_item_actions')
|
||||
if actions:actions.ShowInventory(self, _last[2])
|
||||
return
|
||||
snapshot = _Snapshot(self, slot) if dragging and not mouse.isAttached() else None
|
||||
result = _OriginalSelect(self, slot)
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
#include "UserInterface/CRenderTargetManager.h"
|
||||
#include "EterBase/Timer.h"
|
||||
#include "PythonBoot.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h"
|
||||
#endif
|
||||
#include "../UserInterface/UserInterface.h"
|
||||
#include "PythonHost.h"
|
||||
#include "../EterLib/UIRenderCommands.h"
|
||||
@@ -252,6 +255,10 @@ void* fiber_main(void*)
|
||||
}
|
||||
|
||||
void init_2v0_gameplay_stubs();
|
||||
void StopAccountRegistration(); // PORT: drain registration before networking teardown.
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
void initMeshPort();
|
||||
#endif
|
||||
|
||||
namespace PythonBoot
|
||||
{
|
||||
@@ -901,6 +908,9 @@ bool run_main_script_body(const char* lpCmdLine, std::string* error)
|
||||
initChat();
|
||||
initTextTail();
|
||||
initnet();
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
initMeshPort();
|
||||
#endif
|
||||
initMiniMap();
|
||||
initEvent();
|
||||
initeffect();
|
||||
@@ -1021,6 +1031,10 @@ namespace PythonBoot
|
||||
#include "CostumeAttrScript.inc"
|
||||
#include "PendantScript.inc"
|
||||
#include "RingsScript.inc"
|
||||
#include "ItemActionsScript.inc"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "MeshPortScript.inc"
|
||||
#endif
|
||||
|
||||
static void install_script_module(const char* c_szModule, const char* c_szScript)
|
||||
{
|
||||
@@ -1076,6 +1090,9 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
|
||||
{
|
||||
install_script_module("mt_autohunt", c_szAutoHuntScript);
|
||||
install_script_module("mt_register", c_szRegisterScript);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
install_script_module("mt_meshport", c_szMeshPortScript);
|
||||
#endif
|
||||
install_script_module("mt_framerate", c_szFrameRateOptionScript);
|
||||
install_script_module("mt_uiscale", c_szUIScaleOptionScript);
|
||||
install_script_module("mt_inventory", c_szInventoryPagesScript);
|
||||
@@ -1110,6 +1127,7 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
|
||||
install_script_module("mt_costume_attr", c_szCostumeAttrScript);
|
||||
install_script_module("mt_pendant", c_szPendantScript);
|
||||
install_script_module("mt_rings", c_szRingsScript);
|
||||
install_script_module("mt_item_actions", c_szItemActionsScript);
|
||||
if (g_touch_input)
|
||||
install_script_module("mt_mobile_hud", c_szMobileHUDScript);
|
||||
}
|
||||
@@ -1214,6 +1232,10 @@ void Stop()
|
||||
" getattr(_mm.mouseController, 'cursorDict', {}).clear()\n");
|
||||
PyGILState_Release(gil);
|
||||
}
|
||||
StopAccountRegistration();
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::shutdown(); // PORT: join SDK worker and stop mesh before Python/platform teardown.
|
||||
#endif
|
||||
g_launcher->Clear();
|
||||
g_game_singletons.reset();
|
||||
g_game_application.reset();
|
||||
|
||||
@@ -159,6 +159,8 @@ class RegisterDialog(ui.BoardWithTitleBar):
|
||||
ui.__mem_func__(self.Close))
|
||||
|
||||
def Destroy(self):
|
||||
if self.pending:
|
||||
net.CancelRegisterAccount()
|
||||
self.Hide()
|
||||
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
|
||||
row.Destroy()
|
||||
@@ -178,6 +180,11 @@ class RegisterDialog(ui.BoardWithTitleBar):
|
||||
self.loginRow.edit.SetFocus()
|
||||
|
||||
def Close(self):
|
||||
if self.pending:
|
||||
net.CancelRegisterAccount()
|
||||
self.pending = False
|
||||
self.pendingPassword = ""
|
||||
self.registerButton.Enable()
|
||||
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
|
||||
row.edit.KillFocus()
|
||||
self.Hide()
|
||||
|
||||
@@ -31,7 +31,7 @@ REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达
|
||||
ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练',
|
||||
'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练',
|
||||
'unsupported':'服务器尚未启用自动洗练','slot':'该条属性不能锁定','max':'最多锁定 2 条,且至少留 1 条可洗',
|
||||
'db':'锁定保存失败,请稍后再试'}
|
||||
'db':'锁定保存失败,请稍后再试','five_attr':'装备需要 5 条普通属性才能锁定','material':'锁定需要道具 50348,解锁需要道具 50349'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=4294967295):
|
||||
@@ -189,8 +189,8 @@ class SwitchbotWindow(ui.Window):
|
||||
if not vnum:continue
|
||||
item.SelectItem(vnum);kind=item.GetItemType()
|
||||
# 54001-54267 with a value2 mask are AVA2 costume enchants (mt_costume_attr), 71302 / 53996 talisman
|
||||
# rerolls (mt_pendant), not switchers; talismans have their own attribute pool.
|
||||
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE and not (54001<=vnum<=54267 and item.GetValue(2)) and vnum not in (71302,53996):
|
||||
# rerolls (mt_pendant) and 50348 / 50349 attribute lock materials, not switchers; talismans have their own attribute pool.
|
||||
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE and not (54001<=vnum<=54267 and item.GetValue(2)) and vnum not in (71302,53996,50348,50349):
|
||||
scrolls[vnum]=scrolls.get(vnum,0)+player.GetItemCount(player.INVENTORY,cell)
|
||||
elif kind in (item.ITEM_TYPE_WEAPON,item.ITEM_TYPE_ARMOR) and not (kind==item.ITEM_TYPE_ARMOR and item.GetItemSubType()==item.ARMOR_PENDANT) and any(player.GetItemAttribute(player.INVENTORY,cell,i)[0] for i in range(5)):
|
||||
items.append((cell,vnum))
|
||||
|
||||
@@ -19,6 +19,9 @@ if(NOT TARGET mtpython)
|
||||
endif()
|
||||
|
||||
add_library(port_logic STATIC ${MT_PORT_SOURCES})
|
||||
if(TARGET mt_meshport)
|
||||
target_link_libraries(port_logic PUBLIC mt_meshport)
|
||||
endif()
|
||||
target_include_directories(port_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
# 40250 system headers the ported sources keep including verbatim: D3D8/D3DX/Miles SDK types everywhere,
|
||||
# Windows/CRT ones only where the platform has none.
|
||||
@@ -326,6 +329,12 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_channel.py)
|
||||
add_test(NAME port.boss
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_boss.py)
|
||||
add_test(NAME port.battlepass
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_battlepass.py)
|
||||
add_test(NAME port.model_preview
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_model_preview.py)
|
||||
add_test(NAME port.item_actions
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_item_actions.py)
|
||||
add_test(NAME port.chest
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_chest.py)
|
||||
add_test(NAME port.ava2_items
|
||||
|
||||
@@ -32,9 +32,15 @@ void CNetworkAddress::Clear()
|
||||
|
||||
bool CNetworkAddress::IsIP(const char* c_szAddr)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
// PORT: digit-prefixed hostnames must resolve before the common subnet decision.
|
||||
in_addr parsed{};
|
||||
return c_szAddr && inet_pton(AF_INET,c_szAddr,&parsed) == 1;
|
||||
#else
|
||||
if (c_szAddr[0]<'0' || c_szAddr[0]>'9')
|
||||
return false;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool CNetworkAddress::Set(const char* c_szAddr, int port)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagram.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: preserve datagram payload/source/peek semantics over application-only mesh.
|
||||
#endif
|
||||
|
||||
CNetworkDatagram::CNetworkDatagram()
|
||||
{
|
||||
@@ -16,6 +19,9 @@ void CNetworkDatagram::Destroy()
|
||||
if (INVALID_SOCKET==m_sock)
|
||||
return;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_sock);
|
||||
#endif
|
||||
closesocket(m_sock);
|
||||
|
||||
__Initialize();
|
||||
@@ -68,6 +74,9 @@ void CNetworkDatagram::Update()
|
||||
|
||||
bool CNetworkDatagram::CanRecv()
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (mt::meshport::datagram_ready(m_sock)) return true;
|
||||
#endif
|
||||
if (FD_ISSET(m_sock, &m_fdsRecv))
|
||||
return true;
|
||||
|
||||
@@ -77,19 +86,31 @@ bool CNetworkDatagram::CanRecv()
|
||||
|
||||
int CNetworkDatagram::PeekRecvFrom(UINT uBufLen, void* pvBuf, SOCKADDR_IN* pkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::recv_datagram(m_sock,pvBuf,uBufLen,MSG_PEEK,pkSockAddrIn);
|
||||
#else
|
||||
int nSockAddrInLen=sizeof(SOCKADDR_IN);
|
||||
return recvfrom(m_sock, (char*)pvBuf, uBufLen, MSG_PEEK, (PSOCKADDR)pkSockAddrIn, &nSockAddrInLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNetworkDatagram::RecvFrom(UINT uBufLen, void* pvBuf, SOCKADDR_IN* pkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::recv_datagram(m_sock,pvBuf,uBufLen,0,pkSockAddrIn);
|
||||
#else
|
||||
int nSockAddrInLen=sizeof(SOCKADDR_IN);
|
||||
return recvfrom(m_sock, (char*)pvBuf, uBufLen, 0, (PSOCKADDR)pkSockAddrIn, &nSockAddrInLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNetworkDatagram::SendTo(UINT uBufLen, const void* c_pvBuf, const SOCKADDR_IN& c_rkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::send_datagram(m_sock,c_pvBuf,uBufLen,0,c_rkSockAddrIn);
|
||||
#else
|
||||
return sendto(m_sock, (const char *)c_pvBuf, uBufLen, 0, (PSOCKADDR)&c_rkSockAddrIn, sizeof(SOCKADDR_IN));
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagramReceiver.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: shared datagram receive and relay lifetime.
|
||||
#endif
|
||||
|
||||
BOOL CNetDatagramReceiver::Process()
|
||||
{
|
||||
m_recvBufCurrentPos = 0;
|
||||
m_recvBufCurrentSize = 0;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
m_recvBufCurrentSize = mt::meshport::recv_datagram(m_Socket,m_recvBuf,m_recvBufSize,0,&m_SockAddr);
|
||||
#else
|
||||
int irecvAddrLength = sizeof(SOCKADDR_IN);
|
||||
m_recvBufCurrentSize = recvfrom(m_Socket, (char *)m_recvBuf, m_recvBufSize, 0, (PSOCKADDR)&m_SockAddr, &irecvAddrLength);
|
||||
#endif
|
||||
|
||||
if (m_recvBufCurrentSize <= 0)
|
||||
{
|
||||
@@ -42,7 +49,9 @@ BOOL CNetDatagramReceiver::isBind()
|
||||
|
||||
BOOL CNetDatagramReceiver::Bind(DWORD /*dwAddress*/, WORD wPortIndex)
|
||||
{
|
||||
Clear(); // PORT: rebinding releases any previous UDP/mesh association.
|
||||
m_Socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (m_Socket == INVALID_SOCKET) return FALSE;
|
||||
|
||||
DWORD arg = 1;
|
||||
ioctlsocket(m_Socket, FIONBIO, &arg); // Non-blocking mode
|
||||
@@ -56,6 +65,8 @@ BOOL CNetDatagramReceiver::Bind(DWORD /*dwAddress*/, WORD wPortIndex)
|
||||
if (bind(m_Socket, (PSOCKADDR)&m_SockAddr, sizeof(SOCKADDR_IN)) < 0)
|
||||
{
|
||||
Tracef("Failed binding socket\n");
|
||||
closesocket(m_Socket);
|
||||
m_Socket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
@@ -79,6 +90,12 @@ void CNetDatagramReceiver::SetRecvBufferSize(int recvBufSize)
|
||||
|
||||
void CNetDatagramReceiver::Clear()
|
||||
{
|
||||
if (m_isBind) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket); // PORT: close UDP and any mesh association before resetting state.
|
||||
}
|
||||
|
||||
m_isBind = FALSE;
|
||||
|
||||
@@ -93,6 +110,7 @@ void CNetDatagramReceiver::Clear()
|
||||
|
||||
CNetDatagramReceiver::CNetDatagramReceiver()
|
||||
{
|
||||
m_isBind = FALSE;
|
||||
m_recvBuf = NULL;
|
||||
m_recvBufSize = 0;
|
||||
|
||||
@@ -100,6 +118,7 @@ CNetDatagramReceiver::CNetDatagramReceiver()
|
||||
}
|
||||
CNetDatagramReceiver::~CNetDatagramReceiver()
|
||||
{
|
||||
Clear();
|
||||
if (m_recvBuf)
|
||||
delete [] m_recvBuf;
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagramSender.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: common LAN/mesh policy and relay lifetime.
|
||||
#endif
|
||||
|
||||
BOOL CNetDatagramSender::SetSocket(const char * c_szIP, WORD wPortIndex)
|
||||
{
|
||||
@@ -8,12 +11,19 @@ BOOL CNetDatagramSender::SetSocket(const char * c_szIP, WORD wPortIndex)
|
||||
|
||||
BOOL CNetDatagramSender::SetSocket(DWORD dwAddress, WORD wPortIndex)
|
||||
{
|
||||
if (m_isSocket) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket);
|
||||
}
|
||||
m_isSocket = TRUE;
|
||||
|
||||
m_dwAddress = dwAddress;
|
||||
m_wPortIndex = wPortIndex;
|
||||
|
||||
m_Socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (m_Socket == INVALID_SOCKET) { m_isSocket = FALSE; return FALSE; }
|
||||
|
||||
memset(&m_SockAddr, 0, sizeof(SOCKADDR_IN));
|
||||
m_SockAddr.sin_family = AF_INET;
|
||||
@@ -27,7 +37,11 @@ BOOL CNetDatagramSender::Send(const void * pBuffer, int iSize)
|
||||
{
|
||||
assert(isSocket());
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
int iSendingLength = mt::meshport::send_datagram(m_Socket,pBuffer,iSize,0,m_SockAddr);
|
||||
#else
|
||||
int iSendingLength = sendto(m_Socket, (const char *)pBuffer, iSize, 0, (PSOCKADDR)&m_SockAddr, sizeof(SOCKADDR_IN));
|
||||
#endif
|
||||
if (iSendingLength < 0)
|
||||
{
|
||||
Tracef("Failed sending packet\n");
|
||||
@@ -55,4 +69,10 @@ CNetDatagramSender::CNetDatagramSender()
|
||||
|
||||
CNetDatagramSender::~CNetDatagramSender()
|
||||
{
|
||||
if (m_isSocket) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket); // PORT: release the UDP socket and its mesh association together.
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetStream.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: application-only mesh transport, including account/warp/mark sockets.
|
||||
#endif
|
||||
//#include "eterCrypt.h"
|
||||
|
||||
#ifndef _IMPROVED_PACKET_ENCRYPTION_
|
||||
@@ -288,6 +291,19 @@ void CNetworkStream::Process()
|
||||
if (m_sock == INVALID_SOCKET)
|
||||
return;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (!m_isOnline && mt::meshport::pending(m_sock))
|
||||
{
|
||||
const int state = mt::meshport::poll_socket(m_sock);
|
||||
if (state < 0 || time(NULL) > m_connectLimitTime)
|
||||
{
|
||||
Clear();
|
||||
OnConnectFailure();
|
||||
return;
|
||||
}
|
||||
if (state == 0) return;
|
||||
}
|
||||
#endif
|
||||
fd_set fdsRecv;
|
||||
fd_set fdsSend;
|
||||
|
||||
@@ -373,6 +389,9 @@ void CNetworkStream::Clear()
|
||||
m_cipher.CleanUp();
|
||||
#endif
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_sock); // PORT: discard partial SOCKS negotiation before fd reuse.
|
||||
#endif
|
||||
closesocket(m_sock);
|
||||
m_sock = INVALID_SOCKET;
|
||||
|
||||
@@ -416,7 +435,12 @@ bool CNetworkStream::Connect(const CNetworkAddress& c_rkNetAddr, int limitSec)
|
||||
DWORD arg = 1;
|
||||
ioctlsocket(m_sock, FIONBIO, &arg); // Non-blocking mode
|
||||
|
||||
if (connect(m_sock, (PSOCKADDR)&m_addr, m_addr.GetSize()) == SOCKET_ERROR)
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
const int connectResult = mt::meshport::connect_socket(m_sock, static_cast<const SOCKADDR_IN&>(m_addr), this);
|
||||
#else
|
||||
const int connectResult = connect(m_sock, (PSOCKADDR)&m_addr, m_addr.GetSize());
|
||||
#endif
|
||||
if (connectResult == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
|
||||
@@ -430,6 +454,9 @@ bool CNetworkStream::Connect(const CNetworkAddress& c_rkNetAddr, int limitSec)
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (mt::meshport::pending(m_sock) && limitSec < 75) limitSec = 75; // PORT: DHCP/routes plus remote SOCKS connect.
|
||||
#endif
|
||||
m_connectLimitTime = time(NULL) + limitSec;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2473,11 +2473,24 @@ void CInstanceBase::__UpdateEffectShown()
|
||||
else
|
||||
isShown = false;
|
||||
}
|
||||
m_GraphicThingInstance.SetAttachingEffectShown(isShown);
|
||||
m_GraphicThingInstance.SetAttachingEffectShown(isShown && PORT_IsDisplayVisible());
|
||||
}
|
||||
|
||||
bool CInstanceBase::PORT_IsDisplayVisible()
|
||||
{
|
||||
// AVA2 CActorInstance::IsShop and InstanceBase::__CanRender, including
|
||||
// the original 100/60/40/20/10 metre range presets. Never hide the main actor.
|
||||
CInstanceBase* main = __GetMainInstancePtr();
|
||||
if (!main || main == this || GetRace() < 30000 || GetRace() > 30020)
|
||||
return true;
|
||||
static const unsigned ranges[] = {10000, 6000, 4000, 2000, 1000};
|
||||
return NEW_GetDistanceFromDestInstance(*main) <= ranges[CPythonSystem::Instance().GetShopNamesRange()];
|
||||
}
|
||||
|
||||
bool CInstanceBase::__CanRender()
|
||||
{
|
||||
if (!PORT_IsDisplayVisible())
|
||||
return false;
|
||||
if (!__IsInViewFrustum())
|
||||
return false;
|
||||
if (IsAffect(AFFECT_INVISIBILITY))
|
||||
|
||||
@@ -402,6 +402,7 @@ class CInstanceBase
|
||||
|
||||
public:
|
||||
void SetMainInstance();
|
||||
bool PORT_IsDisplayVisible();
|
||||
|
||||
void OnSelected();
|
||||
void OnUnselected();
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: registration shares the same LAN/mesh policy as every game socket.
|
||||
#endif
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
@@ -35,6 +39,11 @@ const int c_iRegisterTimeoutMs = 8000;
|
||||
std::mutex gs_kRegisterMutex;
|
||||
std::atomic<int> gs_iRegisterState(REGISTER_IDLE);
|
||||
std::string gs_strRegisterResult;
|
||||
// PORT: registration must stop on dialog cancellation and before the mesh runtime is torn down.
|
||||
std::thread gs_registerWorker;
|
||||
std::atomic<bool> gs_registerCancelled(false);
|
||||
std::mutex gs_registerSocketMutex;
|
||||
int gs_registerSocket = -1;
|
||||
|
||||
std::string __UrlEncode(const std::string& c_rstText)
|
||||
{
|
||||
@@ -58,8 +67,14 @@ std::string __UrlEncode(const std::string& c_rstText)
|
||||
|
||||
bool __WaitFor(int iSocket, short sEvents)
|
||||
{
|
||||
pollfd kPoll = { iSocket, sEvents, 0 };
|
||||
return poll(&kPoll, 1, c_iRegisterTimeoutMs) == 1 && (kPoll.revents & sEvents);
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(c_iRegisterTimeoutMs);
|
||||
while (!gs_registerCancelled && std::chrono::steady_clock::now() < deadline) {
|
||||
pollfd kPoll = {iSocket,sEvents,0};
|
||||
int result = poll(&kPoll,1,100);
|
||||
if (result > 0) return (kPoll.revents & sEvents) != 0;
|
||||
if (result < 0 && errno != EINTR) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c_rstBody)
|
||||
@@ -72,6 +87,7 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
if (getaddrinfo(c_rstHost.c_str(), std::to_string(iPort).c_str(), &kHints, &pkAddr) != 0 || !pkAddr)
|
||||
return "ERR CONNECT";
|
||||
|
||||
if (gs_registerCancelled) { freeaddrinfo(pkAddr); return "ERR CANCELLED"; }
|
||||
const int iSocket = socket(pkAddr->ai_family, pkAddr->ai_socktype, pkAddr->ai_protocol);
|
||||
if (iSocket < 0)
|
||||
{
|
||||
@@ -82,14 +98,37 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
const int iOne = 1;
|
||||
setsockopt(iSocket, SOL_SOCKET, SO_NOSIGPIPE, &iOne, sizeof(iOne));
|
||||
#endif
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
gs_registerSocket = iSocket;
|
||||
}
|
||||
fcntl(iSocket, F_SETFL, fcntl(iSocket, F_GETFL, 0) | O_NONBLOCK);
|
||||
|
||||
std::string stResult = "ERR CONNECT";
|
||||
int iError = 0;
|
||||
socklen_t iErrorLen = sizeof(iError);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
const int connected = mt::meshport::connect_socket(iSocket, *reinterpret_cast<sockaddr_in*>(pkAddr->ai_addr));
|
||||
const bool throughMesh = mt::meshport::pending(iSocket);
|
||||
bool meshReady = true;
|
||||
if (mt::meshport::pending(iSocket)) {
|
||||
int state = 0;
|
||||
while (state == 0 && !gs_registerCancelled) {
|
||||
state = mt::meshport::poll_socket(iSocket);
|
||||
if (!state) std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
}
|
||||
meshReady = state == 1;
|
||||
}
|
||||
if (!gs_registerCancelled && meshReady && (throughMesh || connected == 0 ||
|
||||
#else
|
||||
if (connect(iSocket, pkAddr->ai_addr, pkAddr->ai_addrlen) == 0 ||
|
||||
#endif
|
||||
(errno == EINPROGRESS && __WaitFor(iSocket, POLLOUT) &&
|
||||
getsockopt(iSocket, SOL_SOCKET, SO_ERROR, &iError, &iErrorLen) == 0 && iError == 0))
|
||||
getsockopt(iSocket, SOL_SOCKET, SO_ERROR, &iError, &iErrorLen) == 0 && iError == 0)
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
)
|
||||
#endif
|
||||
)
|
||||
{
|
||||
const std::string stRequest =
|
||||
"POST /register HTTP/1.0\r\n"
|
||||
@@ -140,9 +179,16 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
}
|
||||
}
|
||||
|
||||
close(iSocket);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(iSocket);
|
||||
#endif
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
gs_registerSocket = -1;
|
||||
close(iSocket);
|
||||
}
|
||||
freeaddrinfo(pkAddr);
|
||||
return stResult;
|
||||
return gs_registerCancelled ? "ERR CANCELLED" : stResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,10 +218,12 @@ PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs)
|
||||
return Py_BuildValue("i", 0); // one request at a time
|
||||
}
|
||||
|
||||
if (gs_registerWorker.joinable()) gs_registerWorker.join();
|
||||
gs_registerCancelled = false;
|
||||
const std::string stHost = szHost;
|
||||
const std::string stBody = "login=" + __UrlEncode(szLogin) + "&password=" + __UrlEncode(szPassword) +
|
||||
"&social_id=" + __UrlEncode(szSocialID);
|
||||
std::thread([stHost, iPort, stBody]()
|
||||
gs_registerWorker = std::thread([stHost, iPort, stBody]()
|
||||
{
|
||||
const std::string stResult = __Post(stHost, iPort, stBody);
|
||||
{
|
||||
@@ -183,7 +231,7 @@ PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs)
|
||||
gs_strRegisterResult = stResult;
|
||||
}
|
||||
gs_iRegisterState = REGISTER_DONE;
|
||||
}).detach();
|
||||
});
|
||||
return Py_BuildValue("i", 1);
|
||||
}
|
||||
|
||||
@@ -196,3 +244,22 @@ PyObject* netGetRegisterAccountResult(PyObject* poSelf, PyObject* poArgs)
|
||||
std::lock_guard<std::mutex> kLock(gs_kRegisterMutex);
|
||||
return Py_BuildValue("s", gs_strRegisterResult.c_str());
|
||||
}
|
||||
|
||||
// PORT: cancellation interrupts both route preparation and HTTP I/O; the worker owns close().
|
||||
void CancelAccountRegistration()
|
||||
{
|
||||
gs_registerCancelled = true;
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
if (gs_registerSocket >= 0) ::shutdown(gs_registerSocket,SHUT_RDWR);
|
||||
}
|
||||
void StopAccountRegistration()
|
||||
{
|
||||
CancelAccountRegistration();
|
||||
if (gs_registerWorker.joinable()) gs_registerWorker.join();
|
||||
gs_iRegisterState = REGISTER_IDLE;
|
||||
}
|
||||
PyObject* netCancelRegisterAccount(PyObject*,PyObject*)
|
||||
{
|
||||
CancelAccountRegistration();
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#include "StdAfx.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: cancel only this login's pending mesh transports.
|
||||
#endif
|
||||
#include "PythonNetworkStream.h"
|
||||
//#include "PythonNetworkDatagram.h"
|
||||
#include "AccountConnector.h"
|
||||
@@ -14,6 +17,7 @@ std::list<std::string> g_kList_strCommand;
|
||||
// PORT: PythonAccountRegister.cpp
|
||||
PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs);
|
||||
PyObject* netGetRegisterAccountResult(PyObject* poSelf, PyObject* poArgs);
|
||||
PyObject* netCancelRegisterAccount(PyObject*,PyObject*); // PORT: cancel pending HTTP/mesh work.
|
||||
|
||||
PyObject* netGetBettingGuildWarValue(PyObject* poSelf, PyObject* poArgs)
|
||||
{
|
||||
@@ -1014,6 +1018,22 @@ PyObject* netLogOutGame(PyObject* poSelf, PyObject* poArgs)
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
PyObject* netCancelPendingLogin(PyObject*,PyObject*)
|
||||
{
|
||||
bool cancelled = false;
|
||||
auto& account = CAccountConnector::Instance();
|
||||
auto& game = CPythonNetworkStream::Instance();
|
||||
if (mt::meshport::pending_owner(static_cast<CNetworkStream*>(&account))) {
|
||||
account.Disconnect(); cancelled = true;
|
||||
}
|
||||
if (mt::meshport::pending_owner(static_cast<CNetworkStream*>(&game))) {
|
||||
game.Disconnect(); cancelled = true;
|
||||
}
|
||||
return PyBool_FromLong(cancelled);
|
||||
}
|
||||
#endif
|
||||
|
||||
PyObject* netDisconnect(PyObject* poSelf, PyObject* poArgs)
|
||||
{
|
||||
CPythonNetworkStream& rkNetStream=CPythonNetworkStream::Instance();
|
||||
@@ -1774,6 +1794,10 @@ void initnet()
|
||||
{ "SendChangeNamePacket", netSendChangeNamePacket, METH_VARARGS },
|
||||
{ "SendCreateCharacterPacket", netSendCreateCharacterPacket, METH_VARARGS },
|
||||
{ "RegisterAccount", netRegisterAccount, METH_VARARGS },
|
||||
{ "CancelRegisterAccount", netCancelRegisterAccount, METH_NOARGS },
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
{ "CancelPendingLogin", netCancelPendingLogin, METH_NOARGS },
|
||||
#endif
|
||||
{ "GetRegisterAccountResult", netGetRegisterAccountResult, METH_VARARGS },
|
||||
{ "SendDestroyCharacterPacket", netSendDestroyCharacterPacket, METH_VARARGS },
|
||||
{ "SendEnterGamePacket", netSendEnterGamePacket, METH_VARARGS },
|
||||
|
||||
@@ -113,6 +113,10 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
// PORT: AVA2 effect_level (0 all, 1 hide players/NPCs, 2 hide monsters/NPCs, 3 hide others, 4 hide all).
|
||||
int GetEffectLevel() { return m_iPortEffectLevel; }
|
||||
void SetEffectLevel(int iLevel) { m_iPortEffectLevel = iLevel < 0 || iLevel > 4 ? 0 : iLevel; }
|
||||
int GetShopNamesRange() { return m_iPortShopRange; }
|
||||
void SetShopNamesRange(int index) { m_iPortShopRange = index < 0 || index > 4 ? 0 : index; }
|
||||
bool GetShopNameStatus() { return m_bPortNPCNames; }
|
||||
void SetShopNameStatus(bool shown) { m_bPortNPCNames = shown; }
|
||||
bool IsUseDefaultIME();
|
||||
bool IsNoSoundCard();
|
||||
bool IsAutoTiling();
|
||||
@@ -163,4 +167,6 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
PyObject * m_poInterfaceHandler;
|
||||
TWindowStatus m_WindowStatus[WINDOW_MAX_NUM];
|
||||
int m_iPortEffectLevel = 0;
|
||||
};
|
||||
int m_iPortShopRange = 0;
|
||||
bool m_bPortNPCNames = true;
|
||||
};
|
||||
|
||||
@@ -227,6 +227,29 @@ PyObject * systemGetEffectLevel(PyObject * poSelf, PyObject * poArgs)
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetEffectLevel());
|
||||
}
|
||||
|
||||
PyObject* systemSetShopNamesRange(PyObject*, PyObject* args)
|
||||
{
|
||||
int index;
|
||||
if (!PyTuple_GetInteger(args, 0, &index)) return Py_BadArgument();
|
||||
CPythonSystem::Instance().SetShopNamesRange(index);
|
||||
return Py_BuildNone();
|
||||
}
|
||||
PyObject* systemGetShopNamesRange(PyObject*, PyObject*)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetShopNamesRange());
|
||||
}
|
||||
PyObject* systemSetShopNameStatus(PyObject*, PyObject* args)
|
||||
{
|
||||
int shown;
|
||||
if (!PyTuple_GetInteger(args, 0, &shown)) return Py_BadArgument();
|
||||
CPythonSystem::Instance().SetShopNameStatus(shown != 0);
|
||||
return Py_BuildNone();
|
||||
}
|
||||
PyObject* systemGetShopNameStatus(PyObject*, PyObject*)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetShopNameStatus());
|
||||
}
|
||||
|
||||
PyObject * systemIsAlwaysShowName(PyObject * poSelf, PyObject * poArgs)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName());
|
||||
@@ -440,6 +463,10 @@ void initsystem()
|
||||
{ "IsShowSalesText", systemIsShowSalesText, METH_VARARGS },
|
||||
{ "SetEffectLevel", systemSetEffectLevel, METH_VARARGS }, // PORT: AVA2
|
||||
{ "GetEffectLevel", systemGetEffectLevel, METH_VARARGS },
|
||||
{ "SetShopNamesRange", systemSetShopNamesRange, METH_VARARGS },
|
||||
{ "GetShopNamesRange", systemGetShopNamesRange, METH_VARARGS },
|
||||
{ "SetShopNameStatus", systemSetShopNameStatus, METH_VARARGS },
|
||||
{ "GetShopNameStatus", systemGetShopNameStatus, METH_VARARGS },
|
||||
|
||||
{ "GetShadowLevel", systemGetShadowLevel, METH_VARARGS },
|
||||
{ "SetShadowLevel", systemSetShadowLevel, METH_VARARGS },
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "resource.h"
|
||||
#include "PythonTextTail.h"
|
||||
#include "PythonCharacterManager.h"
|
||||
#include "PythonSystem.h"
|
||||
#include "PythonGuild.h"
|
||||
#include "Locale.h"
|
||||
#include "MarkManager.h"
|
||||
@@ -463,6 +464,11 @@ void CPythonTextTail::ShowCharacterTextTail(DWORD VirtualID)
|
||||
|
||||
if (pInstance->IsGuildWall())
|
||||
return;
|
||||
if (!pInstance->PORT_IsDisplayVisible())
|
||||
return;
|
||||
if (pInstance->IsNPC() && (pInstance->GetRace() < 30000 || pInstance->GetRace() > 30020) &&
|
||||
!CPythonSystem::Instance().GetShopNameStatus())
|
||||
return;
|
||||
|
||||
if (pInstance->CanPickInstance())
|
||||
m_CharacterTextTailList.push_back(pTextTail);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
// Exercise the real runtime and the SDK's real subnet gateway, without a login UI or OS routes.
|
||||
#include "transport.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#define CHECK(x) do{if(!(x)){std::fprintf(stderr,"line %d: %s errno=%d\n",__LINE__,#x,errno);std::abort();}}while(0)
|
||||
using namespace mt::meshport;
|
||||
sockaddr_in endpoint(const char* host,int port){sockaddr_in result{};result.sin_family=AF_INET;result.sin_port=htons(port);CHECK(inet_pton(AF_INET,host,&result.sin_addr)==1);return result;}
|
||||
int tcp(int port){
|
||||
int fd=::socket(AF_INET,SOCK_STREAM,0);CHECK(fd>=0);fcntl(fd,F_SETFL,O_NONBLOCK);
|
||||
CHECK(connect_socket(fd,endpoint("10.253.79.1",port))==-1);CHECK(pending(fd));
|
||||
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(70);int state=0;
|
||||
while(!state&&std::chrono::steady_clock::now()<deadline){state=poll_socket(fd);std::this_thread::sleep_for(std::chrono::milliseconds(1));}
|
||||
CHECK(state==1);fcntl(fd,F_SETFL,0);timeval timeout{3,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));return fd;
|
||||
}
|
||||
void finish(int fd){forget_socket(fd);::close(fd);}
|
||||
void echo(int port,const char* text){
|
||||
int fd=tcp(port);size_t size=std::strlen(text);CHECK(::send(fd,text,size,0)==static_cast<ssize_t>(size));
|
||||
char data[128]{};size_t got=0;while(got<size){auto count=::recv(fd,data+got,sizeof(data)-got,0);CHECK(count>0);got+=count;}
|
||||
CHECK(got==size&&std::memcmp(data,text,size)==0);finish(fd);
|
||||
}
|
||||
int main(int argc,char** argv){
|
||||
CHECK(argc==4);std::ifstream input(argv[1]);CHECK(input.good());std::string config((std::istreambuf_iterator<char>(input)),{});
|
||||
// An invalid profile fails without direct fallback; a later request can retry with a valid profile.
|
||||
configure("invalid saved profile");
|
||||
int failed=::socket(AF_INET,SOCK_STREAM,0);CHECK(failed>=0);fcntl(failed,F_SETFL,O_NONBLOCK);
|
||||
CHECK(connect_socket(failed,endpoint("10.253.79.1",std::atoi(argv[2])))==-1);
|
||||
int failed_state=0;auto failed_deadline=std::chrono::steady_clock::now()+std::chrono::seconds(5);
|
||||
while(!failed_state&&std::chrono::steady_clock::now()<failed_deadline){failed_state=poll_socket(failed);std::this_thread::sleep_for(std::chrono::milliseconds(1));}
|
||||
CHECK(failed_state==-1);finish(failed);take_event();
|
||||
configure(config);int tcp_port=std::atoi(argv[2]),udp_port=std::atoi(argv[3]);
|
||||
int fd=::socket(AF_INET,SOCK_DGRAM,0);CHECK(fd>=0);fcntl(fd,F_SETFL,O_NONBLOCK);
|
||||
auto local=endpoint("127.0.0.1",udp_port);auto remote=endpoint("10.253.79.1",udp_port);
|
||||
CHECK(send_datagram(fd,"LAN",3,0,local)==3);
|
||||
sockaddr_in source{};char data[128]{};ssize_t count=-1;
|
||||
for(int i=0;i<3000&&count<0;++i){count=recv_datagram(fd,data,sizeof(data),0,&source);std::this_thread::sleep_for(std::chrono::milliseconds(1));}
|
||||
CHECK(count==3&&std::memcmp(data,"LAN",3)==0&&source.sin_addr.s_addr==local.sin_addr.s_addr);
|
||||
CHECK(take_event()==0); // Local traffic has not started the runtime.
|
||||
CHECK(send_datagram(fd,"MESH",4,0,remote)==4); // First remote operation is UDP, not login.
|
||||
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(70);
|
||||
while(!datagram_ready(fd)&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
CHECK(datagram_ready(fd));
|
||||
CHECK(recv_datagram(fd,data,2,MSG_PEEK,&source)==2);CHECK(std::memcmp(data,"ME",2)==0);
|
||||
CHECK(source.sin_addr.s_addr==remote.sin_addr.s_addr&&source.sin_port==remote.sin_port);
|
||||
CHECK(recv_datagram(fd,data,sizeof(data),0,&source)==4);CHECK(std::memcmp(data,"MESH",4)==0);
|
||||
CHECK(!datagram_ready(fd));
|
||||
std::thread auth([&]{echo(tcp_port,"account-connection");});
|
||||
std::thread game([&]{echo(tcp_port,"game-map-reconnect-guild-marks");});auth.join();game.join();
|
||||
int http=tcp(tcp_port);const char request[]="POST /register HTTP/1.0\r\nContent-Length: 0\r\n\r\n";
|
||||
CHECK(::send(http,request,sizeof(request)-1,0)>0);count=::recv(http,data,sizeof(data)-1,0);CHECK(count>0);
|
||||
data[count]=0;CHECK(std::strstr(data,"200 OK")&&std::strstr(data,"OK\n"));finish(http);
|
||||
// A new request outside every learned route stays pending; it must not connect directly.
|
||||
int missing=::socket(AF_INET,SOCK_STREAM,0);CHECK(missing>=0);fcntl(missing,F_SETFL,O_NONBLOCK);
|
||||
CHECK(connect_socket(missing,endpoint("10.252.79.1",tcp_port))==-1);CHECK(pending(missing));
|
||||
CHECK(poll_socket(missing)==0);socklen_t len=sizeof(source);CHECK(getpeername(missing,reinterpret_cast<sockaddr*>(&source),&len)<0);
|
||||
finish(missing);finish(fd);shutdown();
|
||||
std::puts("Real SDK: LAN bypass, UDP-first DHCP, UDP source/peek, concurrent TCP, HTTP, reconnect and missing-route cancellation passed");
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Exercise real SDK DHCP against an isolated loopback peer; installs no OS routes."""
|
||||
import ctypes
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
library = Path(sys.argv[1]) if len(sys.argv) > 1 else root / 'build/meshport-runtime/release/libmetin2_meshport.dylib'
|
||||
ffi = ctypes.CDLL(str(library))
|
||||
ffi.meshport_context_new.restype = ctypes.c_uint64
|
||||
ffi.meshport_call.argtypes = [ctypes.c_uint64, ctypes.c_char_p]
|
||||
ffi.meshport_call.restype = ctypes.c_void_p
|
||||
ffi.meshport_string_free.argtypes = [ctypes.c_void_p]
|
||||
ffi.meshport_context_free.argtypes = [ctypes.c_uint64]
|
||||
def call(context, **request):
|
||||
pointer = ffi.meshport_call(context, json.dumps(request).encode())
|
||||
assert pointer, 'missing SDK response'
|
||||
try: response = json.loads(ctypes.string_at(pointer))
|
||||
finally: ffi.meshport_string_free(pointer)
|
||||
assert response['ok'], 'SDK request failed: ' + request['op']
|
||||
return response['data']
|
||||
with socket.socket() as listener:
|
||||
listener.bind(('127.0.0.1', 0))
|
||||
port = listener.getsockname()[1]
|
||||
identity = 'metin2-isolated-test-' + uuid.uuid4().hex
|
||||
base = dict(network_name=identity, network_secret=uuid.uuid4().hex, runtime_mode='application',
|
||||
stun_servers=[], stun_servers_v6=[], listeners=[], enable_ipv6=False)
|
||||
contexts = [ffi.meshport_context_new(), ffi.meshport_context_new()]
|
||||
try:
|
||||
info = call(contexts[0], op='abi_info')
|
||||
assert info['abi'] == 1 and info['revision'] >= 2
|
||||
server = dict(base, hostname='dhcp-seed', ipv4='10.253.85.1/24', dhcp=False,
|
||||
listeners=['tcp://127.0.0.1:%d' % port])
|
||||
client = dict(base, hostname='dhcp-client', ipv4='', dhcp=True,
|
||||
peers=['tcp://127.0.0.1:%d' % port])
|
||||
for context, profile in zip(contexts, (server, client)):
|
||||
config = call(context, op='build_config', profile=profile)['toml']
|
||||
call(context, op='start_bridged', toml=config)
|
||||
deadline = time.monotonic() + 40
|
||||
while time.monotonic() < deadline:
|
||||
data = call(contexts[1], op='status')
|
||||
overlay = data.get('platform_network', {}).get('overlay') or {}
|
||||
address = overlay.get('address')
|
||||
if address and address != '0.0.0.0' and data.get('health', {}).get('mesh_routable'):
|
||||
assert address.startswith('10.253.85.') and address != '10.253.85.1'
|
||||
assert data.get('nodes'), 'DHCP node must have joined seed network'
|
||||
print('Real SDK DHCP passed: assigned %s/%s; application bridge healthy' % (address, overlay['prefix']))
|
||||
break
|
||||
time.sleep(.25)
|
||||
else: raise AssertionError('DHCP did not assign an address before deadline')
|
||||
finally:
|
||||
for context in reversed(contexts): ffi.meshport_context_free(context)
|
||||
print('SDK contexts and loopback listeners stopped')
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Actual notice script observes native routing; it must never intercept login credentials."""
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
SOURCE=(Path(__file__).resolve().parents[2]/'src/platform/ScriptLib/MeshPortScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
class Widget:
|
||||
def __init__(self):self.shown=False;self.text=''
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def SetText(self,text):self.text=text
|
||||
def __getattr__(self,name):return lambda *args:None
|
||||
class Tests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.now=0;self.events=[]
|
||||
modules={n:types.ModuleType(n) for n in ['app','ui','wndMgr','player','_mt_meshport','introLogin','net']}
|
||||
modules['app'].GetTime=lambda:self.now
|
||||
modules['ui'].Window=modules['ui'].TextLine=Widget
|
||||
modules['wndMgr'].GetScreenWidth=lambda:1280
|
||||
modules['player'].AutoHuntLocalize=lambda value:value
|
||||
self.cancelled=False
|
||||
modules['net'].CancelPendingLogin=lambda:self.cancelled
|
||||
self.login=type('Login',(),{'SetPasswordEditLineFocus':lambda s:None,'OnPressExitKey':lambda s:None,'Close':lambda s:None})
|
||||
modules['introLogin'].LoginWindow=self.login
|
||||
modules['_mt_meshport'].event=lambda:self.events.pop(0) if self.events else 0
|
||||
self.old={n:sys.modules.get(n) for n in modules};sys.modules.update(modules)
|
||||
self.scope={};exec(compile(SOURCE,'MeshPortScript.inc','exec'),self.scope)
|
||||
self.notice=self.scope['notice']
|
||||
def tearDown(self):
|
||||
for name,value in self.old.items():
|
||||
if value is None:sys.modules.pop(name,None)
|
||||
else:sys.modules[name]=value
|
||||
def test_local_requests_do_not_show_a_mesh_notice(self):
|
||||
self.notice.OnUpdate();self.assertFalse(self.notice.label.shown)
|
||||
def test_prepare_is_not_reported_as_success(self):
|
||||
self.events=[1];self.notice.OnUpdate()
|
||||
self.assertIn('等待动态分配',self.notice.label.text)
|
||||
self.assertNotEqual(self.notice.label.text,'组网成功')
|
||||
def test_success_expires_after_six_seconds(self):
|
||||
self.events=[2];self.notice.OnUpdate();self.assertEqual(self.notice.label.text,'组网成功')
|
||||
self.now=7;self.notice.OnUpdate();self.assertFalse(self.notice.label.shown)
|
||||
def test_failure_and_recovery(self):
|
||||
self.events=[3,1,2]
|
||||
self.notice.OnUpdate();self.assertIn('失败',self.notice.label.text)
|
||||
self.notice.OnUpdate();self.notice.OnUpdate();self.assertEqual(self.notice.label.text,'组网成功')
|
||||
def test_no_login_hooks_or_password_capture(self):
|
||||
self.assertNotIn('LoginWindow.Connect =',SOURCE);self.assertNotIn('password',SOURCE)
|
||||
def test_cancel_login_hides_only_its_pending_notice(self):
|
||||
self.events=[1];self.notice.OnUpdate();self.cancelled=True
|
||||
self.login().SetPasswordEditLineFocus()
|
||||
self.assertFalse(self.notice.label.shown)
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Run the native integration executable against an isolated, real SDK gateway."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
def check_client(root, temporary, profile, info):
|
||||
result_path=Path(temporary)/'client-registration-result.txt'
|
||||
source=r"""import ui, app, net
|
||||
# Cancelling a pending login must not cancel the independent channel query or registration.
|
||||
net.ConnectTCP('10.252.79.1', %d)
|
||||
assert net.CancelPendingLogin()
|
||||
assert not net.CancelPendingLogin()
|
||||
class RegistrationProbe(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self)
|
||||
self.phase = 0
|
||||
self.trace = %r
|
||||
open(self.trace, 'w').write('started\n')
|
||||
self.started = app.GetTime()
|
||||
net.RegisterAccount('10.252.79.1', %d, 'isolatedtest', 'unused', '1234567')
|
||||
self.Show()
|
||||
def OnUpdate(self):
|
||||
if self.phase == 0 and app.GetTime() - self.started > .25:
|
||||
net.CancelRegisterAccount()
|
||||
self.phase = 1
|
||||
open(self.trace, 'a').write('cancel requested\n')
|
||||
result = net.GetRegisterAccountResult()
|
||||
if self.phase == 1 and result:
|
||||
open(self.trace, 'a').write('cancel result: ' + result + '\n')
|
||||
assert result == 'ERR CANCELLED', result
|
||||
net.RegisterAccount('10.253.79.1', %d, 'isolatedtest', 'unused', '1234567')
|
||||
self.phase = 2
|
||||
open(self.trace, 'a').write('remote registration started\n')
|
||||
elif self.phase == 2 and result:
|
||||
open(%r, 'w').write(result)
|
||||
self.Hide()
|
||||
_registration_probe = RegistrationProbe()
|
||||
"""%(info['tcp_port'],str(result_path)+'.trace',info['tcp_port'],info['tcp_port'],str(result_path))
|
||||
args=[str(root/'build/release/src/host/mt_native_render'),'--login-screen',
|
||||
'--live-client',str(root/'build/zh-locale/Client'),
|
||||
'--live-server','10.253.79.1:%d:%d'%(info['tcp_port'],info['tcp_port']),
|
||||
'--frames','600','--py-exec',source]
|
||||
with open(root/'build/meshport-registration-runtime.log','w') as output:
|
||||
result=subprocess.run(args,env=dict(os.environ,MT_MESHPORT_CONFIG=str(profile),MT_MESHPORT_TRACE='1'),
|
||||
stdout=output,stderr=subprocess.STDOUT,timeout=45)
|
||||
assert result.returncode==0, 'native client launch failed'
|
||||
if not result_path.exists() or result_path.read_text()!='OK':
|
||||
trace=Path(str(result_path)+'.trace')
|
||||
print('Client registration trace:',trace.read_text() if trace.exists() else 'no updates')
|
||||
print('Client registration result:',result_path.read_text() if result_path.exists() else 'no result')
|
||||
raise AssertionError('original HTTP registration/cancellation path failed')
|
||||
print('Native Python 2.7 client: pre-login channel routing, actual HTTP registration and cancellation passed')
|
||||
|
||||
def main():
|
||||
root=Path(__file__).resolve().parents[2]
|
||||
fixture=root/'build/meshport-runtime/release/examples/gateway_fixture'
|
||||
binary=Path(sys.argv[1]) if len(sys.argv)>1 else root/'build/native/src/meshport/meshport_network_paths_test'
|
||||
with tempfile.TemporaryDirectory(prefix='metin2-mesh-') as temporary:
|
||||
log=open(Path(temporary)/'gateway.log','w+')
|
||||
gateway=subprocess.Popen([str(fixture)],stdout=subprocess.PIPE,stderr=log,text=True)
|
||||
try:
|
||||
import selectors
|
||||
selector=selectors.DefaultSelector();selector.register(gateway.stdout,selectors.EVENT_READ)
|
||||
if not selector.select(20):raise RuntimeError('gateway startup timed out')
|
||||
info=json.loads(gateway.stdout.readline())
|
||||
config=Path(temporary)/'profile.toml'
|
||||
config.write_text("dhcp=true\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='tcp://127.0.0.1:%d'\n[network_identity]\nnetwork_name='%s'\nnetwork_secret='isolated-test-only'\n[flags]\nno_tun=true\nuse_smoltcp=true\nenable_encryption=true\n"%(info['mesh_port'],info['network_name']))
|
||||
result=subprocess.run([str(binary),str(config),str(info['tcp_port']),str(info['udp_port'])],timeout=100,env=dict(os.environ,MT_MESHPORT_TRACE="1"))
|
||||
if result.returncode:raise RuntimeError('native network paths failed (%s)'%result.returncode)
|
||||
if '--client' in sys.argv:check_client(root,temporary,config,info)
|
||||
finally:
|
||||
gateway.terminate()
|
||||
try:gateway.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:gateway.kill();gateway.wait()
|
||||
log.close()
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,103 @@
|
||||
#include "transport.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #x); std::abort(); } } while (0)
|
||||
using namespace mt::meshport;
|
||||
uint32_t ip(const char* text) { in_addr addr{}; CHECK(inet_pton(AF_INET,text,&addr)==1); return addr.s_addr; }
|
||||
void transfer(int fd, void* p, size_t size, bool send) {
|
||||
auto* bytes = static_cast<unsigned char*>(p);
|
||||
for (size_t offset=0; offset<size;) {
|
||||
auto count = send ? ::send(fd,bytes+offset,1,0) : ::recv(fd,bytes+offset,size-offset,0);
|
||||
CHECK(count>0); offset += count;
|
||||
}
|
||||
}
|
||||
void socks(bool reject) {
|
||||
int listener=::socket(AF_INET,SOCK_STREAM,0); CHECK(listener>=0);
|
||||
sockaddr_in local{};local.sin_family=AF_INET;local.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
CHECK(::bind(listener,reinterpret_cast<sockaddr*>(&local),sizeof(local))==0);
|
||||
CHECK(::listen(listener,1)==0);socklen_t len=sizeof(local);
|
||||
CHECK(getsockname(listener,reinterpret_cast<sockaddr*>(&local),&len)==0);
|
||||
std::thread peer([&] {
|
||||
int fd=::accept(listener,nullptr,nullptr);CHECK(fd>=0);
|
||||
timeval timeout{3,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
|
||||
unsigned char greeting[3];transfer(fd,greeting,3,false);CHECK(greeting[0]==5 && greeting[1]==1 && greeting[2]==0);
|
||||
unsigned char auth[2]={5,0};transfer(fd,auth,2,true);
|
||||
unsigned char request[10];transfer(fd,request,10,false);
|
||||
CHECK(request[0]==5 && request[1]==1 && request[3]==1);
|
||||
CHECK(std::memcmp(request+4,"\x0a\xfd\x55\x02",4)==0);
|
||||
CHECK(request[8]==0x32 && request[9]==0xc8); // port 13000
|
||||
unsigned char response[10]={5,static_cast<unsigned char>(reject?5:0),0,1,0,0,0,0,0,0};
|
||||
transfer(fd,response,10,true);
|
||||
if (!reject) { char payload[4]={'g','a','m','e'};transfer(fd,payload,4,true); }
|
||||
::close(fd);
|
||||
});
|
||||
set_routes("127.0.0.1:"+std::to_string(ntohs(local.sin_port)),{"10.253.85.0/24"});
|
||||
int fd=::socket(AF_INET,SOCK_STREAM,0);CHECK(fd>=0);fcntl(fd,F_SETFL,O_NONBLOCK);
|
||||
sockaddr_in target{};target.sin_family=AF_INET;target.sin_addr.s_addr=ip("10.253.85.2");target.sin_port=htons(13000);
|
||||
int owner;CHECK(connect_socket(fd,target,&owner)==-1);CHECK(pending(fd));CHECK(pending_owner(&owner));
|
||||
int result=0;
|
||||
const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(3);
|
||||
while (!result && std::chrono::steady_clock::now()<deadline) {result=poll_socket(fd);std::this_thread::sleep_for(std::chrono::milliseconds(1));}
|
||||
CHECK(result==(reject?-1:1));
|
||||
if (!reject) { fcntl(fd,F_SETFL,0); char payload[4];transfer(fd,payload,4,false);CHECK(std::memcmp(payload,"game",4)==0); }
|
||||
forget_socket(fd);CHECK(!pending(fd));CHECK(!pending_owner(&owner));::close(fd);peer.join();::close(listener);set_routes("",{});
|
||||
}
|
||||
void udp_socks() {
|
||||
int listener=::socket(AF_INET,SOCK_STREAM,0);CHECK(listener>=0);
|
||||
auto local=sockaddr_in{};local.sin_family=AF_INET;local.sin_addr.s_addr=htonl(INADDR_LOOPBACK);
|
||||
CHECK(::bind(listener,reinterpret_cast<sockaddr*>(&local),sizeof(local))==0);CHECK(::listen(listener,1)==0);
|
||||
socklen_t len=sizeof(local);CHECK(getsockname(listener,reinterpret_cast<sockaddr*>(&local),&len)==0);
|
||||
int relay=::socket(AF_INET,SOCK_DGRAM,0);CHECK(relay>=0);auto relay_address=local;relay_address.sin_port=0;
|
||||
CHECK(::bind(relay,reinterpret_cast<sockaddr*>(&relay_address),sizeof(relay_address))==0);
|
||||
len=sizeof(relay_address);CHECK(getsockname(relay,reinterpret_cast<sockaddr*>(&relay_address),&len)==0);
|
||||
std::thread peer([&]{
|
||||
int control=::accept(listener,nullptr,nullptr);CHECK(control>=0);timeval timeout{4,0};
|
||||
setsockopt(control,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));setsockopt(relay,SOL_SOCKET,SO_RCVTIMEO,&timeout,sizeof(timeout));
|
||||
unsigned char greeting[3];transfer(control,greeting,3,false);unsigned char auth[2]={5,0};transfer(control,auth,2,true);
|
||||
unsigned char request[10];transfer(control,request,10,false);CHECK(request[1]==3);
|
||||
unsigned char response[10]={5,0,0,1,127,0,0,1,0,0};std::memcpy(response+8,&relay_address.sin_port,2);transfer(control,response,10,true);
|
||||
unsigned char frame[128];sockaddr_in source{};socklen_t size=sizeof(source);
|
||||
auto count=::recvfrom(relay,frame,sizeof(frame),0,reinterpret_cast<sockaddr*>(&source),&size);
|
||||
CHECK(count==14);CHECK(std::memcmp(frame+10,"ping",4)==0);
|
||||
CHECK(::sendto(relay,frame,count,0,reinterpret_cast<sockaddr*>(&source),size)==count);
|
||||
char close_byte;::recv(control,&close_byte,1,0);::close(control);
|
||||
});
|
||||
set_routes("127.0.0.1:"+std::to_string(ntohs(local.sin_port)),{"10.253.85.0/24"});
|
||||
int fd=::socket(AF_INET,SOCK_DGRAM,0);CHECK(fd>=0);fcntl(fd,F_SETFL,O_NONBLOCK);
|
||||
auto target=sockaddr_in{};target.sin_family=AF_INET;target.sin_addr.s_addr=ip("10.253.85.2");target.sin_port=htons(13000);
|
||||
CHECK(send_datagram(fd,"ping",4,0,target)==4);
|
||||
const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(4);
|
||||
while(!datagram_ready(fd)&&std::chrono::steady_clock::now()<deadline)std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
CHECK(datagram_ready(fd));sockaddr_in source{};char payload[4];
|
||||
CHECK(recv_datagram(fd,payload,2,MSG_PEEK,&source)==2);CHECK(source.sin_addr.s_addr==target.sin_addr.s_addr&&source.sin_port==target.sin_port);
|
||||
CHECK(recv_datagram(fd,payload,4,0,&source)==4);CHECK(std::memcmp(payload,"ping",4)==0);
|
||||
forget_socket(fd);::close(fd);peer.join();::close(listener);::close(relay);set_routes("",{});
|
||||
}
|
||||
int main() {
|
||||
CHECK(in_subnet(ip("192.168.21.203"),ip("192.168.21.5"),ip("255.255.255.0")));
|
||||
CHECK(!in_subnet(ip("192.168.20.203"),ip("192.168.21.5"),ip("255.255.255.0")));
|
||||
CHECK(in_subnet(ip("192.168.20.203"),ip("192.168.21.5"),ip("255.255.254.0")));
|
||||
CHECK(!in_subnet(ip("192.168.21.203"),ip("192.168.21.5"),0));
|
||||
CHECK(same_subnet("127.0.0.1"));CHECK(!same_subnet("invalid"));
|
||||
CHECK(contains("10.253.85.0/24","10.253.85.2"));CHECK(!contains("10.253.85.0/24","10.253.86.2"));
|
||||
CHECK(contains("10.253.85.2/32","10.253.85.2"));CHECK(!contains("10.0.0.0/0","10.1.2.3"));
|
||||
CHECK(!contains("10.0.0.0/99999999","10.1.2.3"));
|
||||
socks(false);socks(true);udp_socks();
|
||||
configure("invalid saved profile");
|
||||
int failed=::socket(AF_INET,SOCK_STREAM,0);CHECK(failed>=0);fcntl(failed,F_SETFL,O_NONBLOCK);
|
||||
sockaddr_in absent{};absent.sin_family=AF_INET;absent.sin_addr.s_addr=ip("10.253.85.2");absent.sin_port=htons(13000);
|
||||
CHECK(connect_socket(failed,absent)==-1);
|
||||
int state=0;auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(5);
|
||||
while(!state&&std::chrono::steady_clock::now()<deadline){state=poll_socket(failed);std::this_thread::sleep_for(std::chrono::milliseconds(1));}
|
||||
CHECK(state==-1);socklen_t length=sizeof(absent);CHECK(getpeername(failed,reinterpret_cast<sockaddr*>(&absent),&length)<0);
|
||||
forget_socket(failed);::close(failed);
|
||||
shutdown();std::puts("MeshPort subnet, TCP/UDP SOCKS, peek/source preservation and failure without direct fallback passed");
|
||||
}
|
||||
@@ -45,7 +45,7 @@ INFO=['MTBP1 season 202610 1790805600 1793487600 1790900000 6',
|
||||
class BattlePassTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.chat=[];self.sent=[];self.clock=100.
|
||||
names=('app','chat','game','grp','item','net','nonplayer','ui','mt_biolog')
|
||||
names=('app','chat','game','grp','item','net','nonplayer','ui','player','mt_biolog')
|
||||
mods={n:types.ModuleType(n) for n in names}
|
||||
app=mods['app'];app.GetTime=lambda:self.clock;app.DIK_F6=64
|
||||
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
|
||||
@@ -54,6 +54,9 @@ class BattlePassTests(unittest.TestCase):
|
||||
self.selected=0
|
||||
def select(v):self.selected=v
|
||||
mods['item'].SelectItem=select;mods['item'].GetItemName=lambda:NAMES.get(self.selected,'')
|
||||
mods['player'].GetItemIndex=lambda cell:25159 if cell==3 else 0
|
||||
mods['player'].INVENTORY_PAGE_SIZE=45;mods['player'].INVENTORY_PAGE_COUNT=5
|
||||
mods['item'].GetValue=lambda i:10
|
||||
mods['net'].SendChatPacket=self.sent.append
|
||||
mods['nonplayer'].GetMonsterName=lambda v:{691:'狼王'}.get(v,'')
|
||||
mods['ui'].Window=Widget
|
||||
@@ -146,6 +149,24 @@ class BattlePassTests(unittest.TestCase):
|
||||
self.assertEqual(self.ns['Grouped'](50000000),'50,000,000');self.assertEqual(self.ns['Amount'](4,45,90),'0.8')
|
||||
self.assertEqual(self.ns['Unit'](4,90),' 分钟');self.assertEqual(self.ns['Amount'](4,7200,172800),'2');self.assertEqual(self.ns['SeasonName'](7),'第 7 期')
|
||||
|
||||
def test_ticket_access_and_activation(self):
|
||||
self.open()
|
||||
self.feed(INFO[0],'MTBP1 access 0 10',*INFO[1:])
|
||||
self.assertEqual((self.p.access,self.p.month),(0,10))
|
||||
self.assertFalse(self.p.Claim(2))
|
||||
self.assertTrue(self.w.activateButton.IsShow())
|
||||
self.clock+=1
|
||||
self.assertFalse(self.p.Activate(4,25159))
|
||||
self.assertFalse(self.p.Activate(3,93110))
|
||||
self.assertTrue(self.p.Activate(3,25159))
|
||||
self.assertEqual(self.sent[-1],'/mt_bp 1 activate 3 25159')
|
||||
self.assertFalse(self.p.Activate(3,25159))
|
||||
self.feed(INFO[0],'MTBP1 access 1 10',*INFO[1:])
|
||||
self.assertFalse(self.w.activateButton.IsShow())
|
||||
self.clock+=1;self.assertTrue(self.p.Claim(2))
|
||||
self.feed(INFO[0],'MTBP1 access 2 10',*INFO[1:])
|
||||
self.clock+=1;self.assertFalse(self.p.Claim(2))
|
||||
|
||||
def test_registered(self):
|
||||
boot=(ROOT/'src/platform/ScriptLib/PythonBoot.cpp').read_text()
|
||||
self.assertIn('#include "BattlePassScript.inc"',boot)
|
||||
|
||||
@@ -37,6 +37,8 @@ class DisplayTests(unittest.TestCase):
|
||||
mods={n:types.ModuleType(n) for n in ('background','game','grp','systemSetting','ui','mt_biolog','mt_wiki')}
|
||||
bg=mods['background'];bg.PART_TREE=3;bg.PART_CLOUD=2;bg.SetVisiblePart=lambda part,on:self.state['parts'].__setitem__(part,on)
|
||||
ss=mods['systemSetting'];ss.SetEffectLevel=lambda v:self.state.__setitem__('effect',v)
|
||||
ss.SetShopNamesRange=lambda v:self.state.__setitem__('shopRange',v)
|
||||
ss.SetShopNameStatus=lambda v:self.state.__setitem__('npcNames',v)
|
||||
ss.IsAlwaysShowName=lambda:self.state['name'];ss.SetAlwaysShowNameFlag=lambda v:self.state.__setitem__('name',bool(v))
|
||||
ss.IsShowDamage=lambda:self.state['damage'];ss.SetShowDamageFlag=lambda v:self.state.__setitem__('damage',bool(v))
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:self.opened.append(1),Close=lambda s:None))
|
||||
@@ -58,9 +60,9 @@ class DisplayTests(unittest.TestCase):
|
||||
|
||||
def test_defaults_and_config(self):
|
||||
ns=self.load();self.assertEqual(self.state['effect'],0)
|
||||
o=ns['Options']();self.assertEqual(o.Dump(),'0 1 1')
|
||||
o=ns['Options']();self.assertEqual(o.Dump(),'0 1 1 0 1')
|
||||
for bad in ('5 1 1','1 2 1','a 1 1','1 1','10 1 1','-1 1 1'):
|
||||
o=ns['Options']();o.Load(bad);self.assertEqual(o.Dump(),'0 1 1')
|
||||
o=ns['Options']();o.Load(bad);self.assertEqual(o.Dump(),'0 1 1 0 1')
|
||||
Path('mt_display.cfg').write_text('3 0 1')
|
||||
self.load();self.assertEqual(self.state['effect'],3) # applied at boot, before any map
|
||||
|
||||
@@ -74,7 +76,9 @@ class DisplayTests(unittest.TestCase):
|
||||
self.assertNotIn('【',w.treeButton.text);self.assertIn('【',w.cloudButton.text)
|
||||
w.levelButtons[4].event();self.assertEqual(self.state['effect'],4)
|
||||
w.ToggleTree();w.ToggleCloud();self.assertEqual(self.state['parts'],{3:1,2:0})
|
||||
self.assertEqual(Path('mt_display.cfg').read_text(),'4 1 0')
|
||||
self.assertEqual(Path('mt_display.cfg').read_text(),'4 1 0 0 1')
|
||||
w.NextRange();w.ToggleNPC();self.assertEqual((self.state['shopRange'],self.state['npcNames']),(1,False))
|
||||
self.assertEqual(Path('mt_display.cfg').read_text(),'4 1 0 1 0')
|
||||
w.ToggleName();w.ToggleDamage();self.assertEqual((self.state['name'],self.state['damage']),(False,False))
|
||||
self.assertNotIn('【',w.nameButton.text)
|
||||
game.GameWindow.Close(gw);self.assertIsNone(ns['g_window']);self.assertIsNone(ns['g_entry'])
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class Widget:
|
||||
def __init__(self,*args):self.shown=False;self.page=0;self.inventoryPageIndex=0;self.size=(360,400)
|
||||
def __getattr__(self,name):return lambda *args:None
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def IsShow(self):return self.shown
|
||||
def GetGlobalPosition(self):return (10,20)
|
||||
def GetHeight(self):return self.size[1]
|
||||
def GetWidth(self):return self.size[0]
|
||||
def SetSize(self,w,h):self.size=w,h
|
||||
|
||||
|
||||
class Action(Widget):
|
||||
def __init__(self,parent,x,y,width,label,event):super().__init__();self.label=label;self.event=event
|
||||
|
||||
|
||||
class ItemActionsTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
names=('game','grp','player','ui','wndMgr','mt_biolog','mt_preview','mt_chest','mt_wiki','uiInventory','mt_battlepass','mt_switchbot')
|
||||
mods={name:types.ModuleType(name) for name in names};self.mods=mods;self.actions=[];self.bag={3:(50011,2),4:(19,1)}
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None))
|
||||
mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(UseItemSlot=lambda owner,cell:self.actions.append(('use',cell)),_InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda owner,cell:cell))
|
||||
mods['mt_battlepass'].g_window=types.SimpleNamespace(OfferTicket=lambda c,v:self.actions.append(('ticket',c,v)))
|
||||
mods['mt_switchbot'].g_window=types.SimpleNamespace(Open=lambda:self.actions.append(('lock',)))
|
||||
mods['ui'].Window=Widget;mods['mt_biolog'].Action=Action
|
||||
mods['player'].GetItemIndex=lambda cell:self.bag.get(cell,(0,0))[0]
|
||||
mods['player'].GetItemCount=lambda cell:self.bag.get(cell,(0,0))[1]
|
||||
mods['wndMgr'].GetScreenWidth=lambda:1280;mods['wndMgr'].GetScreenHeight=lambda:720
|
||||
mods['mt_preview'].ItemSpec=lambda v:v==19
|
||||
mods['mt_preview'].Preview=lambda kind,v:self.actions.append(('preview',v))
|
||||
mods['mt_chest'].Batchable=lambda v:v==50011
|
||||
mods['mt_chest'].g_window=types.SimpleNamespace(Select=lambda c,v:self.actions.append(('chest',c,v)))
|
||||
mods['mt_wiki'].OpenItem=lambda v:self.actions.append(('wiki',v))
|
||||
self.previous={n:sys.modules.get(n) for n in mods};sys.modules.update(mods)
|
||||
text=(ROOT/'src/platform/ScriptLib/ItemActionsScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
self.ns={'__name__':'mt_item_actions'};exec(text,self.ns)
|
||||
self.game=mods['game'].GameWindow();self.game.Open();self.window=self.ns['g_window'];self.owner=Widget();self.owner.Show()
|
||||
|
||||
def tearDown(self):
|
||||
self.game.Close()
|
||||
for n,value in self.previous.items():
|
||||
if value is None:sys.modules.pop(n,None)
|
||||
else:sys.modules[n]=value
|
||||
|
||||
def test_chest_and_preview_actions(self):
|
||||
self.ns['ShowInventory'](self.owner,3)
|
||||
self.assertEqual([b.label for b in self.window.buttons],['百科','批量开箱','关闭'])
|
||||
self.window.buttons[1].event();self.assertEqual(self.actions,[('chest',3,50011)])
|
||||
self.ns['ShowInventory'](self.owner,4)
|
||||
self.window.buttons[1].event();self.assertEqual(self.actions[-1],('preview',19))
|
||||
|
||||
def test_ticket_lock_and_original_use(self):
|
||||
inventory=self.mods['uiInventory'].InventoryWindow()
|
||||
for vnum in (25159,50348,50349,27001):
|
||||
self.bag[5]=(vnum,1);inventory.UseItemSlot(5)
|
||||
self.assertEqual(self.actions,[('ticket',5,25159),('lock',),('lock',),('use',5)])
|
||||
|
||||
def test_stale_actions_never_fire(self):
|
||||
for change in ('page','vnum','count','closed'):
|
||||
self.owner.Show();self.owner.inventoryPageIndex=0;self.bag[3]=(50011,2)
|
||||
self.ns['ShowInventory'](self.owner,3);button=self.window.buttons[1]
|
||||
if change=='page':self.owner.inventoryPageIndex=1
|
||||
elif change=='vnum':self.bag[3]=(19,2)
|
||||
elif change=='count':self.bag[3]=(50011,1)
|
||||
else:self.owner.Hide()
|
||||
button.event();self.assertEqual(self.actions,[]);self.assertFalse(self.window.IsShow())
|
||||
self.owner.Show();self.ns['ShowInventory'](self.owner,3);self.owner.Hide();self.window.OnUpdate()
|
||||
self.assertFalse(self.window.IsShow())
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
+5148
File diff suppressed because it is too large
Load Diff
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/*", "tools/meshport-test-server", "tools/meshport-vpn-helper"]
|
||||
exclude = ["vendor/easytier"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
toml = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time"] }
|
||||
easytier = { path = "vendor/easytier/easytier", default-features = false, features = ["aes-gcm", "ffi-dataplane", "proxy-cidr-monitor", "dhcp-ipv4", "tcp-hole-punch"] }
|
||||
easytier-core = { path = "vendor/easytier/easytier-core", default-features = false, features = ["proxy-smoltcp-stack"] }
|
||||
meshport = { path = "crates/meshport" }
|
||||
meshport-easytier = { path = "crates/meshport-easytier" }
|
||||
meshport-netstack = { path = "crates/meshport-netstack" }
|
||||
meshport-socks = { path = "crates/meshport-socks" }
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
# MeshPort SDK snapshot
|
||||
|
||||
Source: MeshPort commit `b656c1896a1079f3284b999ecd7a3d650c23ac2a`.
|
||||
Includes the Rust SDK, C ABI, SOCKS bridge and vendored EasyTier source.
|
||||
Flutter UI, proxy engines, private profiles and compiled artifacts are excluded.
|
||||
Build with Rust 1.95+ and protoc; Cargo.lock pins registry dependencies.
|
||||
Upstream EasyTier license: `vendor/easytier/LICENSE`.
|
||||
|
||||
Local integration fix: `crates/meshport-easytier/src/lib.rs` refreshes the remote-subnet filter from the live DHCP address; the upstream filter captured only the initial static IP. Real DHCP plus subnet TCP/UDP coverage is in `tests/meshport/test_network_paths.py`.
|
||||
@@ -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", "easytier/dns-resolver"]
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
|
||||
+62
@@ -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,197 @@
|
||||
//! Structured profile <-> TOML. Hosts edit a JSON draft; the SDK owns the
|
||||
//! mode invariants and the exact configuration text it will accept.
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde_json::Value;
|
||||
|
||||
/// Keys removed from saved configurations by earlier releases.
|
||||
const LEGACY_KEYS: [&str; 1] = ["subnet_routes"];
|
||||
|
||||
/// Builds a validated configuration from a form draft. Any `runtime_mode` other
|
||||
/// than `system_vpn` (including a host's unified VPN) runs the mesh in
|
||||
/// application mode; transport and encryption invariants are not host choices.
|
||||
pub fn build_config(profile: &Value) -> Result<String> {
|
||||
let profile = profile.as_object().context("profile must be an object")?;
|
||||
let text = |key: &str, default: &str| -> Result<Value> {
|
||||
match profile.get(key) {
|
||||
None | Some(Value::Null) => Ok(Value::from(default)),
|
||||
Some(value @ Value::String(_)) => Ok(value.clone()),
|
||||
Some(_) => bail!("{key} must be a string"),
|
||||
}
|
||||
};
|
||||
let system = profile.get("runtime_mode").and_then(Value::as_str) == Some("system_vpn");
|
||||
let mut optimization = match profile.get("optimization") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(map)) => map.clone(),
|
||||
Some(_) => bail!("optimization must be an object"),
|
||||
};
|
||||
optimization
|
||||
.entry("mode")
|
||||
.or_insert_with(|| Value::from("adaptive"));
|
||||
let latency_first = matches!(
|
||||
optimization.get("mode").and_then(Value::as_str),
|
||||
Some("adaptive" | "latency")
|
||||
);
|
||||
let mut flags = match profile.get("flags") {
|
||||
None | Some(Value::Null) => serde_json::Map::new(),
|
||||
Some(Value::Object(map)) => map.clone(),
|
||||
Some(_) => bail!("flags must be an object"),
|
||||
};
|
||||
flags.insert("no_tun".into(), Value::from(!system));
|
||||
flags.insert("use_smoltcp".into(), Value::from(!system));
|
||||
flags.insert("enable_encryption".into(), Value::from(true));
|
||||
flags.insert(
|
||||
"enable_ipv6".into(),
|
||||
profile
|
||||
.get("enable_ipv6")
|
||||
.filter(|v| !v.is_null())
|
||||
.cloned()
|
||||
.unwrap_or(Value::from(true)),
|
||||
);
|
||||
flags.insert("latency_first".into(), Value::from(latency_first));
|
||||
|
||||
let mut root = serde_json::Map::new();
|
||||
root.insert("hostname".into(), text("hostname", "MeshPort")?);
|
||||
if profile.get("dhcp").and_then(Value::as_bool) == Some(true) {
|
||||
root.insert("dhcp".into(), Value::from(true));
|
||||
} else {
|
||||
root.insert("ipv4".into(), text("ipv4", "")?);
|
||||
}
|
||||
root.insert(
|
||||
"listeners".into(),
|
||||
profile
|
||||
.get("listeners")
|
||||
.filter(|v| !v.is_null())
|
||||
.cloned()
|
||||
.unwrap_or(Value::Array(vec![])),
|
||||
);
|
||||
for key in ["stun_servers", "stun_servers_v6"] {
|
||||
if let Some(value) = profile.get(key).filter(|v| !v.is_null()) {
|
||||
root.insert(key.into(), value.clone());
|
||||
}
|
||||
}
|
||||
let peers = match profile.get("peers") {
|
||||
None | Some(Value::Null) => vec![],
|
||||
Some(Value::Array(peers)) => peers
|
||||
.iter()
|
||||
.map(|uri| serde_json::json!({"uri": uri}))
|
||||
.collect(),
|
||||
Some(_) => bail!("peers must be an array"),
|
||||
};
|
||||
if !peers.is_empty() {
|
||||
root.insert("peer".into(), Value::Array(peers));
|
||||
}
|
||||
root.insert(
|
||||
"network_identity".into(),
|
||||
serde_json::json!({
|
||||
"network_name": text("network_name", "")?,
|
||||
"network_secret": text("network_secret", "")?,
|
||||
}),
|
||||
);
|
||||
root.insert("flags".into(), Value::Object(drop_nulls(flags)));
|
||||
root.insert(
|
||||
"runtime".into(),
|
||||
serde_json::json!({"mode": if system { "system_vpn" } else { "application" }}),
|
||||
);
|
||||
root.insert(
|
||||
"optimization".into(),
|
||||
Value::Object(drop_nulls(optimization)),
|
||||
);
|
||||
let value = toml::Value::try_from(Value::Object(root))
|
||||
.map_err(|_| anyhow::anyhow!("profile contains values TOML cannot represent"))?;
|
||||
let output =
|
||||
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
|
||||
super::parse_config(&output)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn drop_nulls(map: serde_json::Map<String, Value>) -> serde_json::Map<String, Value> {
|
||||
map.into_iter().filter(|(_, v)| !v.is_null()).collect()
|
||||
}
|
||||
|
||||
/// Removes options earlier releases saved but this SDK no longer accepts.
|
||||
/// Returns the input unchanged (formatting preserved) when nothing is removed.
|
||||
pub fn migrate_config(input: &str) -> Result<(String, bool)> {
|
||||
let mut value: toml::Value =
|
||||
toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?;
|
||||
let table = value
|
||||
.as_table_mut()
|
||||
.context("configuration must be a TOML table")?;
|
||||
let mut changed = false;
|
||||
for key in LEGACY_KEYS {
|
||||
changed |= table.remove(key).is_some();
|
||||
if let Some(runtime) = table.get_mut("runtime").and_then(|v| v.as_table_mut()) {
|
||||
changed |= runtime.remove(key).is_some();
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return Ok((input.to_owned(), false));
|
||||
}
|
||||
let output =
|
||||
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
|
||||
Ok((output, true))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ConfigLoader;
|
||||
use serde_json::json;
|
||||
|
||||
fn draft() -> Value {
|
||||
json!({
|
||||
"runtime_mode": "unified_vpn",
|
||||
"ipv4": "10.77.0.11/24",
|
||||
"network_name": "test",
|
||||
"network_secret": "test-only",
|
||||
"flags": {"disable_p2p": true, "foreign_relay_bps_limit": "18446744073709551615", "no_tun": false},
|
||||
"listeners": ["udp://0.0.0.0:11010"],
|
||||
"stun_servers": [],
|
||||
"peers": ["tcp://192.0.2.1:11010"],
|
||||
"optimization": {"mode": "direct"},
|
||||
"unknown_projection_field": true,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_modes_force_invariants_and_round_trip() {
|
||||
let toml = build_config(&draft()).unwrap();
|
||||
let config = crate::parse_config(&toml).unwrap();
|
||||
let flags = config.get_flags();
|
||||
assert!(flags.no_tun && flags.use_smoltcp && flags.enable_encryption);
|
||||
assert!(flags.disable_p2p && !flags.latency_first && flags.enable_ipv6);
|
||||
assert_eq!(flags.foreign_relay_bps_limit, u64::MAX);
|
||||
assert_eq!(config.get_peers().len(), 1);
|
||||
assert!(toml.contains("stun_servers = []"));
|
||||
assert!(toml.contains("mode = \"application\""));
|
||||
|
||||
let mut system = draft();
|
||||
system["runtime_mode"] = json!("system_vpn");
|
||||
let config = crate::parse_config(&build_config(&system).unwrap()).unwrap();
|
||||
assert!(!config.get_flags().no_tun && !config.get_flags().use_smoltcp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dhcp_and_defaults() {
|
||||
let toml = build_config(&json!({"dhcp": true, "ipv4": "", "network_name": "n"})).unwrap();
|
||||
let config = crate::parse_config(&toml).unwrap();
|
||||
assert!(config.get_dhcp() && config.get_flags().latency_first);
|
||||
assert_eq!(config.get_hostname(), "MeshPort");
|
||||
assert!(build_config(&json!({"network_name": "n", "ipv4": 7})).is_err());
|
||||
assert!(build_config(&json!({"network_name": ""})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_subnet_routes_are_removed_only_when_present() {
|
||||
let base = "ipv4 = '10.77.0.11'\n[network_identity]\nnetwork_name = 'test'\n";
|
||||
assert_eq!(migrate_config(base).unwrap(), (base.to_owned(), false));
|
||||
for legacy in [
|
||||
format!("subnet_routes = ['192.168.21.0/24']\n{base}"),
|
||||
format!("{base}[runtime]\nmode = 'system_vpn'\nsubnet_routes = ['192.168.21.0/24']\n"),
|
||||
] {
|
||||
assert!(crate::parse_config(&legacy).is_err());
|
||||
let (migrated, changed) = migrate_config(&legacy).unwrap();
|
||||
assert!(changed && !migrated.contains("subnet_routes"));
|
||||
crate::parse_config(&migrated).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,165 @@
|
||||
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)
|
||||
}
|
||||
|
||||
/// Overlay network when it can carry routed host traffic: a private IPv4 /16-/32.
|
||||
pub fn routable_overlay(address: Ipv4Addr, prefix: u8) -> Option<Ipv4Cidr> {
|
||||
if !(16..=32).contains(&prefix) || !address.is_private() {
|
||||
return None;
|
||||
}
|
||||
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
|
||||
Ipv4Cidr::new(Ipv4Addr::from(u32::from(address) & mask), prefix).ok()
|
||||
}
|
||||
|
||||
/// The canonical, sorted set of destinations hosts must send through the mesh:
|
||||
/// the routable overlay network plus accepted advertised subnets.
|
||||
pub fn mesh_cidrs(overlay: Option<(Ipv4Addr, u8)>, accepted: &[Ipv4Cidr]) -> Vec<String> {
|
||||
let mut result = std::collections::BTreeSet::new();
|
||||
if let Some(cidr) = overlay.and_then(|(address, prefix)| routable_overlay(address, prefix)) {
|
||||
result.insert(cidr);
|
||||
}
|
||||
result.extend(accepted.iter().copied());
|
||||
// Always spell the prefix length; host routes would otherwise print bare.
|
||||
result
|
||||
.into_iter()
|
||||
.map(|cidr| format!("{}/{}", cidr.first_address(), cidr.network_length()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fails when the overlay overlaps an address already configured on this host,
|
||||
/// such as the physical LAN or another VPN. Reads interfaces fresh, uncached.
|
||||
pub fn check_local_overlap(address: Ipv4Addr, prefix: u8) -> anyhow::Result<()> {
|
||||
use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig};
|
||||
let interfaces = NetworkInterface::show()
|
||||
.map_err(|_| anyhow::anyhow!("cannot inspect existing interfaces"))?;
|
||||
let conflict = interfaces
|
||||
.into_iter()
|
||||
.flat_map(|iface| iface.addr)
|
||||
.any(|addr| match addr {
|
||||
Addr::V4(v4) => v4
|
||||
.netmask
|
||||
.is_some_and(|mask| overlaps(address, prefix, v4.ip, u32::from(mask))),
|
||||
_ => false,
|
||||
});
|
||||
anyhow::ensure!(
|
||||
!conflict,
|
||||
"overlay overlaps an existing interface; choose another subnet or stop the conflicting VPN"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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 mesh_cidrs_are_canonical_sorted_and_skip_unroutable_overlays() {
|
||||
let accepted: Vec<Ipv4Cidr> = vec!["192.168.21.0/24".parse().unwrap()];
|
||||
assert_eq!(
|
||||
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 24)), &accepted),
|
||||
vec!["10.77.0.0/24", "192.168.21.0/24"]
|
||||
);
|
||||
assert_eq!(
|
||||
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 32)), &[]),
|
||||
vec!["10.77.0.11/32"]
|
||||
);
|
||||
for (address, prefix) in [("8.8.8.8", 24), ("10.0.0.1", 8)] {
|
||||
assert_eq!(
|
||||
mesh_cidrs(Some((address.parse().unwrap(), prefix)), &accepted),
|
||||
vec!["192.168.21.0/24"]
|
||||
);
|
||||
}
|
||||
assert!(mesh_cidrs(None, &[]).is_empty());
|
||||
}
|
||||
#[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,26 @@
|
||||
[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
|
||||
meshport-socks.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"]
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { workspace = true, features = ["proxy-packet"] }
|
||||
easytier-core.workspace = true
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
+862
@@ -0,0 +1,862 @@
|
||||
//! 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);
|
||||
/// Additive JSON operation set within ABI v1. Bump when hosts must rely on a
|
||||
/// newly added operation or field; hosts reject libraries below what they need.
|
||||
const CAPABILITY_REVISION: u32 = 2;
|
||||
const OPERATIONS: &[&str] = &[
|
||||
"abi_info",
|
||||
"build_config",
|
||||
"migrate_config",
|
||||
"validate",
|
||||
"start",
|
||||
"start_bridged",
|
||||
"stop",
|
||||
"status",
|
||||
"wait_routes",
|
||||
"socks_start",
|
||||
"socks_stop",
|
||||
"socks_status",
|
||||
"diagnostics_enable",
|
||||
"probe",
|
||||
"quality_sample",
|
||||
"tcp_connect",
|
||||
"tcp_write",
|
||||
"tcp_read",
|
||||
"udp_bind",
|
||||
"udp_send",
|
||||
"udp_receive",
|
||||
"resource_close",
|
||||
];
|
||||
#[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<Arc<Network>>>,
|
||||
socks: Mutex<Option<meshport_socks::Bridge>>,
|
||||
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.socks.get_mut()
|
||||
&& let Some(mut bridge) = slot.take()
|
||||
{
|
||||
let _ = self.runtime.block_on(bridge.stop());
|
||||
}
|
||||
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),
|
||||
socks: 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(AssertUnwindSafe(|| {
|
||||
let Some(context) = CONTEXTS.lock().unwrap().remove(&id) else {
|
||||
return;
|
||||
};
|
||||
// Stop now rather than when the last Arc drops: a `wait_routes` call
|
||||
// holds one without the serial lock, and stopping is what wakes it.
|
||||
if let Ok(mut network) = context.network.lock() {
|
||||
let _ = stop_all(&context, &mut network);
|
||||
}
|
||||
drop(context);
|
||||
}));
|
||||
}
|
||||
fn start_socks(context: &Context, n: &Arc<Network>, request: &Value) -> anyhow::Result<String> {
|
||||
let mut slot = context.socks.lock().unwrap();
|
||||
anyhow::ensure!(slot.is_none(), "SOCKS bridge already started");
|
||||
let port = match request.get("port") {
|
||||
Some(value) => u16::try_from(
|
||||
value
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid port"))?,
|
||||
)?,
|
||||
None => 0,
|
||||
};
|
||||
let max_sessions = match request.get("max_sessions") {
|
||||
Some(value) => usize::try_from(
|
||||
value
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid session limit"))?,
|
||||
)?,
|
||||
None => 128,
|
||||
};
|
||||
let options = meshport_socks::Options {
|
||||
listen: std::net::SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port),
|
||||
max_sessions,
|
||||
..Default::default()
|
||||
};
|
||||
let bridge = context
|
||||
.runtime
|
||||
.block_on(meshport_socks::Bridge::start(n.clone(), options))?;
|
||||
let address = bridge.local_addr().to_string();
|
||||
*slot = Some(bridge);
|
||||
Ok(address)
|
||||
}
|
||||
fn stop_all(context: &Context, network: &mut Option<Arc<Network>>) -> anyhow::Result<()> {
|
||||
let bridge = context.socks.lock().unwrap().take();
|
||||
let result = match bridge {
|
||||
Some(mut bridge) => context.runtime.block_on(bridge.stop()),
|
||||
None => Ok(()),
|
||||
};
|
||||
context.tcp.blocking_lock().clear();
|
||||
context.udp.blocking_lock().clear();
|
||||
if let Some(n) = network.take() {
|
||||
context.runtime.block_on(n.stop());
|
||||
}
|
||||
result
|
||||
}
|
||||
fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
let op = request["op"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing op"))?;
|
||||
if op == "abi_info" {
|
||||
return Ok(json!({"abi": 1, "revision": CAPABILITY_REVISION, "operations": OPERATIONS}));
|
||||
}
|
||||
// Long poll for route changes. Runs outside the serial context lock so a
|
||||
// host can wait on one thread while issuing other requests on another.
|
||||
if op == "wait_routes" {
|
||||
let timeout_ms = request["timeout_ms"].as_u64().unwrap_or(25000);
|
||||
anyhow::ensure!(
|
||||
(1..=30000).contains(&timeout_ms),
|
||||
"timeout_ms must be 1 to 30000"
|
||||
);
|
||||
let after = match request.get("after_generation") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(value) => Some(
|
||||
value
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid after_generation"))?,
|
||||
),
|
||||
};
|
||||
let network = context
|
||||
.network
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("context lock poisoned"))?
|
||||
.clone();
|
||||
let Some(network) = network else {
|
||||
return Ok(json!({"running": false, "changed": after.is_some(),
|
||||
"route_generation": null, "mesh_cidrs": [], "subnet_routes": []}));
|
||||
};
|
||||
let mut watch = network.watch_mesh_routes();
|
||||
let changed = context.runtime.block_on(async {
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(timeout_ms),
|
||||
watch.wait_for(|r| r.stopped || after.is_none_or(|a| r.generation != a)),
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
});
|
||||
let routes = watch.borrow().clone();
|
||||
return Ok(json!({"running": !routes.stopped,
|
||||
"changed": changed && after.is_some_and(|a| a != routes.generation),
|
||||
"route_generation": routes.generation, "mesh_cidrs": routes.cidrs,
|
||||
"subnet_routes": routes.subnet_routes}));
|
||||
}
|
||||
if op == "diagnostics_enable" {
|
||||
return Ok(json!({"enabled": diagnostics::enable(), "scope": "process"}));
|
||||
}
|
||||
if op == "build_config" {
|
||||
return Ok(json!({"toml": meshport::build_config(&request["profile"])?}));
|
||||
}
|
||||
if op == "migrate_config" {
|
||||
let input = request["toml"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
|
||||
let (toml, changed) = meshport::migrate_config(input)?;
|
||||
return Ok(json!({"toml": toml, "changed": changed}));
|
||||
}
|
||||
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)?;
|
||||
if request["check_local_overlap"].as_bool() == Some(true) {
|
||||
meshport::check_local_overlap(&config)?;
|
||||
}
|
||||
let flags = config.get_flags();
|
||||
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"},
|
||||
"overlay": meshport::overlay_projection(&config)});
|
||||
// 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,
|
||||
"listeners": config.get_listener_uris().iter().map(|uri| uri.to_string()).collect::<Vec<_>>(),
|
||||
"stun_servers": config.get_stun_servers(),
|
||||
"stun_servers_v6": config.get_stun_servers_v6(),
|
||||
"flags": {
|
||||
"default_protocol": flags.default_protocol,
|
||||
"disable_p2p": flags.disable_p2p,
|
||||
"disable_tcp_hole_punching": flags.disable_tcp_hole_punching,
|
||||
"disable_udp_hole_punching": flags.disable_udp_hole_punching,
|
||||
"disable_sym_hole_punching": flags.disable_sym_hole_punching,
|
||||
"p2p_only": flags.p2p_only,
|
||||
"lazy_p2p": flags.lazy_p2p,
|
||||
"need_p2p": flags.need_p2p,
|
||||
"private_mode": flags.private_mode,
|
||||
"foreign_relay_bps_limit": flags.foreign_relay_bps_limit.to_string()
|
||||
}
|
||||
});
|
||||
}
|
||||
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"))?;
|
||||
if request["check_local_overlap"].as_bool() == Some(true) {
|
||||
meshport::check_local_overlap(&meshport::validate_config(config)?)?;
|
||||
}
|
||||
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
|
||||
Ok(json!({"engine_started": true}))
|
||||
}
|
||||
// Application-mode network plus SOCKS bridge as one step, for hosts that
|
||||
// route traffic into the mesh. Either both run or neither does.
|
||||
"start_bridged" => {
|
||||
use meshport_easytier::ConfigLoader;
|
||||
anyhow::ensure!(
|
||||
network.is_none(),
|
||||
"already started; stop before applying a new configuration"
|
||||
);
|
||||
let input = request["toml"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
|
||||
let config = meshport::validate_config(input)?;
|
||||
anyhow::ensure!(
|
||||
config.get_flags().no_tun,
|
||||
"bridged routing requires application-mode MeshPort"
|
||||
);
|
||||
let overlay = meshport::overlay_projection(&config);
|
||||
anyhow::ensure!(
|
||||
!overlay.is_null() || request["require_static_overlay"].as_bool() != Some(true),
|
||||
"static mesh IPv4 required for bridged routing"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
overlay.is_null() || overlay["routable"] == true,
|
||||
"bridged routing requires a private IPv4 overlay with prefix /16 through /32"
|
||||
);
|
||||
if request["check_local_overlap"].as_bool() == Some(true) {
|
||||
meshport::check_local_overlap(&config)?;
|
||||
}
|
||||
let n = Arc::new(context.runtime.block_on(Network::start(input))?);
|
||||
*network = Some(n.clone());
|
||||
let listen = match start_socks(context, &n, &request) {
|
||||
Ok(listen) => listen,
|
||||
Err(error) => {
|
||||
let _ = stop_all(context, &mut network);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let routes = n.watch_mesh_routes().borrow().clone();
|
||||
Ok(
|
||||
json!({"engine_started": true, "listen": listen, "overlay": overlay,
|
||||
"mesh_cidrs": routes.cidrs, "route_generation": routes.generation}),
|
||||
)
|
||||
}
|
||||
"stop" => {
|
||||
stop_all(context, &mut network)?;
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"socks_start" => {
|
||||
let n = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
let address = start_socks(context, n, &request)?;
|
||||
Ok(
|
||||
json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}),
|
||||
)
|
||||
}
|
||||
"socks_stop" => {
|
||||
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
|
||||
context.runtime.block_on(bridge.stop())?;
|
||||
}
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"socks_status" => {
|
||||
let slot = context.socks.lock().unwrap();
|
||||
Ok(match slot.as_ref() {
|
||||
Some(bridge) => {
|
||||
let s = bridge.snapshot();
|
||||
json!({"running": s.running, "listen": bridge.local_addr().to_string(),
|
||||
"active_sessions": s.active_sessions, "accepted_sessions": s.accepted_sessions,
|
||||
"completed_sessions": s.completed_sessions, "failed_sessions": s.failed_sessions,
|
||||
"refused_at_capacity": s.refused_at_capacity, "dropped_udp_packets": s.dropped_udp_packets})
|
||||
}
|
||||
None => json!({"running": false, "active_sessions": 0}),
|
||||
})
|
||||
}
|
||||
"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);
|
||||
let engine_running = snapshot["state"] == "Running";
|
||||
let bridge_running = context
|
||||
.socks
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.is_some_and(|b| b.snapshot().running);
|
||||
// mesh_routable: traffic a host routes to mesh_cidrs via the
|
||||
// bridge can currently be delivered.
|
||||
snapshot["health"] = json!({"engine_running": engine_running,
|
||||
"bridge_running": bridge_running,
|
||||
"mesh_routable": engine_running && bridge_running});
|
||||
Ok(snapshot)
|
||||
}
|
||||
None => Ok(
|
||||
json!({"state": "Stopped", "peer_count": 0, "application_only": true,
|
||||
"health": {"engine_running": false, "bridge_running": false, "mesh_routable": false}}),
|
||||
),
|
||||
},
|
||||
"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"]["flags"]["foreign_relay_bps_limit"],
|
||||
"18446744073709551615"
|
||||
);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_build_and_migration_are_sdk_operations() {
|
||||
let id = meshport_context_new();
|
||||
let built = call(
|
||||
id,
|
||||
&json!({"op": "build_config", "profile": {"runtime_mode": "unified_vpn",
|
||||
"ipv4": "10.79.0.11/24", "network_name": "n", "network_secret": "s"}})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(built["ok"], true);
|
||||
let toml = built["data"]["toml"].as_str().unwrap();
|
||||
let validated = call(id, &json!({"op": "validate", "toml": toml}).to_string());
|
||||
assert_eq!(validated["data"]["runtime_mode"], "application");
|
||||
assert_eq!(validated["data"]["overlay"]["network"], "10.79.0.0/24");
|
||||
let legacy = format!("{toml}\nsubnet_routes = ['192.168.21.0/24']\n");
|
||||
let migrated = call(
|
||||
id,
|
||||
&json!({"op": "migrate_config", "toml": legacy}).to_string(),
|
||||
);
|
||||
assert_eq!(migrated["data"]["changed"], true);
|
||||
let migrated = migrated["data"]["toml"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
call(id, &json!({"op": "validate", "toml": migrated}).to_string())["ok"],
|
||||
true
|
||||
);
|
||||
meshport_context_free(id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bridged_start_is_atomic_and_reports_routes_and_health() {
|
||||
let id = meshport_context_new();
|
||||
let base = "listeners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'bridged-ffi-test'\nnetwork_secret = 'test-only'\n";
|
||||
let system = format!("ipv4 = '10.253.84.11/24'\n{base}[runtime]\nmode = 'system_vpn'\n");
|
||||
let wide = format!("ipv4 = '10.253.84.11/8'\n{base}");
|
||||
let dhcp = format!("dhcp = true\n{base}");
|
||||
for (config, static_required) in [(system, false), (wide, false), (dhcp, true)] {
|
||||
let refused = call(
|
||||
id,
|
||||
&json!({"op": "start_bridged", "toml": config,
|
||||
"require_static_overlay": static_required})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(refused["ok"], false, "{config}");
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
|
||||
}
|
||||
// Bridge failure (invalid session limit) rolls the network back.
|
||||
let config = format!("ipv4 = '10.253.84.11/24'\n{base}");
|
||||
let failed = call(
|
||||
id,
|
||||
&json!({"op": "start_bridged", "toml": config, "max_sessions": 0}).to_string(),
|
||||
);
|
||||
assert_eq!(failed["ok"], false);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
|
||||
|
||||
let started = call(
|
||||
id,
|
||||
&json!({"op": "start_bridged", "toml": config}).to_string(),
|
||||
);
|
||||
assert_eq!(started["ok"], true, "{started}");
|
||||
assert_eq!(started["data"]["mesh_cidrs"], json!(["10.253.84.0/24"]));
|
||||
assert!(started["data"]["route_generation"].as_u64().unwrap() >= 1);
|
||||
assert!(std::net::TcpStream::connect(started["data"]["listen"].as_str().unwrap()).is_ok());
|
||||
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
|
||||
assert_eq!(status["health"]["mesh_routable"], true);
|
||||
assert_eq!(
|
||||
status["platform_network"]["mesh_cidrs"],
|
||||
json!(["10.253.84.0/24"])
|
||||
);
|
||||
assert_eq!(
|
||||
status["platform_network"]["overlay"]["address"],
|
||||
"10.253.84.11"
|
||||
);
|
||||
let generation = started["data"]["route_generation"].as_u64().unwrap();
|
||||
let idle = call(
|
||||
id,
|
||||
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 200})
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(idle["data"]["changed"], false, "{idle}");
|
||||
assert_eq!(idle["data"]["running"], true);
|
||||
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
|
||||
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
|
||||
assert_eq!(status["health"]["engine_running"], true);
|
||||
assert_eq!(status["health"]["mesh_routable"], false);
|
||||
// A waiter does not hold the context: status still answers, and stop
|
||||
// wakes it with empty routes well before its timeout.
|
||||
let waiter = std::thread::spawn(move || {
|
||||
let at = std::time::Instant::now();
|
||||
let reply = call(
|
||||
id,
|
||||
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
|
||||
.to_string(),
|
||||
);
|
||||
(reply, at.elapsed())
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
|
||||
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
|
||||
let (woken, waited) = waiter.join().unwrap();
|
||||
assert!(waited < Duration::from_secs(10), "{waited:?}");
|
||||
assert_eq!(woken["data"]["running"], false, "{woken}");
|
||||
assert_eq!(woken["data"]["changed"], true);
|
||||
assert_eq!(woken["data"]["mesh_cidrs"], json!([]));
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"wait_routes","timeout_ms":0}"#)["ok"],
|
||||
false
|
||||
);
|
||||
let info = call(id, r#"{"op":"abi_info"}"#)["data"].clone();
|
||||
assert_eq!(info["abi"], 1);
|
||||
assert!(info["revision"].as_u64().unwrap() >= 2);
|
||||
assert!(
|
||||
info["operations"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|o| o == "wait_routes")
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"status"}"#)["data"]["health"]["mesh_routable"],
|
||||
false
|
||||
);
|
||||
// Freeing without stop also stops the network and wakes a waiter.
|
||||
let started = call(
|
||||
id,
|
||||
&json!({"op": "start_bridged", "toml": config}).to_string(),
|
||||
);
|
||||
assert_eq!(started["ok"], true, "{started}");
|
||||
let generation = started["data"]["route_generation"].as_u64().unwrap();
|
||||
let waiter = std::thread::spawn(move || {
|
||||
let at = std::time::Instant::now();
|
||||
let reply = call(
|
||||
id,
|
||||
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
|
||||
.to_string(),
|
||||
);
|
||||
(reply, at.elapsed())
|
||||
});
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
meshport_context_free(id);
|
||||
let (woken, waited) = waiter.join().unwrap();
|
||||
assert!(waited < Duration::from_secs(10), "{waited:?}");
|
||||
assert_eq!(woken["data"]["running"], false, "{woken}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socks_control_lifecycle_and_context_cleanup() {
|
||||
use std::io::{Read, Write};
|
||||
let id = meshport_context_new();
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
|
||||
let config = "ipv4 = '10.253.83.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'socks-ffi-test'\nnetwork_secret = 'test-only'\n";
|
||||
assert_eq!(
|
||||
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_start","port":65536}"#)["ok"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_start","max_sessions":0}"#)["ok"],
|
||||
false
|
||||
);
|
||||
let started = call(id, r#"{"op":"socks_start"}"#);
|
||||
assert_eq!(started["ok"], true);
|
||||
let address = started["data"]["listen"].as_str().unwrap();
|
||||
let mut control = std::net::TcpStream::connect(address).unwrap();
|
||||
control
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
control.write_all(&[5, 1, 0]).unwrap();
|
||||
let mut reply = [0; 2];
|
||||
control.read_exact(&mut reply).unwrap();
|
||||
assert_eq!(reply, [5, 0]);
|
||||
// A native session waiting for its request does not hold the ABI lock.
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["active_sessions"],
|
||||
1
|
||||
);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
|
||||
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
|
||||
assert_eq!(control.read(&mut [0]).unwrap(), 0);
|
||||
assert!(std::net::TcpStream::connect(address).is_err());
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
|
||||
false
|
||||
);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], true);
|
||||
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
|
||||
true
|
||||
);
|
||||
let restarted = call(id, r#"{"op":"socks_start"}"#);
|
||||
let address = restarted["data"]["listen"].as_str().unwrap();
|
||||
let mut control = std::net::TcpStream::connect(address).unwrap();
|
||||
control
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
control.write_all(&[5, 1, 0]).unwrap();
|
||||
control.read_exact(&mut reply).unwrap();
|
||||
meshport_context_free(id);
|
||||
assert_eq!(control.read(&mut [0]).unwrap(), 0);
|
||||
// No lingering listener after context destruction.
|
||||
std::net::TcpListener::bind(address).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::TomlConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::ffi::{CStr, CString};
|
||||
fn call(id: u64, request: Value) -> Value {
|
||||
let input = CString::new(request.to_string()).unwrap();
|
||||
unsafe {
|
||||
let reply = meshport_ffi::meshport_call(id, input.as_ptr());
|
||||
let result = serde_json::from_slice(CStr::from_ptr(reply).to_bytes()).unwrap();
|
||||
meshport_ffi::meshport_string_free(reply);
|
||||
result
|
||||
}
|
||||
}
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[test]
|
||||
fn ffi_udp_through_adjacent_mapped_subnet() {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let setup = async {
|
||||
let port = UdpSocket::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
|
||||
let server_config = TomlConfig::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let client = format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
);
|
||||
(server, client)
|
||||
};
|
||||
let (server, client) = runtime.block_on(setup);
|
||||
drop(_entered);
|
||||
let id = meshport_ffi::meshport_context_new();
|
||||
assert_eq!(call(id, json!({"op":"start", "toml":client}))["ok"], true);
|
||||
let deadline = std::time::Instant::now();
|
||||
loop {
|
||||
if call(id, json!({"op":"status"}))["data"]["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
assert!(deadline.elapsed() < Duration::from_secs(15));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
let (target, echo): (std::net::SocketAddr, _) = runtime.block_on(async {
|
||||
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let echo = tokio::spawn(async move {
|
||||
let mut buffer = [0; 128];
|
||||
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
||||
udp.send_to(&buffer[..n], source).await.unwrap();
|
||||
});
|
||||
(target, echo)
|
||||
});
|
||||
let result = call(
|
||||
id,
|
||||
json!({"op":"probe", "target":target.to_string(), "protocol":"UDP", "echo":true, "timeout_ms":3000}),
|
||||
);
|
||||
|
||||
echo.abort();
|
||||
call(id, json!({"op":"stop"}));
|
||||
meshport_ffi::meshport_context_free(id);
|
||||
runtime.block_on(server.stop());
|
||||
assert_eq!(result["ok"], true, "FFI UDP failed: {result}");
|
||||
}
|
||||
@@ -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,25 @@
|
||||
[package]
|
||||
name = "meshport-socks"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
meshport.workspace = true
|
||||
anyhow.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
meshport-easytier.workspace = true
|
||||
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
|
||||
easytier-core.workspace = true
|
||||
tokio = { workspace = true, features = ["signal", "process"] }
|
||||
serde_json.workspace = true
|
||||
futures = "0.3"
|
||||
parking_lot = "0.12"
|
||||
smoltcp = { version = "0.14", default-features = false }
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
tracing = "0.1"
|
||||
bytes = "1"
|
||||
aes-gcm = "0.10"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Run with an application-mode TOML file; never prints its credentials.
|
||||
use anyhow::{Context, Result};
|
||||
use meshport::Network;
|
||||
use meshport_socks::{Bridge, Options};
|
||||
use std::{
|
||||
net::{Ipv4Addr, SocketAddrV4},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
let path = arguments
|
||||
.next()
|
||||
.context("usage: local_bridge CONFIG.toml [PORT]")?;
|
||||
let port = arguments
|
||||
.next()
|
||||
.map(|s| s.parse::<u16>())
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
anyhow::ensure!(arguments.next().is_none(), "too many arguments");
|
||||
let config = std::fs::read_to_string(path).context("cannot read configuration")?;
|
||||
let network = Arc::new(Network::start(&config).await?);
|
||||
let result = async {
|
||||
let mut bridge = Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, port),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
println!("MeshPort SOCKS5 IPv4 TCP/UDP: {}", bridge.local_addr());
|
||||
println!("Waiting for Ctrl-C; engine startup does not guarantee remote reachability.");
|
||||
let signal = tokio::signal::ctrl_c().await;
|
||||
bridge.stop().await?;
|
||||
signal?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
network.stop().await;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Local IPv4 SOCKS5 bridge to the MeshPort application data plane.
|
||||
//! No DNS or ordinary internet fallback. This is a restricted internal bridge,
|
||||
//! not a public SOCKS service (no GSSAPI, password authentication, or BIND).
|
||||
mod protocol;
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
use meshport::Network;
|
||||
use protocol::*;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt, copy, split},
|
||||
net::{TcpListener, TcpStream, UdpSocket},
|
||||
sync::{Semaphore, watch},
|
||||
task::{JoinHandle, JoinSet},
|
||||
time::{Instant, sleep_until, timeout},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Options {
|
||||
pub listen: SocketAddrV4,
|
||||
pub max_sessions: usize,
|
||||
pub handshake_timeout: Duration,
|
||||
pub connect_timeout: Duration,
|
||||
/// Grace period for the remaining direction after either side reaches EOF.
|
||||
pub tcp_close_timeout: Duration,
|
||||
pub udp_idle_timeout: Duration,
|
||||
pub udp_io_timeout: Duration,
|
||||
pub max_udp_targets: usize,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0),
|
||||
max_sessions: 128,
|
||||
handshake_timeout: Duration::from_secs(5),
|
||||
connect_timeout: Duration::from_secs(10),
|
||||
tcp_close_timeout: Duration::from_secs(30),
|
||||
udp_idle_timeout: Duration::from_secs(120),
|
||||
udp_io_timeout: Duration::from_secs(5),
|
||||
max_udp_targets: 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Counters {
|
||||
active: AtomicUsize,
|
||||
accepted: AtomicU64,
|
||||
completed: AtomicU64,
|
||||
failed: AtomicU64,
|
||||
refused_at_capacity: AtomicU64,
|
||||
dropped_udp: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Snapshot {
|
||||
pub running: bool,
|
||||
pub active_sessions: usize,
|
||||
pub accepted_sessions: u64,
|
||||
pub completed_sessions: u64,
|
||||
pub failed_sessions: u64,
|
||||
pub refused_at_capacity: u64,
|
||||
pub dropped_udp_packets: u64,
|
||||
}
|
||||
|
||||
struct Active(Arc<Counters>);
|
||||
impl Drop for Active {
|
||||
fn drop(&mut self) {
|
||||
self.0.active.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the listener and its sessions, but not the supplied network.
|
||||
/// Stop the bridge before stopping the network. Dropping aborts all sessions;
|
||||
/// `stop` additionally waits for resources to be released.
|
||||
pub struct Bridge {
|
||||
address: SocketAddrV4,
|
||||
shutdown: watch::Sender<bool>,
|
||||
task: Option<JoinHandle<std::io::Result<()>>>,
|
||||
counters: Arc<Counters>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
pub async fn start(network: Arc<Network>, options: Options) -> Result<Self> {
|
||||
ensure!(
|
||||
options.listen.ip().is_loopback(),
|
||||
"SOCKS bridge must bind IPv4 loopback"
|
||||
);
|
||||
ensure!(
|
||||
options.max_sessions > 0 && options.max_sessions <= 4096,
|
||||
"invalid session limit"
|
||||
);
|
||||
ensure!(
|
||||
options.max_udp_targets > 0 && options.max_udp_targets <= 1024,
|
||||
"invalid UDP target limit"
|
||||
);
|
||||
ensure!(
|
||||
!options.handshake_timeout.is_zero()
|
||||
&& !options.connect_timeout.is_zero()
|
||||
&& !options.tcp_close_timeout.is_zero()
|
||||
&& !options.udp_idle_timeout.is_zero()
|
||||
&& !options.udp_io_timeout.is_zero(),
|
||||
"timeouts must be positive"
|
||||
);
|
||||
let status = network.snapshot().await;
|
||||
ensure!(
|
||||
status["application_only"] == true,
|
||||
"SOCKS bridge requires application mode"
|
||||
);
|
||||
ensure!(status["state"] == "Running", "network is not running");
|
||||
let listener = TcpListener::bind(options.listen).await?;
|
||||
let SocketAddr::V4(address) = listener.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
let counters = Arc::new(Counters::default());
|
||||
let (shutdown, rx) = watch::channel(false);
|
||||
let task = tokio::spawn(serve(listener, network, options, rx, counters.clone()));
|
||||
Ok(Self {
|
||||
address,
|
||||
shutdown,
|
||||
task: Some(task),
|
||||
counters,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> SocketAddrV4 {
|
||||
self.address
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let c = &self.counters;
|
||||
Snapshot {
|
||||
running: self.task.as_ref().is_some_and(|task| !task.is_finished()),
|
||||
active_sessions: c.active.load(Ordering::Relaxed),
|
||||
accepted_sessions: c.accepted.load(Ordering::Relaxed),
|
||||
completed_sessions: c.completed.load(Ordering::Relaxed),
|
||||
failed_sessions: c.failed.load(Ordering::Relaxed),
|
||||
refused_at_capacity: c.refused_at_capacity.load(Ordering::Relaxed),
|
||||
dropped_udp_packets: c.dropped_udp.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn stop(&mut self) -> Result<()> {
|
||||
self.shutdown.send_replace(true);
|
||||
if let Some(task) = self.task.take() {
|
||||
task.await??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Bridge {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown.send_replace(true);
|
||||
if let Some(task) = &self.task {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
listener: TcpListener,
|
||||
network: Arc<Network>,
|
||||
options: Options,
|
||||
mut shutdown: watch::Receiver<bool>,
|
||||
counters: Arc<Counters>,
|
||||
) -> std::io::Result<()> {
|
||||
let permits = Arc::new(Semaphore::new(options.max_sessions));
|
||||
let mut sessions = JoinSet::new();
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.changed() => break Ok(()),
|
||||
_ = sessions.join_next(), if !sessions.is_empty() => {},
|
||||
accepted = listener.accept() => {
|
||||
let (stream, peer) = match accepted { Ok(v) => v, Err(e) => break Err(e) };
|
||||
let Ok(permit) = permits.clone().try_acquire_owned() else {
|
||||
counters.refused_at_capacity.fetch_add(1, Ordering::Relaxed);
|
||||
drop(stream);
|
||||
continue;
|
||||
};
|
||||
let SocketAddr::V4(peer) = peer else { continue; };
|
||||
counters.active.fetch_add(1, Ordering::Relaxed);
|
||||
counters.accepted.fetch_add(1, Ordering::Relaxed);
|
||||
let active = Active(counters.clone());
|
||||
let c = counters.clone();
|
||||
let network = network.clone();
|
||||
let options = options.clone();
|
||||
sessions.spawn(async move {
|
||||
let _permit = permit;
|
||||
let _active = active;
|
||||
if session(stream, peer, network, options, &c).await.is_err() {
|
||||
c.failed.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
c.completed.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
drop(listener);
|
||||
sessions.shutdown().await;
|
||||
result
|
||||
}
|
||||
|
||||
fn empty_address() -> SocketAddrV4 {
|
||||
SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)
|
||||
}
|
||||
|
||||
async fn session(
|
||||
mut stream: TcpStream,
|
||||
peer: SocketAddrV4,
|
||||
network: Arc<Network>,
|
||||
options: Options,
|
||||
counters: &Counters,
|
||||
) -> Result<()> {
|
||||
let request = timeout(options.handshake_timeout, async {
|
||||
ensure!(negotiate(&mut stream).await?, "no acceptable SOCKS method");
|
||||
Ok::<_, anyhow::Error>(request(&mut stream).await?)
|
||||
})
|
||||
.await??;
|
||||
let request = match request {
|
||||
Ok(request) => request,
|
||||
Err(code) => {
|
||||
reply(&mut stream, code, empty_address()).await?;
|
||||
anyhow::bail!("unsupported SOCKS request");
|
||||
}
|
||||
};
|
||||
if request.command == 1 {
|
||||
if !valid_target(request.address) {
|
||||
reply(&mut stream, DENIED, empty_address()).await?;
|
||||
anyhow::bail!("invalid mesh destination");
|
||||
}
|
||||
let result = timeout(
|
||||
options.connect_timeout,
|
||||
network.connect_tcp(request.address.into(), options.connect_timeout),
|
||||
)
|
||||
.await;
|
||||
let mut overlay = match result {
|
||||
Ok(Ok(stream)) => stream,
|
||||
error => {
|
||||
let code = match &error {
|
||||
Ok(Err(e))
|
||||
if e.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused) =>
|
||||
{
|
||||
REFUSED
|
||||
}
|
||||
_ => HOST_UNREACHABLE,
|
||||
};
|
||||
reply(&mut stream, code, empty_address()).await?;
|
||||
anyhow::bail!("mesh connection unavailable");
|
||||
}
|
||||
};
|
||||
let SocketAddr::V4(bound) = overlay.local_addr() else {
|
||||
unreachable!()
|
||||
};
|
||||
reply(&mut stream, SUCCESS, bound).await?;
|
||||
relay_tcp(&mut stream, &mut overlay, options.tcp_close_timeout).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if !request.address.ip().is_unspecified() && request.address.ip() != peer.ip() {
|
||||
reply(&mut stream, DENIED, empty_address()).await?;
|
||||
anyhow::bail!("UDP source differs from control connection");
|
||||
}
|
||||
let setup = timeout(options.connect_timeout, async {
|
||||
let SocketAddr::V4(local) = stream.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
let relay = UdpSocket::bind(SocketAddrV4::new(*local.ip(), 0)).await?;
|
||||
let overlay = network.bind_udp(0, options.connect_timeout).await?;
|
||||
Ok::<_, anyhow::Error>((relay, overlay))
|
||||
})
|
||||
.await;
|
||||
let (relay, overlay) = match setup {
|
||||
Ok(Ok(v)) => v,
|
||||
_ => {
|
||||
reply(&mut stream, FAILURE, empty_address()).await?;
|
||||
anyhow::bail!("UDP setup failed");
|
||||
}
|
||||
};
|
||||
let SocketAddr::V4(bound) = relay.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
reply(&mut stream, SUCCESS, bound).await?;
|
||||
udp_session(
|
||||
stream,
|
||||
peer,
|
||||
request.address.port(),
|
||||
relay,
|
||||
overlay,
|
||||
options,
|
||||
counters,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn relay_tcp(
|
||||
local: &mut TcpStream,
|
||||
remote: &mut meshport::TcpStream,
|
||||
close_timeout: Duration,
|
||||
) -> Result<()> {
|
||||
let (mut local_read, mut local_write) = split(local);
|
||||
let (mut remote_read, mut remote_write) = split(remote);
|
||||
let (closed, mut closure) = watch::channel(false);
|
||||
let upload = async {
|
||||
copy(&mut local_read, &mut remote_write).await?;
|
||||
// Notify before native shutdown: a FIN ACK may never arrive after
|
||||
// a route disappears. Permit pending response data a bounded grace.
|
||||
closed.send_replace(true);
|
||||
remote_write.shutdown().await
|
||||
};
|
||||
let download = async {
|
||||
copy(&mut remote_read, &mut local_write).await?;
|
||||
closed.send_replace(true);
|
||||
local_write.shutdown().await
|
||||
};
|
||||
let forwarding = async { tokio::try_join!(upload, download) };
|
||||
tokio::pin!(forwarding);
|
||||
tokio::select! {
|
||||
result = &mut forwarding => { result?; }
|
||||
_ = closure.changed() => { timeout(close_timeout, forwarding).await??; }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn udp_session(
|
||||
mut control: TcpStream,
|
||||
peer: SocketAddrV4,
|
||||
source_port: u16,
|
||||
relay: UdpSocket,
|
||||
overlay: meshport::UdpSocket,
|
||||
options: Options,
|
||||
counters: &Counters,
|
||||
) -> Result<()> {
|
||||
let mut endpoint = (source_port != 0).then_some(SocketAddrV4::new(*peer.ip(), source_port));
|
||||
let mut targets = HashSet::new();
|
||||
let mut local_buffer = vec![0; 65535];
|
||||
let mut remote_buffer = vec![0; 65535];
|
||||
let mut control_buffer = [0; 1];
|
||||
let mut idle = Instant::now() + options.udp_idle_timeout;
|
||||
loop {
|
||||
tokio::select! {
|
||||
// Association lifetime is tied to its TCP control channel.
|
||||
result = control.read(&mut control_buffer) => {
|
||||
result?;
|
||||
return Ok(()); // EOF or unexpected control payload closes it.
|
||||
}
|
||||
_ = sleep_until(idle) => return Ok(()),
|
||||
result = relay.recv_from(&mut local_buffer) => {
|
||||
let (len, source) = result?;
|
||||
let SocketAddr::V4(source) = source else { continue; };
|
||||
let decoded = udp_request(&local_buffer[..len]);
|
||||
if source.ip() != peer.ip() || endpoint.is_some_and(|e| e != source) || decoded.is_none() {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let (target, payload) = decoded.unwrap();
|
||||
if !targets.contains(&target) && targets.len() >= options.max_udp_targets {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
endpoint = Some(source);
|
||||
// Count attempted destinations too: the native socket can register
|
||||
// a flow before a send fails. This bounds its resource growth.
|
||||
targets.insert(target);
|
||||
match timeout(options.udp_io_timeout, overlay.send_to(payload, target.into())).await {
|
||||
Ok(Ok(n)) if n == payload.len() => idle = Instant::now() + options.udp_idle_timeout,
|
||||
_ => { counters.dropped_udp.fetch_add(1, Ordering::Relaxed); }
|
||||
}
|
||||
}
|
||||
result = overlay.recv_from(&mut remote_buffer) => {
|
||||
let (len, source) = result?;
|
||||
let SocketAddr::V4(source) = source else { continue; };
|
||||
let Some(endpoint) = endpoint else { continue; };
|
||||
if !targets.contains(&source) { continue; }
|
||||
let Some(frame) = udp_reply(source, &remote_buffer[..len]) else {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
};
|
||||
timeout(options.udp_io_timeout, relay.send_to(&frame, endpoint)).await??;
|
||||
idle = Instant::now() + options.udp_idle_timeout;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
pub(crate) const SUCCESS: u8 = 0;
|
||||
pub(crate) const FAILURE: u8 = 1;
|
||||
pub(crate) const DENIED: u8 = 2;
|
||||
pub(crate) const HOST_UNREACHABLE: u8 = 4;
|
||||
pub(crate) const REFUSED: u8 = 5;
|
||||
pub(crate) const COMMAND_UNSUPPORTED: u8 = 7;
|
||||
pub(crate) const ADDRESS_UNSUPPORTED: u8 = 8;
|
||||
|
||||
pub(crate) struct Request {
|
||||
pub command: u8,
|
||||
pub address: SocketAddrV4,
|
||||
}
|
||||
|
||||
pub(crate) async fn negotiate<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
s: &mut S,
|
||||
) -> std::io::Result<bool> {
|
||||
let mut header = [0; 2];
|
||||
s.read_exact(&mut header).await?;
|
||||
if header[0] != 5 || header[1] == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut methods = vec![0; header[1] as usize];
|
||||
s.read_exact(&mut methods).await?;
|
||||
let accepted = methods.contains(&0);
|
||||
s.write_all(&[5, if accepted { 0 } else { 255 }]).await?;
|
||||
Ok(accepted)
|
||||
}
|
||||
|
||||
/// Unsupported address types are deliberately not resolved using system DNS.
|
||||
pub(crate) async fn request<S: AsyncRead + Unpin>(
|
||||
s: &mut S,
|
||||
) -> std::io::Result<Result<Request, u8>> {
|
||||
let mut header = [0; 4];
|
||||
s.read_exact(&mut header).await?;
|
||||
if header[0] != 5 || header[2] != 0 {
|
||||
return Ok(Err(FAILURE));
|
||||
}
|
||||
if !matches!(header[1], 1 | 3) {
|
||||
return Ok(Err(COMMAND_UNSUPPORTED));
|
||||
}
|
||||
if header[3] != 1 {
|
||||
return Ok(Err(ADDRESS_UNSUPPORTED));
|
||||
}
|
||||
let mut address = [0; 6];
|
||||
s.read_exact(&mut address).await?;
|
||||
Ok(Ok(Request {
|
||||
command: header[1],
|
||||
address: decode_address(&address),
|
||||
}))
|
||||
}
|
||||
|
||||
fn decode_address(bytes: &[u8]) -> SocketAddrV4 {
|
||||
SocketAddrV4::new(
|
||||
Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]),
|
||||
u16::from_be_bytes([bytes[4], bytes[5]]),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn address_bytes(address: SocketAddrV4) -> [u8; 6] {
|
||||
let [a, b, c, d] = address.ip().octets();
|
||||
let [hi, lo] = address.port().to_be_bytes();
|
||||
[a, b, c, d, hi, lo]
|
||||
}
|
||||
|
||||
pub(crate) async fn reply<S: AsyncWrite + Unpin>(
|
||||
s: &mut S,
|
||||
code: u8,
|
||||
address: SocketAddrV4,
|
||||
) -> std::io::Result<()> {
|
||||
let mut bytes = vec![5, code, 0, 1];
|
||||
bytes.extend_from_slice(&address_bytes(address));
|
||||
s.write_all(&bytes).await
|
||||
}
|
||||
|
||||
pub(crate) fn valid_target(address: SocketAddrV4) -> bool {
|
||||
address.port() != 0
|
||||
&& !address.ip().is_unspecified()
|
||||
&& !address.ip().is_multicast()
|
||||
&& !address.ip().is_broadcast()
|
||||
&& !address.ip().is_loopback()
|
||||
}
|
||||
|
||||
pub(crate) fn udp_request(bytes: &[u8]) -> Option<(SocketAddrV4, &[u8])> {
|
||||
// No fragmentation, domain resolution, IPv6, or reserved bits.
|
||||
if bytes.len() < 10 || bytes[..4] != [0, 0, 0, 1] || bytes.len() > 65507 {
|
||||
return None;
|
||||
}
|
||||
let address = decode_address(&bytes[4..10]);
|
||||
valid_target(address).then_some((address, &bytes[10..]))
|
||||
}
|
||||
|
||||
pub(crate) fn udp_reply(address: SocketAddrV4, payload: &[u8]) -> Option<Vec<u8>> {
|
||||
if payload.len() > 65497 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(10 + payload.len());
|
||||
bytes.extend_from_slice(&[0, 0, 0, 1]);
|
||||
bytes.extend_from_slice(&address_bytes(address));
|
||||
bytes.extend_from_slice(payload);
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn udp_rejects_malformed_fragmented_and_non_mesh_addresses() {
|
||||
let target = "10.77.0.2:7007".parse().unwrap();
|
||||
let frame = udp_reply(target, b"hello").unwrap();
|
||||
assert_eq!(udp_request(&frame), Some((target, &b"hello"[..])));
|
||||
for length in 0..10 {
|
||||
assert!(udp_request(&frame[..length]).is_none());
|
||||
}
|
||||
for (index, value) in [(0, 1), (1, 1), (2, 1), (3, 3), (3, 4)] {
|
||||
let mut bad = frame.clone();
|
||||
bad[index] = value;
|
||||
assert!(udp_request(&bad).is_none());
|
||||
}
|
||||
for address in [
|
||||
"0.0.0.0:1",
|
||||
"127.0.0.1:1",
|
||||
"224.0.0.1:1",
|
||||
"255.255.255.255:1",
|
||||
"10.0.0.1:0",
|
||||
] {
|
||||
assert!(udp_request(&udp_reply(address.parse().unwrap(), b"x").unwrap()).is_none());
|
||||
}
|
||||
assert!(udp_reply(target, &vec![0; 65498]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
|
||||
use meshport::Network;
|
||||
use meshport_socks::{Bridge, Options};
|
||||
use std::{
|
||||
net::SocketAddrV4,
|
||||
path::{Path, PathBuf},
|
||||
process::Stdio,
|
||||
sync::Arc,
|
||||
time::{Duration, SystemTime},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
|
||||
net::{TcpListener, TcpStream, UdpSocket},
|
||||
task::JoinSet,
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
|
||||
const WAIT: Duration = Duration::from_secs(15);
|
||||
|
||||
#[path = "support/queue_drop_counter.rs"]
|
||||
mod queue_drop_counter;
|
||||
#[path = "support/wire_stats.rs"]
|
||||
mod wire_stats;
|
||||
|
||||
struct ExternalEngine {
|
||||
child: tokio::process::Child,
|
||||
config_path: PathBuf,
|
||||
listen: SocketAddrV4,
|
||||
}
|
||||
|
||||
impl Drop for ExternalEngine {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.config_path);
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalEngine {
|
||||
async fn start(
|
||||
binary: &Path,
|
||||
bridge: SocketAddrV4,
|
||||
network: &Network,
|
||||
extra_cidrs: &[&str],
|
||||
) -> Self {
|
||||
let reserved = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let listen: SocketAddrV4 = reserved.local_addr().unwrap().to_string().parse().unwrap();
|
||||
let stamp = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let config_path = std::env::temp_dir().join(format!(
|
||||
"meshport-singbox-{}-{stamp}.json",
|
||||
std::process::id()
|
||||
));
|
||||
let snapshot = network.snapshot().await;
|
||||
let mut prefixes = snapshot["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.clone();
|
||||
prefixes.push(snapshot["ipv4"].clone());
|
||||
prefixes.extend(extra_cidrs.iter().map(|cidr| serde_json::json!(cidr)));
|
||||
let config = serde_json::json!({"listen_port": listen.port(), "mesh_socks": bridge.to_string(), "mesh_cidrs": prefixes});
|
||||
std::fs::write(&config_path, config.to_string()).unwrap();
|
||||
drop(reserved);
|
||||
let child = tokio::process::Command::new(binary)
|
||||
.arg(&config_path)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut engine = Self {
|
||||
child,
|
||||
config_path,
|
||||
listen,
|
||||
};
|
||||
let mut readiness = String::new();
|
||||
timeout(
|
||||
WAIT,
|
||||
BufReader::new(engine.child.stdout.take().unwrap()).read_line(&mut readiness),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let ready: serde_json::Value = serde_json::from_str(&readiness).unwrap();
|
||||
assert_eq!(ready["state"], "Running");
|
||||
engine
|
||||
}
|
||||
|
||||
async fn stop(&mut self) {
|
||||
let id = self.child.id().unwrap();
|
||||
let status = std::process::Command::new("/bin/kill")
|
||||
.args(["-TERM", &id.to_string()])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
assert!(
|
||||
timeout(WAIT, self.child.wait())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.success()
|
||||
);
|
||||
assert!(TcpStream::connect(self.listen).await.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn config(ip: &str, bootstrap: Option<u16>) -> String {
|
||||
let peer = bootstrap
|
||||
.map(|port| format!("[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n"))
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
"ipv4 = '{ip}/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n{peer}[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n"
|
||||
)
|
||||
}
|
||||
|
||||
async fn negotiate(addr: SocketAddrV4) -> TcpStream {
|
||||
let mut s = TcpStream::connect(addr).await.unwrap();
|
||||
// Deliberately split protocol fields across writes.
|
||||
s.write_all(&[5]).await.unwrap();
|
||||
s.write_all(&[1, 0]).await.unwrap();
|
||||
let mut reply = [0; 2];
|
||||
s.read_exact(&mut reply).await.unwrap();
|
||||
assert_eq!(reply, [5, 0]);
|
||||
s
|
||||
}
|
||||
|
||||
async fn request(s: &mut TcpStream, command: u8, target: SocketAddrV4) -> (u8, SocketAddrV4) {
|
||||
let mut bytes = vec![5, command, 0, 1];
|
||||
bytes.extend_from_slice(&target.ip().octets());
|
||||
bytes.extend_from_slice(&target.port().to_be_bytes());
|
||||
s.write_all(&bytes).await.unwrap();
|
||||
let mut reply = [0; 10];
|
||||
s.read_exact(&mut reply).await.unwrap();
|
||||
assert_eq!([reply[0], reply[2], reply[3]], [5, 0, 1]);
|
||||
(
|
||||
reply[1],
|
||||
SocketAddrV4::new(
|
||||
[reply[4], reply[5], reply[6], reply[7]].into(),
|
||||
u16::from_be_bytes([reply[8], reply[9]]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn frame(target: SocketAddrV4, payload: &[u8]) -> Vec<u8> {
|
||||
let mut bytes = vec![0, 0, 0, 1];
|
||||
bytes.extend_from_slice(&target.ip().octets());
|
||||
bytes.extend_from_slice(&target.port().to_be_bytes());
|
||||
bytes.extend_from_slice(payload);
|
||||
bytes
|
||||
}
|
||||
|
||||
async fn wait_no_sessions(bridge: &Bridge) {
|
||||
timeout(WAIT, async {
|
||||
while bridge.snapshot().active_sessions != 0 {
|
||||
sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn concurrent_tcp_udp_over_learned_subnet_and_withdrawal() {
|
||||
overlay_check(None).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "requires the built Go engine; run sh scripts/test-singbox-bridge.sh"]
|
||||
async fn singbox_to_meshport_tcp_udp_and_withdrawal() {
|
||||
let binary = std::env::var_os("MESHPORT_SINGBOX_BIN").expect("MESHPORT_SINGBOX_BIN required");
|
||||
overlay_check(Some(PathBuf::from(binary))).await;
|
||||
}
|
||||
|
||||
async fn overlay_check(engine_binary: Option<PathBuf>) {
|
||||
let port = std::net::UdpSocket::bind("127.0.0.1:0")
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
// A real remote gateway maps its advertised private subnet to an OS echo
|
||||
// server. Unlike the SDK UDP listener, this accepts unknown first packets.
|
||||
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[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config.clone()).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let network = Arc::new(
|
||||
Network::start(&config("10.253.80.11", Some(port)))
|
||||
.await
|
||||
.unwrap(),
|
||||
);
|
||||
timeout(WAIT, async {
|
||||
while !network.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r == "10.253.79.0/24")
|
||||
{
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let tcp_target: SocketAddrV4 = format!("10.253.79.1:{}", tcp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let tcp_echo = tokio::spawn(async move {
|
||||
let mut children = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
accepted = tcp.accept() => {
|
||||
let (mut s, _) = accepted.unwrap();
|
||||
children.spawn(async move {
|
||||
let mut buffer = [0; 4096];
|
||||
loop {
|
||||
let n = s.read(&mut buffer).await.unwrap();
|
||||
if n == 0 { break; }
|
||||
s.write_all(&buffer[..n]).await.unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
_ = children.join_next(), if !children.is_empty() => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let udp_target: SocketAddrV4 = format!("10.253.79.1:{}", udp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let udp_echo = tokio::spawn(async move {
|
||||
let mut buffer = [0; 65535];
|
||||
loop {
|
||||
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
||||
udp.send_to(&buffer[..n], source).await.unwrap();
|
||||
}
|
||||
});
|
||||
let mut bridge = Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
tcp_close_timeout: Duration::from_secs(1),
|
||||
..Options::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut engine = match engine_binary {
|
||||
Some(binary) => {
|
||||
Some(ExternalEngine::start(&binary, bridge.local_addr(), &network, &[]).await)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let entry = engine.as_ref().map_or(bridge.local_addr(), |e| e.listen);
|
||||
let result = timeout(Duration::from_secs(45), async {
|
||||
// An established TCP connection blocked on read does not serialize
|
||||
// the other connections or either UDP association.
|
||||
let mut idle = negotiate(entry).await;
|
||||
assert_eq!(request(&mut idle, 1, tcp_target).await.0, 0);
|
||||
let mut clients = JoinSet::new();
|
||||
for i in 0..4 {
|
||||
let addr = entry;
|
||||
clients.spawn(async move {
|
||||
let mut s = negotiate(addr).await;
|
||||
assert_eq!(request(&mut s, 1, tcp_target).await.0, 0);
|
||||
let payload = vec![i; 32768];
|
||||
s.write_all(&payload).await.unwrap();
|
||||
let mut received = vec![0; payload.len()];
|
||||
s.read_exact(&mut received).await.unwrap();
|
||||
assert_eq!(received, payload);
|
||||
s.shutdown().await.unwrap();
|
||||
});
|
||||
}
|
||||
while let Some(result) = clients.join_next().await {
|
||||
result.unwrap();
|
||||
}
|
||||
let mut associations = Vec::new();
|
||||
for payload in [b"first-session".as_slice(), b"second-session".as_slice()] {
|
||||
let local = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let mut control = negotiate(entry).await;
|
||||
let (code, relay) = request(&mut control, 3, "0.0.0.0:0".parse().unwrap()).await;
|
||||
assert_eq!(code, 0);
|
||||
local
|
||||
.send_to(&frame(udp_target, payload), relay)
|
||||
.await
|
||||
.unwrap();
|
||||
associations.push((control, local, relay, payload));
|
||||
}
|
||||
for (_, local, _, payload) in &associations {
|
||||
let mut buffer = [0; 256];
|
||||
let (n, _) = timeout(WAIT, local.recv_from(&mut buffer))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buffer[..n], frame(udp_target, payload));
|
||||
}
|
||||
// The direct bridge enforces endpoint pinning. The outer engine's
|
||||
// inbound association policy is independently owned by sing-box.
|
||||
let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let (control, local, relay, _) = associations.remove(0);
|
||||
let mut buffer = [0; 128];
|
||||
if engine.is_none() {
|
||||
intruder
|
||||
.send_to(&frame(udp_target, b"injected"), relay)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let mut fragmented = frame(udp_target, b"fragmented");
|
||||
fragmented[2] = 1;
|
||||
local.send_to(&fragmented, relay).await.unwrap();
|
||||
assert!(
|
||||
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
drop(control);
|
||||
let (remaining_control, remaining_local, remaining_relay, _) = associations.remove(0);
|
||||
drop(idle);
|
||||
if engine.is_none() {
|
||||
assert!(bridge.snapshot().dropped_udp_packets >= 2);
|
||||
}
|
||||
// Removal propagates through the real route plane. A fresh SOCKS
|
||||
// request fails rather than reaching the ordinary network.
|
||||
server_config.clear_proxy_cidrs();
|
||||
let updated =
|
||||
easytier_core::instance::CoreInstanceConfig::from_toml(&server_config).unwrap();
|
||||
server
|
||||
.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
|
||||
services: updated.connectivity.runtime,
|
||||
peer: Arc::new(updated.peer.snapshot),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
timeout(WAIT, async {
|
||||
while !network.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
{
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let mut rejected = negotiate(entry).await;
|
||||
let code = request(&mut rejected, 1, tcp_target).await.0;
|
||||
if engine.is_some() && code == 0 {
|
||||
// sing-box acknowledges SOCKS before its asynchronous outbound
|
||||
// dial. A route failure must then close, never deliver data.
|
||||
let closed = timeout(WAIT, rejected.read(&mut buffer)).await.unwrap();
|
||||
assert!(matches!(closed, Ok(0) | Err(_)));
|
||||
} else {
|
||||
assert_ne!(code, 0);
|
||||
}
|
||||
remaining_local
|
||||
.send_to(&frame(udp_target, b"after-withdrawal"), remaining_relay)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
timeout(
|
||||
Duration::from_millis(400),
|
||||
remaining_local.recv_from(&mut buffer)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
drop(remaining_control);
|
||||
drop(rejected);
|
||||
if engine.is_none() {
|
||||
wait_no_sessions(&bridge).await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
if let Some(engine) = &mut engine {
|
||||
engine.stop().await;
|
||||
}
|
||||
bridge.stop().await.unwrap();
|
||||
assert_eq!(bridge.snapshot().active_sessions, 0);
|
||||
assert!(!bridge.snapshot().running);
|
||||
assert!(TcpStream::connect(bridge.local_addr()).await.is_err());
|
||||
bridge.stop().await.unwrap();
|
||||
// Explicit stop releases the address, allowing a new bridge lifecycle.
|
||||
let mut restarted = Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
listen: bridge.local_addr(),
|
||||
..Options::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
restarted.stop().await.unwrap();
|
||||
network.stop().await;
|
||||
server.stop().await;
|
||||
tcp_echo.abort();
|
||||
udp_echo.abort();
|
||||
result.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn limits_protocol_errors_timeout_and_shutdown() {
|
||||
let network = Arc::new(Network::start(&config("10.253.82.11", None)).await.unwrap());
|
||||
assert!(
|
||||
Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
listen: "0.0.0.0:0".parse().unwrap(),
|
||||
..Options::default()
|
||||
}
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let mut bridge = Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
max_sessions: 2,
|
||||
handshake_timeout: Duration::from_millis(300),
|
||||
udp_idle_timeout: Duration::from_millis(300),
|
||||
..Options::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let result = timeout(WAIT, async {
|
||||
let mut auth = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
||||
auth.write_all(&[5, 1, 2]).await.unwrap();
|
||||
let mut selection = [0; 2];
|
||||
auth.read_exact(&mut selection).await.unwrap();
|
||||
assert_eq!(selection, [5, 255]);
|
||||
assert_eq!(auth.read(&mut [0]).await.unwrap(), 0);
|
||||
wait_no_sessions(&bridge).await;
|
||||
for (bytes, code) in [
|
||||
(&[5, 2, 0, 1][..], 7),
|
||||
(&[5, 1, 0, 3][..], 8),
|
||||
(&[5, 1, 0, 4][..], 8),
|
||||
(&[4, 1, 0, 1][..], 1),
|
||||
(&[5, 1, 1, 1][..], 1),
|
||||
] {
|
||||
let mut s = negotiate(bridge.local_addr()).await;
|
||||
s.write_all(bytes).await.unwrap();
|
||||
let mut response = [0; 10];
|
||||
s.read_exact(&mut response).await.unwrap();
|
||||
assert_eq!(response[1], code);
|
||||
assert_eq!(s.read(&mut [0]).await.unwrap(), 0);
|
||||
wait_no_sessions(&bridge).await;
|
||||
}
|
||||
let mut wrong_source = negotiate(bridge.local_addr()).await;
|
||||
assert_eq!(
|
||||
request(&mut wrong_source, 3, "127.0.0.2:1".parse().unwrap())
|
||||
.await
|
||||
.0,
|
||||
2
|
||||
);
|
||||
drop(wrong_source);
|
||||
wait_no_sessions(&bridge).await;
|
||||
let mut control = negotiate(bridge.local_addr()).await;
|
||||
assert_eq!(
|
||||
request(&mut control, 3, "0.0.0.0:0".parse().unwrap())
|
||||
.await
|
||||
.0,
|
||||
0
|
||||
);
|
||||
assert_eq!(control.read(&mut [0]).await.unwrap(), 0); // idle association expiry
|
||||
wait_no_sessions(&bridge).await;
|
||||
let mut incomplete = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
||||
incomplete.write_all(&[5]).await.unwrap();
|
||||
assert_eq!(incomplete.read(&mut [0]).await.unwrap(), 0);
|
||||
wait_no_sessions(&bridge).await;
|
||||
// Exhaust both slots with incomplete handshakes.
|
||||
let _a = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
||||
let _b = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
||||
timeout(Duration::from_millis(200), async {
|
||||
while bridge.snapshot().active_sessions < 2 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let mut rejected = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
||||
assert_eq!(rejected.read(&mut [0]).await.unwrap(), 0);
|
||||
assert_eq!(bridge.snapshot().refused_at_capacity, 1);
|
||||
bridge.stop().await.unwrap();
|
||||
assert_eq!(bridge.snapshot().active_sessions, 0);
|
||||
})
|
||||
.await;
|
||||
bridge.stop().await.unwrap();
|
||||
network.stop().await;
|
||||
result.unwrap();
|
||||
}
|
||||
|
||||
// Isolated diagnostic: no system routes, user profiles, STUN or WAN traffic.
|
||||
// Report timings rather than asserting host-dependent throughput thresholds.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "local throughput diagnostic; run release with --ignored --nocapture"]
|
||||
async fn subnet_throughput_diagnostic() {
|
||||
let trace_tcp = std::env::var_os("MESHPORT_TEST_TRACE_TCP").is_some();
|
||||
let queue_drops = Arc::new(std::sync::atomic::AtomicU64::new(0));
|
||||
if trace_tcp {
|
||||
tracing::subscriber::set_global_default(queue_drop_counter::QueueDropCounter(
|
||||
queue_drops.clone(),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
let entries =
|
||||
std::env::var("MESHPORT_TEST_ENTRIES").unwrap_or_else(|_| "sdk,socks,singbox".to_owned());
|
||||
let entries: Vec<_> = entries.split(',').collect();
|
||||
assert!(
|
||||
entries
|
||||
.iter()
|
||||
.all(|entry| matches!(*entry, "sdk" | "socks" | "singbox"))
|
||||
);
|
||||
if entries.contains(&"singbox") && std::env::var_os("MESHPORT_SINGBOX_BIN").is_none() {
|
||||
println!("singbox entry skipped: MESHPORT_SINGBOX_BIN not set");
|
||||
}
|
||||
let mib = std::env::var("MESHPORT_TEST_MIB")
|
||||
.map(|v| v.parse::<usize>().expect("size must be MiB"))
|
||||
.unwrap_or(2);
|
||||
assert!((1..=64).contains(&mib));
|
||||
let size = mib * 1024 * 1024;
|
||||
let delays = std::env::var("MESHPORT_TEST_DELAY_MS")
|
||||
.map(|v| vec![v.parse::<u64>().expect("delay must be milliseconds")])
|
||||
.unwrap_or_else(|_| vec![0, 29, 50]);
|
||||
for delay_ms in delays {
|
||||
let reserve = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
|
||||
let port = reserve.local_addr().unwrap().port();
|
||||
drop(reserve);
|
||||
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[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true\ndisable_p2p = true\nenable_encryption = true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let relay = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
|
||||
let relay_port = relay.local_addr().unwrap().port();
|
||||
// Only synthetic local test packets are inspected, using the fixture key.
|
||||
// Real user profiles and production traffic are never captured here.
|
||||
let wire_stats = Arc::new(std::sync::Mutex::new([
|
||||
wire_stats::WireStats::default(),
|
||||
wire_stats::WireStats::default(),
|
||||
]));
|
||||
let relay_stats = wire_stats.clone();
|
||||
let relay_task = tokio::spawn(async move {
|
||||
use aes_gcm::{AeadInPlace, KeyInit};
|
||||
use easytier_core::packet::{StandardAeadTail, ZCPacket, ZCPacketType};
|
||||
use std::hash::Hasher;
|
||||
// Same deterministic key derivation as the fixture's production
|
||||
// encryptor; the core encrypt module is intentionally private.
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
hasher.write(b"test-only");
|
||||
let mut key = [0u8; 16];
|
||||
key[..8].copy_from_slice(&hasher.finish().to_be_bytes());
|
||||
hasher.write(&key[..8]);
|
||||
key[8..].copy_from_slice(&hasher.finish().to_be_bytes());
|
||||
let cipher = aes_gcm::Aes128Gcm::new((&key).into());
|
||||
let remote: std::net::SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
|
||||
let mut client = None;
|
||||
let mut pending = std::collections::VecDeque::new();
|
||||
let mut packet = vec![0u8; 65536];
|
||||
loop {
|
||||
let deadline = pending
|
||||
.front()
|
||||
.map(|v: &(tokio::time::Instant, Vec<u8>, std::net::SocketAddr)| v.0)
|
||||
.unwrap_or_else(|| tokio::time::Instant::now() + Duration::from_secs(3600));
|
||||
tokio::select! {
|
||||
value = relay.recv_from(&mut packet) => {
|
||||
let (n, source) = value.unwrap();
|
||||
if trace_tcp && n >= 24 && packet[4] == 3 && packet[16] == 1 {
|
||||
let mut copy = ZCPacket::new_from_buf(bytes::BytesMut::from(&packet[..n]), ZCPacketType::UDP);
|
||||
let encrypted = copy.peer_manager_header().unwrap().is_encrypted();
|
||||
let len = copy.payload().len() - if encrypted {StandardAeadTail::SIZE} else {0};
|
||||
if encrypted {
|
||||
let tag: [u8;16] = copy.payload()[len..len+16].try_into().unwrap();
|
||||
let nonce: [u8;12] = copy.payload()[len+16..].try_into().unwrap();
|
||||
cipher.decrypt_in_place_detached((&nonce).into(), &[], &mut copy.mut_payload()[..len], (&tag).into()).unwrap();
|
||||
}
|
||||
relay_stats.lock().unwrap()[usize::from(source == remote)].record(©.payload()[..len]);
|
||||
}
|
||||
let destination = if source == remote {
|
||||
let Some(client) = client else { continue; };
|
||||
client
|
||||
} else { client = Some(source); remote };
|
||||
pending.push_back((tokio::time::Instant::now() + Duration::from_millis(delay_ms), packet[..n].to_vec(), destination));
|
||||
}
|
||||
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
|
||||
let (_, data, destination) = pending.pop_front().unwrap();
|
||||
relay.send_to(&data, destination).await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let client_config =
|
||||
config("10.253.80.11", Some(relay_port)) + "[flags]\ndisable_p2p = true\n";
|
||||
let network = Arc::new(Network::start(&client_config).await.unwrap());
|
||||
timeout(WAIT, async {
|
||||
while !network.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r == "10.253.79.0/24")
|
||||
{
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let os_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let os_port = os_listener.local_addr().unwrap().port();
|
||||
let mut sdk_listener = server.data_plane_tcp_bind(0, WAIT).await.unwrap();
|
||||
let sdk_port = sdk_listener.local_addr().port();
|
||||
let mut bridge = Bridge::start(network.clone(), Options::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let mut engine = match std::env::var_os("MESHPORT_SINGBOX_BIN") {
|
||||
Some(binary) => Some(
|
||||
ExternalEngine::start(
|
||||
Path::new(&binary),
|
||||
bridge.local_addr(),
|
||||
&network,
|
||||
&["10.253.81.2/32"],
|
||||
)
|
||||
.await,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
for (kind, target) in [
|
||||
("sdk", format!("10.253.81.2:{sdk_port}")),
|
||||
("subnet", format!("10.253.79.1:{os_port}")),
|
||||
] {
|
||||
if std::env::var("MESHPORT_TEST_TARGET").is_ok_and(|selected| selected != kind) {
|
||||
continue;
|
||||
}
|
||||
for &entry in &entries {
|
||||
if entry == "singbox" && engine.is_none() {
|
||||
continue;
|
||||
}
|
||||
for download in [true, false] {
|
||||
if trace_tcp {
|
||||
*wire_stats.lock().unwrap() = Default::default();
|
||||
queue_drops.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
let (finished, completion) = tokio::sync::oneshot::channel();
|
||||
let client = async {
|
||||
let mut socket: Box<dyn DiagnosticIo> = if entry == "sdk" {
|
||||
Box::new(
|
||||
network
|
||||
.connect_tcp(target.parse().unwrap(), WAIT)
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
} else {
|
||||
let address = if entry == "socks" {
|
||||
bridge.local_addr()
|
||||
} else {
|
||||
engine.as_ref().unwrap().listen
|
||||
};
|
||||
let mut socket = negotiate(address).await;
|
||||
assert_eq!(request(&mut socket, 1, target.parse().unwrap()).await.0, 0);
|
||||
Box::new(socket)
|
||||
};
|
||||
let payload = vec![0x5a; size];
|
||||
let start = std::time::Instant::now();
|
||||
if download {
|
||||
socket.write_all(&[1]).await.unwrap();
|
||||
let mut response = vec![0; size];
|
||||
socket.read_exact(&mut response).await.unwrap();
|
||||
assert_eq!(response, payload);
|
||||
} else {
|
||||
socket.write_all(&payload).await.unwrap();
|
||||
assert_eq!(socket.read_u8().await.unwrap(), 1);
|
||||
}
|
||||
finished.send(()).unwrap();
|
||||
println!(
|
||||
"{kind} entry={entry} added_rtt_ms={} direction={} mib={} mbps={:.2}",
|
||||
delay_ms * 2,
|
||||
if download { "download" } else { "upload" },
|
||||
mib,
|
||||
size as f64 * 8.0 / start.elapsed().as_secs_f64() / 1e6
|
||||
);
|
||||
};
|
||||
let responder = async {
|
||||
let mut socket: Box<dyn DiagnosticIo> = if kind == "sdk" {
|
||||
Box::new(sdk_listener.accept().await.unwrap().0)
|
||||
} else {
|
||||
Box::new(os_listener.accept().await.unwrap().0)
|
||||
};
|
||||
if download {
|
||||
assert_eq!(socket.read_u8().await.unwrap(), 1);
|
||||
socket.write_all(&vec![0x5a; size]).await.unwrap();
|
||||
} else {
|
||||
let mut response = vec![0; size];
|
||||
socket.read_exact(&mut response).await.unwrap();
|
||||
assert!(response.iter().all(|v| *v == 0x5a));
|
||||
socket.write_all(&[1]).await.unwrap();
|
||||
}
|
||||
completion.await.unwrap();
|
||||
};
|
||||
timeout(Duration::from_secs(60), async {
|
||||
tokio::join!(client, responder);
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if trace_tcp {
|
||||
let stats = wire_stats.lock().unwrap();
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"mode":"easytier_encrypted_relay", "target":kind,"entry":entry,
|
||||
"direction":if download {"download"} else {"upload"}, "client_wire_at_relay":stats[0].observation_json(),
|
||||
"server_wire_at_relay":stats[1].observation_json(),
|
||||
"udp_session_queue_full_drops":queue_drops.load(std::sync::atomic::Ordering::Relaxed)})
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(engine) = engine.as_mut() {
|
||||
engine.stop().await;
|
||||
}
|
||||
bridge.stop().await.unwrap();
|
||||
network.stop().await;
|
||||
server.stop().await;
|
||||
relay_task.abort();
|
||||
let _ = relay_task.await;
|
||||
}
|
||||
}
|
||||
|
||||
trait DiagnosticIo: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send {}
|
||||
impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send> DiagnosticIo for T {}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
//! Counts the existing production UDP queue-full trace event in synthetic tests.
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
};
|
||||
|
||||
pub(crate) struct QueueDropCounter(pub(crate) Arc<AtomicU64>);
|
||||
|
||||
impl tracing::Subscriber for QueueDropCounter {
|
||||
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
|
||||
metadata.target().ends_with("socket::udp::session")
|
||||
}
|
||||
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
|
||||
tracing::span::Id::from_u64(1)
|
||||
}
|
||||
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
|
||||
fn enter(&self, _: &tracing::span::Id) {}
|
||||
fn exit(&self, _: &tracing::span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
struct Visitor(bool);
|
||||
impl tracing::field::Visit for Visitor {
|
||||
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
||||
if field.name() == "message"
|
||||
&& format!("{value:?}").contains("udp session data queue full")
|
||||
{
|
||||
self.0 = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut visitor = Visitor(false);
|
||||
event.record(&mut visitor);
|
||||
if visitor.0 {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_only_udp_session_queue_full_events() {
|
||||
let count = Arc::new(AtomicU64::new(0));
|
||||
tracing::subscriber::with_default(QueueDropCounter(count.clone()), || {
|
||||
tracing::trace!(target: "easytier_core::socket::udp::session", "udp session data queue full");
|
||||
tracing::trace!(target: "easytier_core::socket::udp::session", "other session event");
|
||||
tracing::trace!(target: "other_target", "udp session data queue full");
|
||||
});
|
||||
assert_eq!(count.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
use smoltcp::wire::{Ipv4Packet, TcpPacket};
|
||||
use std::collections::HashSet;
|
||||
use tokio::time::Instant;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WireStats {
|
||||
emitted_packets: usize,
|
||||
pub(crate) received_packets: usize,
|
||||
data_packets: usize,
|
||||
repeated_sequences: usize,
|
||||
duplicate_acks: usize,
|
||||
zero_windows: usize,
|
||||
max_advertised_window: usize,
|
||||
window_scale: Option<u8>,
|
||||
last_ack: Option<i32>,
|
||||
seen: HashSet<(u16, i32, usize)>,
|
||||
last_data: Option<Instant>,
|
||||
max_data_gap_ms: u128,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_repeated_data_sequences_but_ignores_ip_fragments() {
|
||||
let mut bytes = vec![0u8; 41];
|
||||
{
|
||||
let mut ip = Ipv4Packet::new_unchecked(&mut bytes);
|
||||
ip.set_version(4);
|
||||
ip.set_header_len(20);
|
||||
ip.set_total_len(41);
|
||||
ip.set_next_header(smoltcp::wire::IpProtocol::Tcp);
|
||||
}
|
||||
{
|
||||
let mut tcp = TcpPacket::new_unchecked(&mut bytes[20..]);
|
||||
tcp.set_header_len(20);
|
||||
tcp.set_src_port(1234);
|
||||
tcp.set_dst_port(5678);
|
||||
tcp.set_seq_number(smoltcp::wire::TcpSeqNumber(100));
|
||||
tcp.set_window_len(4096);
|
||||
}
|
||||
bytes[40] = 0x5a;
|
||||
let mut stats = WireStats::default();
|
||||
stats.record(&bytes);
|
||||
stats.record(&bytes);
|
||||
assert_eq!(stats.json()["data_packets"], 2);
|
||||
assert_eq!(stats.json()["repeated_sequences"], 1);
|
||||
assert_eq!(stats.json()["max_advertised_window"], 4096);
|
||||
Ipv4Packet::new_unchecked(&mut bytes).set_more_frags(true);
|
||||
stats.record(&bytes);
|
||||
assert_eq!(stats.json()["data_packets"], 2);
|
||||
}
|
||||
|
||||
impl WireStats {
|
||||
pub(crate) fn record(&mut self, bytes: &[u8]) {
|
||||
let Ok(ip) = Ipv4Packet::new_checked(bytes) else {
|
||||
return;
|
||||
};
|
||||
if ip.next_header() != smoltcp::wire::IpProtocol::Tcp
|
||||
|| ip.frag_offset() != 0
|
||||
|| ip.more_frags()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Ok(tcp) = TcpPacket::new_checked(ip.payload()) else {
|
||||
return;
|
||||
};
|
||||
self.emitted_packets += 1;
|
||||
if tcp.syn() {
|
||||
self.window_scale = smoltcp::wire::TcpRepr::parse(
|
||||
&tcp,
|
||||
&smoltcp::wire::IpAddress::Ipv4(ip.src_addr()),
|
||||
&smoltcp::wire::IpAddress::Ipv4(ip.dst_addr()),
|
||||
&smoltcp::phy::ChecksumCapabilities::ignored(),
|
||||
)
|
||||
.unwrap()
|
||||
.window_scale;
|
||||
}
|
||||
let window = (tcp.window_len() as usize)
|
||||
<< if tcp.syn() {
|
||||
0
|
||||
} else {
|
||||
self.window_scale.unwrap_or(0)
|
||||
};
|
||||
self.max_advertised_window = self.max_advertised_window.max(window);
|
||||
if window == 0 {
|
||||
self.zero_windows += 1;
|
||||
}
|
||||
let len = tcp.payload().len();
|
||||
if len > 0 {
|
||||
self.data_packets += 1;
|
||||
if !self.seen.insert((tcp.src_port(), tcp.seq_number().0, len)) {
|
||||
self.repeated_sequences += 1;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if let Some(last) = self.last_data {
|
||||
self.max_data_gap_ms = self
|
||||
.max_data_gap_ms
|
||||
.max(now.duration_since(last).as_millis());
|
||||
}
|
||||
self.last_data = Some(now);
|
||||
} else if tcp.ack() && !tcp.syn() && !tcp.fin() {
|
||||
let ack = tcp.ack_number().0;
|
||||
if self.last_ack == Some(ack) {
|
||||
self.duplicate_acks += 1;
|
||||
}
|
||||
self.last_ack = Some(ack);
|
||||
}
|
||||
}
|
||||
pub(crate) fn observation_json(&self) -> serde_json::Value {
|
||||
let mut value = self.json();
|
||||
let map = value.as_object_mut().unwrap();
|
||||
let observed = map.remove("emitted_packets").unwrap();
|
||||
map.remove("received_packets");
|
||||
map.insert("observed_tcp_packets".to_owned(), observed);
|
||||
value
|
||||
}
|
||||
pub(crate) fn json(&self) -> serde_json::Value {
|
||||
serde_json::json!({"emitted_packets":self.emitted_packets,"received_packets":self.received_packets,
|
||||
"data_packets":self.data_packets,"repeated_sequences":self.repeated_sequences,
|
||||
"duplicate_ack_numbers":self.duplicate_acks,"zero_window_packets":self.zero_windows,
|
||||
"max_advertised_window":self.max_advertised_window,"window_scale":self.window_scale,
|
||||
"max_data_gap_ms":self.max_data_gap_ms})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
//! Native TCP-stack isolation over lossless channels or loopback UDP.
|
||||
//! Includes the production wrapper so reactor/socket behavior stays identical.
|
||||
#![allow(dead_code, unused_imports)]
|
||||
|
||||
mod foundation {
|
||||
pub mod time {
|
||||
pub use tokio::time::{Instant, sleep};
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "../../../vendor/easytier/easytier-core/src/gateway/smoltcp/tokio_smoltcp/mod.rs"]
|
||||
mod stack;
|
||||
|
||||
use smoltcp::{
|
||||
phy::{DeviceCapabilities, Medium},
|
||||
wire::{HardwareAddress, Ipv4Packet, TcpPacket},
|
||||
};
|
||||
use stack::{BufferSize, Net, NetConfig, channel_device::ChannelDevice};
|
||||
use std::{
|
||||
collections::{HashSet, VecDeque},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
sync::mpsc,
|
||||
time::{Instant, timeout},
|
||||
};
|
||||
|
||||
#[path = "support/wire_stats.rs"]
|
||||
mod wire_stats;
|
||||
use wire_stats::WireStats;
|
||||
|
||||
fn net(
|
||||
ip: &str,
|
||||
mtu: usize,
|
||||
tx_kib: usize,
|
||||
) -> (
|
||||
Net,
|
||||
mpsc::Sender<std::io::Result<Vec<u8>>>,
|
||||
mpsc::Receiver<Vec<u8>>,
|
||||
) {
|
||||
let mut caps = DeviceCapabilities::default();
|
||||
caps.medium = Medium::Ip;
|
||||
caps.max_transmission_unit = mtu;
|
||||
let (device, input, output) = ChannelDevice::new(caps);
|
||||
let config = NetConfig::new(
|
||||
smoltcp::iface::Config::new(HardwareAddress::Ip),
|
||||
format!("{ip}/24").parse().unwrap(),
|
||||
vec![],
|
||||
Some(BufferSize {
|
||||
tcp_rx_size: 1024 * 1024,
|
||||
tcp_tx_size: tx_kib * 1024,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
(Net::new(device, config), input, output)
|
||||
}
|
||||
|
||||
async fn link(
|
||||
mut output: mpsc::Receiver<Vec<u8>>,
|
||||
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
|
||||
delay: Duration,
|
||||
stats: Arc<Mutex<WireStats>>,
|
||||
) {
|
||||
let mut pending = VecDeque::new();
|
||||
loop {
|
||||
let deadline = pending
|
||||
.front()
|
||||
.map(|(at, _): &(Instant, Vec<u8>)| *at)
|
||||
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
|
||||
tokio::select! {
|
||||
packet = output.recv() => {
|
||||
let Some(packet) = packet else { return; };
|
||||
stats.lock().unwrap().record(&packet);
|
||||
pending.push_back((Instant::now() + delay, packet));
|
||||
}
|
||||
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
|
||||
let (_, packet) = pending.pop_front().unwrap();
|
||||
if input.send(Ok(packet)).await.is_err() { return; }
|
||||
stats.lock().unwrap().received_packets += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp_link(
|
||||
mut output: mpsc::Receiver<Vec<u8>>,
|
||||
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
|
||||
delay: Duration,
|
||||
stats: Arc<Mutex<WireStats>>,
|
||||
) {
|
||||
let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let destination = receiver.local_addr().unwrap();
|
||||
let sender = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let sender_stats = stats.clone();
|
||||
let _sender = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
while let Some(packet) = output.recv().await {
|
||||
sender_stats.lock().unwrap().record(&packet);
|
||||
assert_eq!(
|
||||
sender.send_to(&packet, destination).await.unwrap(),
|
||||
packet.len()
|
||||
);
|
||||
}
|
||||
}));
|
||||
let mut packet = vec![0u8; 65536];
|
||||
let mut pending = VecDeque::new();
|
||||
loop {
|
||||
let deadline = pending
|
||||
.front()
|
||||
.map(|(at, _): &(Instant, Vec<u8>)| *at)
|
||||
.unwrap_or_else(|| Instant::now() + Duration::from_secs(3600));
|
||||
tokio::select! {
|
||||
result = receiver.recv(&mut packet) => {
|
||||
let len = result.unwrap();
|
||||
stats.lock().unwrap().received_packets += 1;
|
||||
pending.push_back((Instant::now()+delay,packet[..len].to_vec()));
|
||||
}
|
||||
_ = tokio::time::sleep_until(deadline), if !pending.is_empty() => {
|
||||
let (_, packet) = pending.pop_front().unwrap();
|
||||
if input.send(Ok(packet)).await.is_err() { return; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pipe(
|
||||
udp: bool,
|
||||
output: mpsc::Receiver<Vec<u8>>,
|
||||
input: mpsc::Sender<std::io::Result<Vec<u8>>>,
|
||||
delay: Duration,
|
||||
stats: Arc<Mutex<WireStats>>,
|
||||
) {
|
||||
if udp {
|
||||
udp_link(output, input, delay, stats).await;
|
||||
} else {
|
||||
link(output, input, delay, stats).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "manual TCP stack diagnostic; run release --ignored --nocapture"]
|
||||
async fn sdk_tcp_stack_diagnostic() {
|
||||
let mib = std::env::var("MESHPORT_TEST_MIB")
|
||||
.map(|v| v.parse::<usize>().unwrap())
|
||||
.unwrap_or(2);
|
||||
assert!((1..=64).contains(&mib));
|
||||
let delay_ms = std::env::var("MESHPORT_TEST_DELAY_MS")
|
||||
.map(|v| v.parse::<u64>().unwrap())
|
||||
.unwrap_or(29);
|
||||
let mtu = std::env::var("MESHPORT_TEST_MTU")
|
||||
.map(|v| v.parse::<usize>().unwrap())
|
||||
.unwrap_or(1284);
|
||||
assert!((576..=1500).contains(&mtu));
|
||||
let tx_kib = std::env::var("MESHPORT_TEST_TX_KIB")
|
||||
.map(|v| v.parse::<usize>().unwrap())
|
||||
.unwrap_or(512);
|
||||
assert!((16..=1024).contains(&tx_kib));
|
||||
let mode = std::env::var("MESHPORT_TEST_LINK").unwrap_or_else(|_| "channel".to_owned());
|
||||
assert!(matches!(mode.as_str(), "channel" | "udp"));
|
||||
let udp = mode == "udp";
|
||||
for download in [true, false] {
|
||||
let (client, client_in, client_out) = net("10.254.90.1", mtu, tx_kib);
|
||||
let (server, server_in, server_out) = net("10.254.90.2", mtu, tx_kib);
|
||||
let client_stats = Arc::new(Mutex::new(WireStats::default()));
|
||||
let server_stats = Arc::new(Mutex::new(WireStats::default()));
|
||||
let ctask = tokio::spawn(pipe(
|
||||
udp,
|
||||
client_out,
|
||||
server_in,
|
||||
Duration::from_millis(delay_ms),
|
||||
client_stats.clone(),
|
||||
));
|
||||
let stask = tokio::spawn(pipe(
|
||||
udp,
|
||||
server_out,
|
||||
client_in,
|
||||
Duration::from_millis(delay_ms),
|
||||
server_stats.clone(),
|
||||
));
|
||||
let mut listener = server
|
||||
.tcp_bind("10.254.90.2:9000".parse().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let bytes = mib * 1024 * 1024;
|
||||
let payload = vec![0x5a; bytes];
|
||||
let transfer = async {
|
||||
let (connection, accepted) = tokio::join!(
|
||||
client.tcp_connect("10.254.90.2:9000".parse().unwrap(), 40000),
|
||||
listener.accept()
|
||||
);
|
||||
let mut c = connection.unwrap();
|
||||
let (mut s, _) = accepted.unwrap();
|
||||
let start = Instant::now();
|
||||
if download {
|
||||
let (sent, _) = tokio::join!(s.write_all(&payload), async {
|
||||
let mut b = vec![0; bytes];
|
||||
c.read_exact(&mut b).await.unwrap();
|
||||
assert_eq!(b, payload);
|
||||
});
|
||||
sent.unwrap();
|
||||
} else {
|
||||
let (sent, _) = tokio::join!(c.write_all(&payload), async {
|
||||
let mut b = vec![0; bytes];
|
||||
s.read_exact(&mut b).await.unwrap();
|
||||
assert_eq!(b, payload);
|
||||
});
|
||||
sent.unwrap();
|
||||
}
|
||||
let elapsed = start.elapsed();
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms * 2 + 100)).await;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"mode":mode,"tx_kib":tx_kib,"added_rtt_ms":delay_ms*2,"mtu":mtu,"mib":mib,
|
||||
"direction":if download {"download"} else {"upload"},"mbps":bytes as f64*8.0/elapsed.as_secs_f64()/1e6,
|
||||
"client_wire":client_stats.lock().unwrap().json(),"server_wire":server_stats.lock().unwrap().json()})
|
||||
);
|
||||
};
|
||||
let result = timeout(Duration::from_secs(90), transfer).await;
|
||||
ctask.abort();
|
||||
stask.abort();
|
||||
let _ = ctask.await;
|
||||
let _ = stask.await;
|
||||
result.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Compile the production ordering tests in the SDK workspace as well as the
|
||||
// upstream workspace, which has a separate dependency lockfile.
|
||||
#[path = "../../../vendor/easytier/easytier-core/src/peers/conn/selection.rs"]
|
||||
mod selection;
|
||||
@@ -0,0 +1,57 @@
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::TomlConfig;
|
||||
use meshport::Network;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn udp_through_adjacent_mapped_subnet() {
|
||||
let port = UdpSocket::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
|
||||
let server_config = TomlConfig::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let network = Network::start(&format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
loop {
|
||||
if network.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let echo = tokio::spawn(async move {
|
||||
let mut buffer = [0; 128];
|
||||
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
||||
udp.send_to(&buffer[..n], source).await.unwrap();
|
||||
});
|
||||
let result = network
|
||||
.probe(target, true, true, Duration::from_secs(3))
|
||||
.await;
|
||||
echo.abort();
|
||||
network.stop().await;
|
||||
server.stop().await;
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"adjacent mapped subnet UDP failed: {result:?}"
|
||||
);
|
||||
}
|
||||
+17
@@ -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
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
//! 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_easytier::{
|
||||
MeshRoutes, build_config, check_local_overlap, migrate_config, overlay_projection,
|
||||
};
|
||||
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;
|
||||
}
|
||||
/// Destinations to route through this network; changes as advertisements
|
||||
/// are accepted or withdrawn. Use instead of polling `snapshot`.
|
||||
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
|
||||
self.engine.watch_mesh_routes()
|
||||
}
|
||||
/// 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "meshport-test-server"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tokio.workspace = true
|
||||
anyhow.workspace = true
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Run on the game server; TCP/UDP echo is separate from the actual game service.
|
||||
use anyhow::Result;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, UdpSocket},
|
||||
};
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let addr = std::env::args()
|
||||
.nth(1)
|
||||
.unwrap_or_else(|| "127.0.0.1:7007".into());
|
||||
let tcp = TcpListener::bind(&addr).await?;
|
||||
let udp = UdpSocket::bind(&addr).await?;
|
||||
println!("MeshPort TCP/UDP echo listening on {addr}");
|
||||
let tcp_task = async {
|
||||
loop {
|
||||
let (mut socket, _) = tcp.accept().await?;
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 16384];
|
||||
loop {
|
||||
let n = socket.read(&mut buffer).await?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
socket.write_all(&buffer[..n]).await?;
|
||||
}
|
||||
Ok::<_, std::io::Error>(())
|
||||
});
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), std::io::Error>(())
|
||||
};
|
||||
let udp_task = async {
|
||||
let mut buffer = [0; 65535];
|
||||
loop {
|
||||
let (n, peer) = udp.recv_from(&mut buffer).await?;
|
||||
udp.send_to(&buffer[..n], peer).await?;
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), std::io::Error>(())
|
||||
};
|
||||
tokio::try_join!(tcp_task, udp_task)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "meshport-vpn-helper"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
[dependencies]
|
||||
meshport-ffi = { path = "../../crates/meshport-ffi", features = ["system-vpn"] }
|
||||
meshport-easytier.workspace = true
|
||||
serde_json.workspace = true
|
||||
anyhow.workspace = true
|
||||
libc = "0.2"
|
||||
meshport.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
# The local self-test gateway must forward its mapped subnet's UDP traffic.
|
||||
easytier = { workspace = true, features = ["proxy-packet"] }
|
||||
easytier-core.workspace = true
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Privileged test: overlay 10.253.77.0/24, advertised subnet 10.253.78.0/24, loopback.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use meshport::Network;
|
||||
use meshport_easytier::ConfigLoader;
|
||||
use std::{process::Command, time::Duration};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
fn default_route() -> Result<Vec<u8>> {
|
||||
let output = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?;
|
||||
ensure!(output.status.success(), "cannot record default route");
|
||||
Ok(output.stdout)
|
||||
}
|
||||
fn stage(value: &str) {
|
||||
use std::io::Write;
|
||||
let path = format!("/tmp/meshport-vpn-self-test-{}.log", std::process::id());
|
||||
let mut log = std::fs::OpenOptions::new().append(true).open(path).unwrap();
|
||||
writeln!(log, "{value}").unwrap();
|
||||
}
|
||||
pub fn run() -> Result<()> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o644)
|
||||
.open(format!(
|
||||
"/tmp/meshport-vpn-self-test-{}.log",
|
||||
std::process::id()
|
||||
))?;
|
||||
// Self-test must not leave privileged interfaces behind if an upstream task stalls.
|
||||
std::thread::spawn(|| {
|
||||
std::thread::sleep(Duration::from_secs(45));
|
||||
std::process::exit(2);
|
||||
});
|
||||
stage("preflight");
|
||||
tokio::runtime::Runtime::new()?.block_on(async {
|
||||
let before = default_route()?;
|
||||
let port = std::net::UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
|
||||
let identity = "[network_identity]\nnetwork_name = 'meshport-vpn-self-test'\nnetwork_secret = 'test-only'\n";
|
||||
let system_config = format!("ipv4 = '10.253.77.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}[runtime]\nmode = 'system_vpn'");
|
||||
meshport::check_local_overlap(&meshport_easytier::parse_config(&system_config)?)?;
|
||||
stage("starting application server");
|
||||
let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!(
|
||||
"ipv4 = '10.253.78.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '10.253.78.0/24'\n{identity}[flags]\nno_tun = true\nuse_smoltcp = true"
|
||||
))?;
|
||||
let server = easytier::instance::factory::create_native_instance(server_config.clone())?;
|
||||
server.start().await?;
|
||||
stage("starting system VPN");
|
||||
let vpn = match Network::start(&system_config).await { Ok(v) => v, Err(e) => { server.stop().await; return Err(e); } };
|
||||
stage("system started, collecting snapshot");
|
||||
let snapshot = vpn.snapshot().await;
|
||||
stage("snapshot ready");
|
||||
let interface = snapshot["platform_network"]["interface_name"].as_str().map(str::to_owned);
|
||||
let result = async {
|
||||
ensure!(snapshot["platform_network"]["ready"] == true, "TUN not ready");
|
||||
stage("TCP listener");
|
||||
let mut listener = server.data_plane_tcp_bind(7007, Duration::from_secs(5)).await?;
|
||||
let tcp_port = 7007;
|
||||
let echo = tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await?;
|
||||
let mut bytes = [0; 128]; let n = stream.read(&mut bytes).await?;
|
||||
stream.write_all(&bytes[..n]).await?;
|
||||
let _ = stream.read(&mut bytes).await;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
let started = std::time::Instant::now();
|
||||
while vpn.snapshot().await["peer_count"] == 0 {
|
||||
ensure!(started.elapsed() < Duration::from_secs(10), "peer discovery timeout");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
let mut routes = vpn.watch_mesh_routes();
|
||||
tokio::time::timeout(Duration::from_secs(10).saturating_sub(started.elapsed()),
|
||||
routes.wait_for(|r| r.cidrs.iter().any(|c| c == "10.253.78.0/24")))
|
||||
.await.context("advertised subnet learning timeout")??;
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
// Ordinary OS TCP socket: no MeshPort data-plane API on the client.
|
||||
let route = Command::new("/sbin/route").args(["-n", "get", "10.253.78.2"]).output()?;
|
||||
let route = String::from_utf8_lossy(&route.stdout);
|
||||
ensure!(route.lines().any(|line| line.trim() == format!("interface: {}", interface.as_deref().unwrap())), "learned subnet does not use VPN interface");
|
||||
stage("OS TCP connect via learned subnet");
|
||||
let mut tcp = tokio::net::TcpStream::connect(format!("10.253.78.2:{tcp_port}")).await?;
|
||||
tcp.write_all(b"OS TCP via utun").await?;
|
||||
let mut bytes = [0; 15]; tcp.read_exact(&mut bytes).await?;
|
||||
ensure!(&bytes == b"OS TCP via utun", "TCP echo mismatch");
|
||||
drop(tcp); echo.await??;
|
||||
stage("TCP passed, OS UDP probe");
|
||||
let udp_server = server.data_plane_udp_bind(7008, Duration::from_secs(5)).await?;
|
||||
let udp_port = 7008;
|
||||
let udp_client = tokio::net::UdpSocket::bind("10.253.77.11:0").await?;
|
||||
udp_server.send_to(b"warmup", udp_client.local_addr()?).await?;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
udp_client.send_to(b"OS UDP via utun", format!("10.253.78.2:{udp_port}")).await?;
|
||||
let mut bytes = [0; 128]; let (n, target) = udp_server.recv_from(&mut bytes).await?;
|
||||
udp_server.send_to(&bytes[..n], target).await?;
|
||||
loop {
|
||||
let (n, _) = udp_client.recv_from(&mut bytes).await?;
|
||||
if &bytes[..n] == b"warmup" { continue; }
|
||||
ensure!(&bytes[..n] == b"OS UDP via utun", "UDP echo mismatch"); break;
|
||||
}
|
||||
ensure!(default_route()? == before, "default route changed");
|
||||
stage("withdrawing advertised subnet");
|
||||
server_config.clear_proxy_cidrs();
|
||||
let config = easytier_core::instance::CoreInstanceConfig::from_toml(&server_config)?;
|
||||
server.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
|
||||
services: config.connectivity.runtime,
|
||||
peer: std::sync::Arc::new(config.peer.snapshot),
|
||||
}).await?;
|
||||
let withdrawn = std::time::Instant::now();
|
||||
loop {
|
||||
let route = Command::new("/sbin/route").args(["-n", "get", "10.253.78.2"]).output()?;
|
||||
if !String::from_utf8_lossy(&route.stdout).lines().any(|line| line.trim() == format!("interface: {}", interface.as_deref().unwrap())) { break; }
|
||||
ensure!(withdrawn.elapsed() < Duration::from_secs(12), "withdrawn route was not removed");
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
stage("withdrawal passed");
|
||||
Ok::<_, anyhow::Error>(())
|
||||
};
|
||||
let result = tokio::time::timeout(Duration::from_secs(35), result).await;
|
||||
stage("stopping VPN");
|
||||
vpn.stop().await;
|
||||
stage("VPN stopped"); server.stop().await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
if let Some(interface) = interface {
|
||||
let after = Command::new("/sbin/route").args(["-n", "get", "10.253.78.2"]).output()?;
|
||||
ensure!(!String::from_utf8_lossy(&after.stdout).lines().any(|line| line.trim() == format!("interface: {interface}")), "subnet route still uses removed interface");
|
||||
ensure!(!Command::new("/sbin/ifconfig").arg(interface).output()?.status.success(), "TUN still exists after stop");
|
||||
}
|
||||
ensure!(default_route()? == before, "default route changed after stop");
|
||||
result.context("system socket test timed out")??;
|
||||
stage("PASS");
|
||||
println!("PASS: learned subnet route → OS TCP/UDP → utun → EasyTier; withdrawn route and interface removed, default route unchanged");
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
ffi::{CStr, CString},
|
||||
io::Write,
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
};
|
||||
|
||||
// The privileged helper loads only its packaged sibling library. Go runtimes
|
||||
// cannot safely be unloaded with dlclose while their runtime threads exist.
|
||||
struct Proxy {
|
||||
handle: u64,
|
||||
call: unsafe extern "C" fn(u64, *const libc::c_char) -> *mut libc::c_char,
|
||||
free_string: unsafe extern "C" fn(*mut libc::c_char),
|
||||
free: unsafe extern "C" fn(u64),
|
||||
}
|
||||
impl Proxy {
|
||||
fn open() -> Result<Self> {
|
||||
let executable = std::env::current_exe()?.canonicalize()?;
|
||||
let path: PathBuf = executable
|
||||
.parent()
|
||||
.context("helper bundle missing")?
|
||||
.join("../Frameworks/libmeshport_proxy.dylib")
|
||||
.canonicalize()?;
|
||||
let name = CString::new(path.as_os_str().as_encoded_bytes())?;
|
||||
unsafe {
|
||||
let library = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
|
||||
ensure!(!library.is_null(), "packaged proxy library unavailable");
|
||||
fn symbol(library: *mut libc::c_void, name: &str) -> Result<*mut libc::c_void> {
|
||||
let name = CString::new(name)?;
|
||||
let symbol = unsafe { libc::dlsym(library, name.as_ptr()) };
|
||||
ensure!(!symbol.is_null(), "proxy ABI symbol unavailable");
|
||||
Ok(symbol)
|
||||
}
|
||||
let new: unsafe extern "C" fn() -> u64 =
|
||||
std::mem::transmute(symbol(library, "meshport_proxy_context_new")?);
|
||||
let version: unsafe extern "C" fn() -> u32 =
|
||||
std::mem::transmute(symbol(library, "meshport_proxy_abi_version")?);
|
||||
ensure!(version() == 1, "proxy ABI incompatible");
|
||||
let handle = new();
|
||||
ensure!(handle != 0, "proxy context unavailable");
|
||||
Ok(Self {
|
||||
handle,
|
||||
call: std::mem::transmute(symbol(library, "meshport_proxy_call")?),
|
||||
free_string: std::mem::transmute(symbol(library, "meshport_proxy_string_free")?),
|
||||
free: std::mem::transmute(symbol(library, "meshport_proxy_context_free")?),
|
||||
})
|
||||
}
|
||||
}
|
||||
fn request(&self, request: Value) -> Result<Value> {
|
||||
let encoded = request.to_string();
|
||||
ensure!(encoded.len() <= 65536, "proxy request exceeds limit");
|
||||
let encoded = CString::new(encoded)?;
|
||||
unsafe {
|
||||
let reply = (self.call)(self.handle, encoded.as_ptr());
|
||||
ensure!(!reply.is_null(), "proxy response missing");
|
||||
let parsed = serde_json::from_slice::<Value>(CStr::from_ptr(reply).to_bytes());
|
||||
(self.free_string)(reply);
|
||||
let parsed = parsed?;
|
||||
ensure!(
|
||||
parsed["ok"] == true,
|
||||
"{}",
|
||||
parsed["error"].as_str().unwrap_or("proxy engine failed")
|
||||
);
|
||||
Ok(parsed["data"].clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Proxy {
|
||||
fn drop(&mut self) {
|
||||
unsafe { (self.free)(self.handle) }
|
||||
}
|
||||
}
|
||||
|
||||
struct DnsGuard {
|
||||
child: Child,
|
||||
}
|
||||
|
||||
// Darwin IP_BOUND_IF sockets need an interface-scoped default when the TUN's
|
||||
// more-specific split defaults become the global route. Own only our new route.
|
||||
struct PhysicalRouteGuard {
|
||||
interface: String,
|
||||
gateway: std::net::Ipv4Addr,
|
||||
owned: bool,
|
||||
}
|
||||
fn route_field<'a>(text: &'a str, field: &str) -> Option<&'a str> {
|
||||
text.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(field).map(str::trim))
|
||||
}
|
||||
fn scoped_route_matches(text: &str, interface: &str, gateway: std::net::Ipv4Addr) -> bool {
|
||||
route_field(text, "interface:") == Some(interface)
|
||||
&& route_field(text, "gateway:").and_then(|value| value.parse().ok()) == Some(gateway)
|
||||
&& route_field(text, "flags:").is_some_and(|flags| flags.contains("IFSCOPE"))
|
||||
}
|
||||
impl PhysicalRouteGuard {
|
||||
fn install(interface: &str) -> Result<Self> {
|
||||
let before = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "-ifscope", interface, "default"])
|
||||
.output()?;
|
||||
ensure!(before.status.success(), "physical IPv4 gateway unavailable");
|
||||
let text = String::from_utf8(before.stdout)?;
|
||||
ensure!(
|
||||
route_field(&text, "interface:") == Some(interface),
|
||||
"physical gateway interface changed"
|
||||
);
|
||||
let gateway: std::net::Ipv4Addr = route_field(&text, "gateway:")
|
||||
.context("physical IPv4 gateway missing")?
|
||||
.parse()?;
|
||||
let mut guard = Self {
|
||||
interface: interface.into(),
|
||||
gateway,
|
||||
owned: false,
|
||||
};
|
||||
if scoped_route_matches(&text, interface, gateway) {
|
||||
return Ok(guard);
|
||||
}
|
||||
let installed = Command::new("/sbin/route")
|
||||
.args([
|
||||
"-n",
|
||||
"add",
|
||||
"-inet",
|
||||
"-ifscope",
|
||||
interface,
|
||||
"default",
|
||||
&gateway.to_string(),
|
||||
])
|
||||
.output()?;
|
||||
if !installed.status.success() {
|
||||
// Another owner may have installed it meanwhile. Reuse, never remove.
|
||||
let existing = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "-ifscope", interface, "default"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
existing.status.success()
|
||||
&& scoped_route_matches(
|
||||
&String::from_utf8_lossy(&existing.stdout),
|
||||
interface,
|
||||
gateway
|
||||
),
|
||||
"cannot protect physical IPv4 default route"
|
||||
);
|
||||
return Ok(guard);
|
||||
}
|
||||
guard.owned = true;
|
||||
let verified = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "-ifscope", interface, "default"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
verified.status.success()
|
||||
&& scoped_route_matches(
|
||||
&String::from_utf8_lossy(&verified.stdout),
|
||||
interface,
|
||||
gateway
|
||||
),
|
||||
"physical scoped route verification failed"
|
||||
);
|
||||
Ok(guard)
|
||||
}
|
||||
}
|
||||
impl Drop for PhysicalRouteGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.owned {
|
||||
return;
|
||||
}
|
||||
if let Ok(current) = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "-ifscope", &self.interface, "default"])
|
||||
.output()
|
||||
{
|
||||
if current.status.success()
|
||||
&& scoped_route_matches(
|
||||
&String::from_utf8_lossy(¤t.stdout),
|
||||
&self.interface,
|
||||
self.gateway,
|
||||
)
|
||||
{
|
||||
let _ = Command::new("/sbin/route")
|
||||
.args([
|
||||
"-n",
|
||||
"delete",
|
||||
"-inet",
|
||||
"-ifscope",
|
||||
&self.interface,
|
||||
"default",
|
||||
&self.gateway.to_string(),
|
||||
])
|
||||
.output();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl DnsGuard {
|
||||
fn install() -> Result<Self> {
|
||||
let mut child = Command::new("/usr/sbin/scutil")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
let key = format!(
|
||||
"State:/Network/Service/MeshPort-{}-Unified/DNS",
|
||||
std::process::id()
|
||||
);
|
||||
let input = child.stdin.as_mut().context("DNS control unavailable")?;
|
||||
writeln!(
|
||||
input,
|
||||
"open\nd.init\nd.add ServerAddresses * 172.19.0.2\nd.add SupplementalMatchDomains * \"\"\nd.add SupplementalMatchOrders # 1\nadd {key} temporary"
|
||||
)?;
|
||||
input.flush()?;
|
||||
let guard = Self { child };
|
||||
// Verify our exact temporary key; do not inspect or modify saved service DNS.
|
||||
for _ in 0..20 {
|
||||
let output = Command::new("/usr/sbin/scutil")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let mut output = output;
|
||||
writeln!(output.stdin.take().unwrap(), "show {key}\nquit")?;
|
||||
let response = output.wait_with_output()?;
|
||||
if String::from_utf8_lossy(&response.stdout).contains("172.19.0.2") {
|
||||
return Ok(guard);
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
anyhow::bail!("temporary system DNS registration failed")
|
||||
}
|
||||
}
|
||||
impl Drop for DnsGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut input) = self.child.stdin.take() {
|
||||
let _ = writeln!(input, "quit");
|
||||
}
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Unified {
|
||||
physical_route: Option<PhysicalRouteGuard>,
|
||||
dns: Option<DnsGuard>,
|
||||
proxy: Option<Proxy>,
|
||||
profile: Value,
|
||||
protected: BTreeSet<String>,
|
||||
active: BTreeSet<String>,
|
||||
overlay_network: Option<String>,
|
||||
physical: String,
|
||||
mesh: bool,
|
||||
running: bool,
|
||||
}
|
||||
fn physical_interface(internet: bool) -> Result<String> {
|
||||
let route = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "1.1.1.1"])
|
||||
.output()?;
|
||||
ensure!(route.status.success(), "physical route unavailable");
|
||||
let text = String::from_utf8(route.stdout)?;
|
||||
let interface = text
|
||||
.lines()
|
||||
.find_map(|line| line.trim().strip_prefix("interface:").map(str::trim))
|
||||
.context("physical interface unavailable")?;
|
||||
let interface = if interface.starts_with("utun") && !internet {
|
||||
let interfaces = Command::new("/sbin/ifconfig").arg("-l").output()?;
|
||||
let interfaces = String::from_utf8(interfaces.stdout)?;
|
||||
let physical = interfaces
|
||||
.split_whitespace()
|
||||
.filter(|name| name.starts_with("en") || name.starts_with("bridge"))
|
||||
.find(|name| {
|
||||
Command::new("/sbin/route")
|
||||
.args(["-n", "get", "-ifscope", name, "default"])
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
})
|
||||
.context("physical scoped gateway unavailable")?;
|
||||
physical.to_owned()
|
||||
} else {
|
||||
interface.to_owned()
|
||||
};
|
||||
ensure!(
|
||||
!interface.starts_with("utun") && interface != "lo0",
|
||||
"another VPN owns the default route; stop its TUN before starting internet unified VPN"
|
||||
);
|
||||
ensure!(
|
||||
interface.chars().all(|c| c.is_ascii_alphanumeric()),
|
||||
"invalid physical interface"
|
||||
);
|
||||
// Do not allow sing-tun to replace another owner's split-default routes.
|
||||
let table = Command::new("/usr/sbin/netstat").args(["-rn"]).output()?;
|
||||
let text = String::from_utf8(table.stdout)?;
|
||||
for line in text.lines().filter(|_| internet) {
|
||||
let destination = line.split_whitespace().next().unwrap_or("");
|
||||
ensure!(
|
||||
![
|
||||
"0/1",
|
||||
"128.0/1",
|
||||
"0.0.0.0/1",
|
||||
"128.0.0.0/1",
|
||||
"::/1",
|
||||
"8000::/1"
|
||||
]
|
||||
.contains(&destination),
|
||||
"split default routes already installed by another VPN"
|
||||
);
|
||||
}
|
||||
Ok(interface)
|
||||
}
|
||||
/// The SDK's canonical mesh destinations: overlay network plus accepted subnets.
|
||||
pub(super) fn prefixes(snapshot: &Value) -> Result<BTreeSet<String>> {
|
||||
snapshot["platform_network"]["mesh_cidrs"]
|
||||
.as_array()
|
||||
.context("mesh routes unavailable")?
|
||||
.iter()
|
||||
.map(|value| Ok(value.as_str().context("invalid mesh route")?.to_owned()))
|
||||
.collect()
|
||||
}
|
||||
impl Unified {
|
||||
pub fn active(&self) -> bool {
|
||||
self.running
|
||||
}
|
||||
pub fn start(&mut self, id: u64, request: &Value) -> Result<Value> {
|
||||
ensure!(!self.running, "unified VPN already started");
|
||||
self.physical = physical_interface(request["unified_profile"]["feature"] != "mesh")?;
|
||||
self.profile = request["unified_profile"].clone();
|
||||
ensure!(self.profile.is_object(), "proxy profile required");
|
||||
// Host-owned fields cannot come from client profile input.
|
||||
for field in [
|
||||
"tun",
|
||||
"desktop_tun",
|
||||
"physical_interface",
|
||||
"mesh_cidrs",
|
||||
"protected_cidrs",
|
||||
"mesh_socks",
|
||||
"listen_port",
|
||||
] {
|
||||
ensure!(
|
||||
self.profile.get(field).is_none(),
|
||||
"unexpected host-owned proxy field"
|
||||
);
|
||||
}
|
||||
self.mesh = self.profile["feature"] != "proxy";
|
||||
let physical_route = if self.profile["feature"] != "mesh" {
|
||||
Some(PhysicalRouteGuard::install(&self.physical)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.proxy = Some(Proxy::open()?);
|
||||
self.physical_route = physical_route;
|
||||
self.proxy
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.request(json!({"op":"configure_cache","directory":"/var/run"}))?;
|
||||
let result = (|| -> Result<Value> {
|
||||
let mut active = BTreeSet::new();
|
||||
if self.mesh {
|
||||
let config = request["toml"].as_str().context("configuration missing")?;
|
||||
let bridge = super::call(
|
||||
id,
|
||||
&json!({"op":"start_bridged","toml":config,
|
||||
"check_local_overlap":true,"require_static_overlay":true}),
|
||||
)?;
|
||||
ensure!(
|
||||
bridge["ok"] == true,
|
||||
"mesh startup failed: {}",
|
||||
bridge["error"].as_str().unwrap_or("unknown error")
|
||||
);
|
||||
self.profile["mesh_socks"] = bridge["data"]["listen"].clone();
|
||||
self.overlay_network = bridge["data"]["overlay"]["network"]
|
||||
.as_str()
|
||||
.map(str::to_owned);
|
||||
active = prefixes(&json!({"platform_network": bridge["data"]}))?;
|
||||
}
|
||||
self.restart(active)?;
|
||||
if self.profile["feature"] != "mesh" {
|
||||
self.dns = Some(DnsGuard::install()?);
|
||||
}
|
||||
self.running = true;
|
||||
Ok(json!({"ok":true,"data":{"started":true}}))
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = self.stop(id);
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn restart(&mut self, active: BTreeSet<String>) -> Result<()> {
|
||||
let proxy = self.proxy.as_ref().context("proxy unavailable")?;
|
||||
proxy.request(json!({"op":"stop"}))?;
|
||||
self.protected.extend(active.iter().cloned());
|
||||
let mut config = self.profile.clone();
|
||||
config["listen_port"] = json!(10818);
|
||||
config["mesh_cidrs"] = json!(active);
|
||||
config["protected_cidrs"] = json!(self.protected);
|
||||
config["desktop_tun"] = json!(true);
|
||||
config["physical_interface"] = json!(self.physical);
|
||||
proxy.request(json!({"op":"start","config":config}))?;
|
||||
self.active = active;
|
||||
Ok(())
|
||||
}
|
||||
pub fn status(&mut self, id: u64) -> Result<Value> {
|
||||
let mut snapshot = super::call(id, &json!({"op":"status"}))?["data"].clone();
|
||||
// Like Android: mesh-only has nothing left to serve once the mesh is
|
||||
// gone (the caller then stops the session); combined keeps the proxy.
|
||||
ensure!(
|
||||
self.profile["feature"] != "mesh" || snapshot["health"]["mesh_routable"] == true,
|
||||
"mesh network stopped unexpectedly"
|
||||
);
|
||||
let active = if self.mesh && snapshot["health"]["mesh_routable"] == true {
|
||||
prefixes(&snapshot)?
|
||||
} else {
|
||||
BTreeSet::new()
|
||||
};
|
||||
if active != self.active {
|
||||
self.restart(active.clone())?;
|
||||
}
|
||||
let proxy = self
|
||||
.proxy
|
||||
.as_ref()
|
||||
.context("proxy unavailable")?
|
||||
.request(json!({"op":"status"}))?;
|
||||
ensure!(proxy["state"] == "Running", "proxy stopped unexpectedly");
|
||||
snapshot["state"] = json!(if self.mesh && active.is_empty() {
|
||||
"Partial"
|
||||
} else {
|
||||
"Running"
|
||||
});
|
||||
snapshot["runtime_mode"] = json!("unified_vpn");
|
||||
snapshot["proxy"] = proxy;
|
||||
snapshot["platform_network"]["ready"] = json!(true);
|
||||
snapshot["platform_network"]["route_installation"] = json!("macos_unified_tun");
|
||||
// Same meaning on every platform: advertised subnets only, not the overlay.
|
||||
let installed: Vec<_> = self
|
||||
.active
|
||||
.iter()
|
||||
.filter(|cidr| Some(*cidr) != self.overlay_network.as_ref())
|
||||
.collect();
|
||||
snapshot["platform_network"]["installed_subnet_routes"] = json!(installed);
|
||||
snapshot["platform_network"]["protected_subnets"] = json!(self.protected);
|
||||
Ok(json!({"ok":true,"data":snapshot}))
|
||||
}
|
||||
pub fn stop(&mut self, id: u64) -> Result<()> {
|
||||
self.running = false;
|
||||
self.dns.take();
|
||||
let proxy_error = self
|
||||
.proxy
|
||||
.take()
|
||||
.and_then(|proxy| proxy.request(json!({"op":"stop"})).err());
|
||||
let network = super::call(id, &json!({"op":"stop"}));
|
||||
self.physical_route.take();
|
||||
self.protected.clear();
|
||||
self.active.clear();
|
||||
self.overlay_network = None;
|
||||
if let Some(error) = proxy_error {
|
||||
return Err(error);
|
||||
}
|
||||
network?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod route_guard_tests {
|
||||
use super::scoped_route_matches;
|
||||
#[test]
|
||||
fn only_matching_scoped_route_is_owned() {
|
||||
let gateway = "192.168.21.1".parse().unwrap();
|
||||
let original = "gateway: 192.168.21.1\ninterface: en0\nflags: <UP,GATEWAY,GLOBAL>";
|
||||
assert!(!scoped_route_matches(original, "en0", gateway));
|
||||
let scoped = original.replace("GLOBAL", "IFSCOPE");
|
||||
assert!(scoped_route_matches(&scoped, "en0", gateway));
|
||||
assert!(!scoped_route_matches(&scoped, "en1", gateway));
|
||||
assert!(!scoped_route_matches(
|
||||
&scoped,
|
||||
"en0",
|
||||
"192.168.21.2".parse().unwrap()
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
//! Real OS sockets through sing-box TUN -> Rust SOCKS -> EasyTier application stack.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
io::{Read, Write},
|
||||
net::{TcpStream, UdpSocket},
|
||||
process::Command,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
pub fn run() -> Result<()> {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let port = UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-tun-self-test'\nnetwork_secret='test-only'\n";
|
||||
let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
))?;
|
||||
let server = {
|
||||
let _entered = runtime.enter();
|
||||
easytier::instance::factory::create_native_instance(server_config)?
|
||||
};
|
||||
runtime.block_on(server.start())?;
|
||||
let id = super::ContextHandle(meshport_ffi::meshport_context_new());
|
||||
let mut unified = super::unified::Unified::default();
|
||||
let before = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout;
|
||||
let result = (|| -> Result<()> {
|
||||
let config = format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
);
|
||||
unified
|
||||
.start(
|
||||
id.0,
|
||||
&json!({"toml":config,"unified_profile":{"feature":"mesh"}}),
|
||||
)
|
||||
.context("unified startup")?;
|
||||
let deadline = Instant::now();
|
||||
loop {
|
||||
let snapshot = unified.status(id.0)?;
|
||||
if snapshot["data"]["peer_count"].as_u64().unwrap_or(0) > 0
|
||||
&& snapshot["data"]["platform_network"]["mesh_cidrs"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
deadline.elapsed() < Duration::from_secs(12),
|
||||
"peer discovery timeout"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
// PeerAdded precedes route convergence; let the overlay advertise its
|
||||
// data plane before probing an ordinary OS socket.
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
for target in ["10.253.88.2", "10.253.88.129", "172.19.0.1"] {
|
||||
let output = Command::new("/sbin/route")
|
||||
.args(["-n", "get", target])
|
||||
.output()?;
|
||||
println!(
|
||||
"self-test route {target}: {}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
}
|
||||
let interfaces = Command::new("/sbin/ifconfig").output()?;
|
||||
for block in String::from_utf8_lossy(&interfaces.stdout).split("\nutun") {
|
||||
if block.contains("inet 172.19.0.1 ") {
|
||||
println!("self-test TUN interface: {block}");
|
||||
}
|
||||
}
|
||||
let mut listener =
|
||||
runtime.block_on(server.data_plane_tcp_bind(7007, Duration::from_secs(5)))?;
|
||||
let tcp_echo = runtime.spawn(async move {
|
||||
let (mut conn, _) = listener.accept().await?;
|
||||
let mut data = [0; 128];
|
||||
let n = conn.read(&mut data).await?;
|
||||
conn.write_all(&data[..n]).await?;
|
||||
// Dropping smoltcp immediately can discard its buffered reply.
|
||||
let _ = conn.read(&mut data).await;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
// SDK UDP sockets expose outbound flows, not an inbound UDP server.
|
||||
// A mapped remote subnet exercises the real gateway used by applications.
|
||||
let udp = runtime.block_on(tokio::net::UdpSocket::bind("127.0.0.1:0"))?;
|
||||
let udp_target = format!("10.253.88.129:{}", udp.local_addr()?.port());
|
||||
let udp_echo = runtime.spawn(async move {
|
||||
let mut data = [0; 128];
|
||||
loop {
|
||||
let (n, address) = udp.recv_from(&mut data).await?;
|
||||
println!("self-test UDP server received {n} bytes from {address}");
|
||||
udp.send_to(&data[..n], address).await?;
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<_, anyhow::Error>(())
|
||||
});
|
||||
let udp_probe = super::call(
|
||||
id.0,
|
||||
&json!({"op":"probe", "target":udp_target, "protocol":"UDP", "echo":true, "timeout_ms":3000}),
|
||||
)?;
|
||||
println!("self-test native UDP probe: {udp_probe}");
|
||||
let mut tcp =
|
||||
TcpStream::connect_timeout(&"10.253.88.2:7007".parse()?, Duration::from_secs(5))
|
||||
.context("OS TCP connect")?;
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
tcp.write_all(b"unified TCP")?;
|
||||
let mut buffer = [0; 11];
|
||||
tcp.read_exact(&mut buffer).context("OS TCP echo receive")?;
|
||||
println!("PASS: OS TCP echo through unified TUN");
|
||||
ensure!(&buffer == b"unified TCP", "TCP mismatch");
|
||||
drop(tcp);
|
||||
let udp = UdpSocket::bind("0.0.0.0:0")?;
|
||||
udp.set_read_timeout(Some(Duration::from_secs(1)))?;
|
||||
let mut buffer = [0; 128];
|
||||
let mut received = None;
|
||||
for _ in 0..5 {
|
||||
udp.send_to(b"unified UDP", &udp_target)?;
|
||||
match udp.recv_from(&mut buffer) {
|
||||
Ok((n, _)) => {
|
||||
received = Some(n);
|
||||
break;
|
||||
}
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
|
||||
) =>
|
||||
{
|
||||
()
|
||||
}
|
||||
Err(e) => return Err(e).context("OS UDP echo receive"),
|
||||
}
|
||||
}
|
||||
if received.is_none() {
|
||||
println!(
|
||||
"self-test bridge counters: {}",
|
||||
super::call(id.0, &json!({"op":"socks_status"}))?
|
||||
);
|
||||
println!("self-test UDP task finished: {}", udp_echo.is_finished());
|
||||
}
|
||||
let n = received.context("OS UDP echo timed out after five probes")?;
|
||||
ensure!(&buffer[..n] == b"unified UDP", "UDP mismatch");
|
||||
udp_echo.abort();
|
||||
runtime.block_on(async {
|
||||
tcp_echo.await??;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})?;
|
||||
ensure!(
|
||||
unified.status(id.0)?["data"]["platform_network"]["ready"] == true,
|
||||
"unified status not ready"
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
eprintln!("self-test failure: {error:#}");
|
||||
}
|
||||
let stopped = unified.stop(id.0);
|
||||
runtime.block_on(server.stop());
|
||||
if let Err(error) = &stopped {
|
||||
eprintln!("self-test cleanup failure: {error:#}");
|
||||
}
|
||||
ensure!(
|
||||
Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout
|
||||
== before,
|
||||
"default route changed"
|
||||
);
|
||||
let route = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "10.253.88.2"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
!String::from_utf8_lossy(&route.stdout).contains("172.19.0.1"),
|
||||
"unified test route still installed"
|
||||
);
|
||||
let route = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "10.253.88.129"])
|
||||
.output()?;
|
||||
ensure!(
|
||||
!String::from_utf8_lossy(&route.stdout).contains("172.19.0.1"),
|
||||
"learned subnet test route still installed"
|
||||
);
|
||||
result?;
|
||||
stopped?;
|
||||
println!(
|
||||
"PASS: OS TCP/UDP -> sing-box TUN -> MeshPort SOCKS -> EasyTier; stop removed test route and preserved default route"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn desktop_tun_attached() -> bool {
|
||||
let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
|
||||
if unsafe { libc::getifaddrs(&mut head) } != 0 {
|
||||
return false;
|
||||
}
|
||||
let mut attached = false;
|
||||
let mut cursor = head;
|
||||
while !cursor.is_null() {
|
||||
let row = unsafe { &*cursor };
|
||||
if !row.ifa_addr.is_null()
|
||||
&& unsafe { (*row.ifa_addr).sa_family as i32 } == libc::AF_INET
|
||||
{
|
||||
let address = unsafe { &*(row.ifa_addr as *const libc::sockaddr_in) };
|
||||
let parsed = std::net::Ipv4Addr::from(u32::from_be(address.sin_addr.s_addr));
|
||||
if parsed == std::net::Ipv4Addr::new(172, 19, 0, 1) {
|
||||
attached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
cursor = row.ifa_next;
|
||||
}
|
||||
unsafe { libc::freeifaddrs(head) };
|
||||
attached
|
||||
}
|
||||
|
||||
fn fd_utun_name(fd: i32) -> Option<String> {
|
||||
let mut buffer = [0u8; 64];
|
||||
let mut length: libc::socklen_t = buffer.len() as u32;
|
||||
let status = unsafe {
|
||||
libc::getsockopt(
|
||||
fd,
|
||||
2, /* SYSPROTO_CONTROL */
|
||||
2, /* UTUN_OPT_IFNAME */
|
||||
buffer.as_mut_ptr() as *mut libc::c_void,
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
if status == 0 && length > 0 {
|
||||
Some(
|
||||
String::from_utf8_lossy(&buffer[..length as usize])
|
||||
.trim_matches('\0')
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// Names every live holder of the desktop TUN address: the helper's own
|
||||
// descriptors plus any spawned child that inherited a utun socket.
|
||||
fn report_desktop_tun_holders(tag: &str) {
|
||||
println!(
|
||||
"diagnostics[{tag}]: desktop TUN address attached = {}",
|
||||
desktop_tun_attached()
|
||||
);
|
||||
match std::fs::read_dir("/dev/fd") {
|
||||
Ok(entries) => {
|
||||
let mut holders = 0;
|
||||
for entry in entries.flatten() {
|
||||
let Ok(fd) = entry.file_name().to_string_lossy().parse::<i32>() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(name) = fd_utun_name(fd) {
|
||||
println!("diagnostics[{tag}]: own fd {fd} holds {name}");
|
||||
holders += 1;
|
||||
}
|
||||
}
|
||||
if holders == 0 {
|
||||
println!("diagnostics[{tag}]: no own fd holds a utun");
|
||||
}
|
||||
}
|
||||
Err(error) => println!("diagnostics[{tag}]: cannot list /dev/fd: {error}"),
|
||||
}
|
||||
let self_pid = std::process::id().to_string();
|
||||
if let Ok(output) = Command::new("/usr/bin/pgrep")
|
||||
.args(["-P", &self_pid])
|
||||
.output()
|
||||
{
|
||||
let children = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
println!("diagnostics[{tag}]: children = {children}");
|
||||
for pid in children.split_whitespace() {
|
||||
let Ok(report) = Command::new("/usr/sbin/lsof")
|
||||
.args(["-p", pid])
|
||||
.output()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for line in String::from_utf8_lossy(&report.stdout).lines() {
|
||||
if line.contains("utun") || line.contains("SYSTEM") {
|
||||
println!("diagnostics[{tag}]: child {pid}: {line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Announcement-driven rebuild under the combined feature: the proxy engine
|
||||
// must survive stop -> immediate start while DnsGuard and the physical route
|
||||
// guard are installed. This is the exact path that fails interactively.
|
||||
pub fn run_rebuild() -> Result<()> {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let port = UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-tun-self-test'\nnetwork_secret='test-only'\n";
|
||||
let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
))?;
|
||||
let server = {
|
||||
let _entered = runtime.enter();
|
||||
easytier::instance::factory::create_native_instance(server_config)?
|
||||
};
|
||||
runtime.block_on(server.start())?;
|
||||
let id = super::ContextHandle(meshport_ffi::meshport_context_new());
|
||||
let mut unified = super::unified::Unified::default();
|
||||
let before = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout;
|
||||
let profile = json!({
|
||||
"feature": "combined",
|
||||
// No bypass_cn here: its remote rule sets cannot download through the
|
||||
// synthetic dead SOCKS node; the rebuild path under test is identical.
|
||||
"default_action": "proxy",
|
||||
"rules": [],
|
||||
"dns_protection": true,
|
||||
"dns_server": "1.1.1.1",
|
||||
"proxy_dns_server": "https://1.1.1.1/dns-query",
|
||||
"rule_sets": [],
|
||||
"mesh_dns": [],
|
||||
"fakeip": false,
|
||||
"proxy": {"type": "socks", "server": "127.0.0.1", "server_port": 1},
|
||||
});
|
||||
let config = format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
);
|
||||
let result = (|| -> Result<()> {
|
||||
unified
|
||||
.start(id.0, &json!({"toml": config, "unified_profile": profile}))
|
||||
.context("unified combined startup")?;
|
||||
let deadline = Instant::now();
|
||||
loop {
|
||||
let snapshot = unified
|
||||
.status(id.0)
|
||||
.context("status poll during convergence")?;
|
||||
if snapshot["data"]["platform_network"]["installed_subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
deadline.elapsed() < Duration::from_secs(12),
|
||||
"peer discovery timeout"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
ensure!(
|
||||
desktop_tun_attached(),
|
||||
"combined mode did not attach the desktop TUN address"
|
||||
);
|
||||
println!("PASS: announcement rebuild converged in combined mode");
|
||||
// Hammer the announcement path directly: even identical prefix sets
|
||||
// stop and immediately start the proxy engine.
|
||||
for round in 1..=3 {
|
||||
let snapshot = unified.status(id.0).context("status before rebuild")?;
|
||||
let active = super::unified::prefixes(&snapshot["data"])?;
|
||||
if let Err(error) = unified.restart(active) {
|
||||
report_desktop_tun_holders("rebuild failure");
|
||||
return Err(error).context(format!("forced rebuild {round} failed"));
|
||||
}
|
||||
ensure!(
|
||||
desktop_tun_attached(),
|
||||
"desktop TUN address missing after rebuild {round}"
|
||||
);
|
||||
println!("PASS: forced rebuild {round} completed");
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
eprintln!("rebuild self-test failure: {error:#}");
|
||||
}
|
||||
let stopped = unified.stop(id.0);
|
||||
runtime.block_on(server.stop());
|
||||
let mut drained = false;
|
||||
for _ in 0..80 {
|
||||
if !desktop_tun_attached() {
|
||||
drained = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
if !drained {
|
||||
report_desktop_tun_holders("after stop");
|
||||
}
|
||||
if let Err(error) = &stopped {
|
||||
eprintln!("self-test cleanup failure: {error:#}");
|
||||
}
|
||||
ensure!(
|
||||
Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout
|
||||
== before,
|
||||
"default route changed"
|
||||
);
|
||||
result?;
|
||||
stopped?;
|
||||
ensure!(drained, "desktop TUN address retained 20s after unified stop");
|
||||
println!("PASS: combined feature survives announcement rebuilds and stops cleanly");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Development-only macOS privileged transport. No persistent root service.
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac {
|
||||
mod self_test;
|
||||
mod unified;
|
||||
mod unified_test;
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use meshport_easytier::ConfigLoader;
|
||||
use std::{
|
||||
ffi::{CStr, CString},
|
||||
io::{Read, Write},
|
||||
os::fd::AsRawFd,
|
||||
os::unix::net::UnixStream,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
static QUIT: AtomicBool = AtomicBool::new(false);
|
||||
static BUSY_SINCE: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);
|
||||
extern "C" fn signal(_: libc::c_int) {
|
||||
QUIT.store(true, Ordering::Relaxed);
|
||||
}
|
||||
struct ContextHandle(u64);
|
||||
impl Drop for ContextHandle {
|
||||
fn drop(&mut self) {
|
||||
*BUSY_SINCE.lock().unwrap() = Some(Instant::now());
|
||||
meshport_ffi::meshport_context_free(self.0);
|
||||
*BUSY_SINCE.lock().unwrap() = None;
|
||||
}
|
||||
}
|
||||
fn call(id: u64, value: &serde_json::Value) -> Result<serde_json::Value> {
|
||||
let input = CString::new(value.to_string())?;
|
||||
unsafe {
|
||||
let p = meshport_ffi::meshport_call(id, input.as_ptr());
|
||||
ensure!(!p.is_null(), "native response missing");
|
||||
let decoded = serde_json::from_slice(CStr::from_ptr(p).to_bytes());
|
||||
meshport_ffi::meshport_string_free(p);
|
||||
Ok(decoded?)
|
||||
}
|
||||
}
|
||||
// Overlap with existing interfaces is checked by the SDK when a system
|
||||
// VPN starts; the helper only refuses configurations it must not run.
|
||||
fn require_system_mode(config: &str) -> Result<()> {
|
||||
let config = meshport_easytier::parse_config(config)?;
|
||||
ensure!(
|
||||
!config.get_flags().no_tun,
|
||||
"helper accepts only system_vpn mode"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn dispatch(
|
||||
id: u64,
|
||||
unified: &mut unified::Unified,
|
||||
request: serde_json::Value,
|
||||
) -> serde_json::Value {
|
||||
let result = (|| -> Result<serde_json::Value> {
|
||||
if request["op"] == "start" && request.get("unified_profile").is_some() {
|
||||
return unified.start(id, &request);
|
||||
}
|
||||
if unified.active() {
|
||||
match request["op"].as_str() {
|
||||
Some("status") => {
|
||||
let status = unified.status(id);
|
||||
if status.is_err() {
|
||||
let _ = unified.stop(id);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
Some("stop") => {
|
||||
unified.stop(id)?;
|
||||
return Ok(serde_json::json!({"ok":true,"data":{}}));
|
||||
}
|
||||
Some("start") => bail!("unified VPN already started"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match request["op"].as_str() {
|
||||
Some("start") => {
|
||||
require_system_mode(request["toml"].as_str().context("missing toml")?)?
|
||||
}
|
||||
Some("stop" | "status" | "probe" | "validate" | "diagnostics_enable") => {}
|
||||
_ => bail!("operation unavailable in system VPN helper"),
|
||||
}
|
||||
call(id, &request)
|
||||
})();
|
||||
result.unwrap_or_else(|e| serde_json::json!({"ok": false, "error": e.to_string()}))
|
||||
}
|
||||
fn serve(id: u64, reader: &mut impl Read, writer: &mut impl Write) -> Result<()> {
|
||||
let mut unified = unified::Unified::default();
|
||||
let mut line = Vec::new();
|
||||
let mut last = Instant::now();
|
||||
loop {
|
||||
if QUIT.load(Ordering::Relaxed) || last.elapsed() > Duration::from_secs(120) {
|
||||
break;
|
||||
}
|
||||
let mut buffer = [0; 4096];
|
||||
let n = match reader.read(&mut buffer) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => n,
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
std::io::ErrorKind::WouldBlock
|
||||
| std::io::ErrorKind::TimedOut
|
||||
| std::io::ErrorKind::Interrupted
|
||||
) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
last = Instant::now();
|
||||
for b in &buffer[..n] {
|
||||
if *b != b'\n' {
|
||||
line.push(*b);
|
||||
ensure!(line.len() <= 131072, "request exceeds limit");
|
||||
continue;
|
||||
}
|
||||
let request = serde_json::from_slice(&line)?;
|
||||
line.clear();
|
||||
*BUSY_SINCE.lock().unwrap() = Some(Instant::now());
|
||||
let response = dispatch(id, &mut unified, request);
|
||||
*BUSY_SINCE.lock().unwrap() = None;
|
||||
serde_json::to_writer(&mut *writer, &response)?;
|
||||
writer.write_all(b"\n")?;
|
||||
writer.flush()?;
|
||||
}
|
||||
}
|
||||
unified.stop(id)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn run() -> Result<()> {
|
||||
ensure!(
|
||||
unsafe { libc::geteuid() } == 0,
|
||||
"administrator authorization is required"
|
||||
);
|
||||
// Upstream interface commands must resolve from system directories only.
|
||||
unsafe {
|
||||
std::env::set_var("PATH", "/usr/bin:/bin:/usr/sbin:/sbin");
|
||||
libc::signal(libc::SIGTERM, signal as *const () as libc::sighandler_t);
|
||||
libc::signal(libc::SIGINT, signal as *const () as libc::sighandler_t);
|
||||
}
|
||||
// Closing the process also closes all utun FDs if a native operation stalls.
|
||||
std::thread::spawn(|| {
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
if BUSY_SINCE
|
||||
.lock()
|
||||
.unwrap()
|
||||
.is_some_and(|at| at.elapsed() > Duration::from_secs(60))
|
||||
{
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
});
|
||||
*BUSY_SINCE.lock().unwrap() = Some(Instant::now());
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
if args == ["--self-test-unified"] {
|
||||
return unified_test::run();
|
||||
}
|
||||
if args == ["--self-test-unified-rebuild"] {
|
||||
return unified_test::run_rebuild();
|
||||
}
|
||||
if args == ["--self-test"] {
|
||||
*BUSY_SINCE.lock().unwrap() = None;
|
||||
return self_test::run();
|
||||
}
|
||||
let handle = ContextHandle(meshport_ffi::meshport_context_new());
|
||||
ensure!(handle.0 != 0, "could not create network context");
|
||||
*BUSY_SINCE.lock().unwrap() = None;
|
||||
if args == ["--stdio"] {
|
||||
return serve(handle.0, &mut std::io::stdin(), &mut std::io::stdout());
|
||||
}
|
||||
ensure!(
|
||||
args.len() == 4 && args[0] == "--socket" && args[2] == "--uid",
|
||||
"usage: meshport-vpn-helper --socket PATH --uid UID | --stdio"
|
||||
);
|
||||
let uid: libc::uid_t = args[3].parse()?;
|
||||
ensure!(uid != 0, "GUI must run as an ordinary user");
|
||||
let mut stream = UnixStream::connect(&args[1])?;
|
||||
let (mut peer_uid, mut peer_gid) = (0, 0);
|
||||
ensure!(
|
||||
unsafe { libc::getpeereid(stream.as_raw_fd(), &mut peer_uid, &mut peer_gid) } == 0
|
||||
&& peer_uid == uid,
|
||||
"unexpected control socket owner"
|
||||
);
|
||||
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let mut output = stream.try_clone()?;
|
||||
serve(handle.0, &mut stream, &mut output)
|
||||
}
|
||||
}
|
||||
fn main() {
|
||||
#[cfg(target_os = "macos")]
|
||||
if let Err(e) = mac::run() {
|
||||
eprintln!("MeshPort VPN helper: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
eprintln!("system VPN helper currently supports macOS only");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
+12521
File diff suppressed because it is too large
Load Diff
+105
@@ -0,0 +1,105 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["easytier", "easytier-core", "easytier-proto"]
|
||||
default-members = ["easytier"]
|
||||
exclude = []
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared versions and sources; members select features and optional dependencies.
|
||||
anyhow = "1.0"
|
||||
arc-swap = "1.9"
|
||||
async-trait = "0.1.92"
|
||||
atomic-shim = "0.2.0"
|
||||
auto_impl = "1.3.0"
|
||||
axum = "0.8"
|
||||
# Match pbjson 0.9's base64 dependency; upgrade together to avoid two codecs.
|
||||
base64 = "0.22.1"
|
||||
bon = "3.10.1"
|
||||
bytecodec = "0.5.0"
|
||||
bytes = "1.12.1"
|
||||
chrono = "0.4.45"
|
||||
cidr = "0.3.2"
|
||||
clap = "4.6.7"
|
||||
crossbeam = "0.8.5"
|
||||
crossbeam-utils = "0.8.23"
|
||||
dashmap = "6.2.1"
|
||||
easytier = { version = "2.7.0", path = "easytier", default-features = false }
|
||||
easytier-core = { version = "2.7.0", path = "easytier-core", default-features = false }
|
||||
easytier-ffi = { version = "0.1.0", path = "easytier-contrib/easytier-ffi", default-features = false }
|
||||
easytier-ohos-core = { version = "0.1.0", path = "easytier-contrib/easytier-ohrs/crates/easytier-ohos-core", default-features = false }
|
||||
easytier-ohos-features = { version = "0.1.0", path = "easytier-contrib/easytier-ohrs/crates/easytier-ohos-features", default-features = false }
|
||||
easytier-proto = { version = "2.7.0", path = "easytier-proto", default-features = false }
|
||||
futures = { version = "0.3", default-features = false }
|
||||
gethostname = "1.1"
|
||||
guarden = "0.3"
|
||||
# Keep HMAC/SHA2 on digest 0.10, shared by stun_codec 0.4 and snow 0.10.
|
||||
# Upgrade this crypto family together when those upstream constraints move.
|
||||
hmac = "0.12.1"
|
||||
http-body-util = "0.1"
|
||||
hyper = { version = "1", default-features = false }
|
||||
hyper-util = { version = "0.1", default-features = false }
|
||||
indoc = "2.0.7"
|
||||
log = "0.4"
|
||||
mimalloc = "*"
|
||||
once_cell = "1.21"
|
||||
parking_lot = "0.12.5"
|
||||
percent-encoding = "2.3.2"
|
||||
pin-project-lite = "0.2.17"
|
||||
prost = "0.14.4"
|
||||
prost-types = "0.14.4"
|
||||
quanta = "0.12"
|
||||
# rand 0.10 / x25519-dalek 3 require a coordinated RNG trait migration.
|
||||
rand = "0.8.8"
|
||||
reqwest = { version = "0.13.5", default-features = false }
|
||||
rust-i18n = "4"
|
||||
rustls = { version = "0.23.45", default-features = false }
|
||||
# tower-sessions-sqlx-store 0.15 requires SQLx 0.8; SeaORM 2 requires SQLx 0.9.
|
||||
sea-orm = "1.1.20"
|
||||
sea-orm-migration = "1.1.20"
|
||||
serde = "1.0.229"
|
||||
serde_json = "1.0"
|
||||
# See the HMAC constraint above; SHA2 must use the same digest generation.
|
||||
sha2 = "0.10.9"
|
||||
smoltcp = { version = "0.14.0", default-features = false }
|
||||
sqlx = "0.8.6"
|
||||
strum = "0.28.0"
|
||||
stun_codec = "0.4.0"
|
||||
sys-locale = "0.3"
|
||||
tauri = "2.11.5"
|
||||
tempfile = "3.27.0"
|
||||
thiserror = "2.0"
|
||||
thunk-rs = { git = "https://github.com/EasyTier/thunk.git", default-features = false }
|
||||
tokio = { version = "1.53", default-features = false }
|
||||
tokio-rustls = { version = "0.26", default-features = false }
|
||||
tokio-util = "0.7.19"
|
||||
toml = "1.1.6"
|
||||
tower-http = "0.7"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", default-features = false }
|
||||
url = "2.5"
|
||||
uuid = "1.26.1"
|
||||
winapi = "0.3.9"
|
||||
windows = "0.62"
|
||||
x25519-dalek = "2.0.1"
|
||||
# zerocopy 0.8 requires migrating the packet layout and casting APIs.
|
||||
zerocopy = "0.7.35"
|
||||
|
||||
[profile.dev]
|
||||
panic = "unwind"
|
||||
debug = 2
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = 3
|
||||
strip = true
|
||||
|
||||
[profile.mini]
|
||||
inherits = "release"
|
||||
opt-level = "z"
|
||||
strip = "symbols"
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
@@ -0,0 +1,27 @@
|
||||
# MeshPort vendored EasyTier
|
||||
|
||||
Source: https://github.com/EasyTier/EasyTier
|
||||
Upstream revision: 7af7bdc16a41d64d58743d15023a63b3eed2102c
|
||||
Imported using git archive. Retained LGPL-3.0 LICENSE and upstream crate sources.
|
||||
|
||||
This is a local source customization, not a published GitHub fork. Root workspace members were limited to easytier, easytier-core and easytier-proto for the SDK build. MeshPort root uses path dependencies and its own Cargo.lock.
|
||||
|
||||
Local modifications:
|
||||
- easytier-core/src/socket/udp/layer.rs: yield after batches of 32 received datagrams so session-ring consumers can run before the fixed 128-slot queues overflow during bursts. Keeps queue capacities and enqueue/drop policies unchanged. Local encrypted SDK diagnostics count queue-full events and TCP sequence repeats; live WAN validation remains pending.
|
||||
- easytier/src/common/dns.rs: resolve numeric bootstrap addresses without DNS, including when a platform socket protector is installed.
|
||||
- easytier/src/common/network.rs: macOS hardware enumeration uses blocking subprocess waits; physical connection candidates exclude route-probe addresses and nonphysical IPv6 interfaces so another VPN's TUN is not reintroduced. Hardware device names match exactly.
|
||||
- easytier-core/src/peers/meshport_optimization.rs: direct preference, improvement thresholds, hold/cooldown and candidate first-hop filter.
|
||||
- easytier-core/src/peers/mod.rs: exposes policy module.
|
||||
- easytier-core/src/peers/conn/peer_map.rs: local policy and bounded decision caches.
|
||||
- easytier-core/src/peers/conn/peer.rs and selection.rs: measured RTT precedes protocol preference; optional UDP preference breaks equal-RTT ties, unverified punched connections cannot displace verified links. Skip closed connections, resolve default selection for status/fallback.
|
||||
- easytier-core/src/peers/peer_manager.rs: policy configuration and effective next-hop inspection.
|
||||
- easytier/src/common/ifcfg/mod.rs: macOS interface commands use blocking-pool subprocess waits rather than Tokio SIGCHLD-driven waits, for embedded runtime compatibility.
|
||||
- easytier-core/src/instance/packet_plane.rs: optional host subnet filter for route projection.
|
||||
- easytier-core/src/peers/peer_manager.rs: apply the same host filter to application TCP/UDP packet destinations.
|
||||
- easytier/src/instance/virtual_nic.rs: recompute filtered route deltas on events and periodic refresh, retry failed route additions.
|
||||
- easytier/Cargo.toml and easytier/src/instance/config.rs: expose the existing core packet proxy as an independent native host capability for subnet-gateway tests, without requiring KCP/QUIC. SDK production builds do not enable it.
|
||||
- easytier-core/src/gateway/dataplane/stack.rs: data-plane TCP socket buffers raised from 128 KiB to 1 MiB receive / 512 KiB transmit, lifting the single-stream window ceiling (window / RTT). Wire format unchanged; window scaling is negotiated from buffer size.
|
||||
- easytier-core/src/gateway/smoltcp/stack.rs: user-space subnet TCP buffers raised from 16 KiB each to 1 MiB receive / 128 KiB transmit. Keeps transmit buffering below the SDK's 512 KiB after local short-download regressions with that value. Allocates about 1.125 MiB per socket, including pending handshakes. Applies on the subnet gateway running this code, not on unmodified remote EasyTier gateways.
|
||||
- Cargo.toml: reduced workspace member list.
|
||||
|
||||
No packet/protobuf wire-format modification. Do not assume mixed-version interoperability from local tests alone. Before upstream updates, compare these files against the pinned revision and rerun MeshPort real overlay and transport fallback tests. See ../../docs/optimization.md for policy limits.
|
||||
@@ -0,0 +1,178 @@
|
||||
[package]
|
||||
name = "easytier-core"
|
||||
description = "EasyTier OS-free control-plane core primitives."
|
||||
homepage = "https://github.com/EasyTier/EasyTier"
|
||||
repository = "https://github.com/EasyTier/EasyTier"
|
||||
version = "2.7.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
authors = ["kkrainbow"]
|
||||
keywords = ["vpn", "p2p", "network", "easytier"]
|
||||
categories = ["network-programming"]
|
||||
license-file = "../LICENSE"
|
||||
|
||||
[lib]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
ariadne = { version = "0.6", optional = true }
|
||||
arc-swap.workspace = true
|
||||
async-ringbuf = "0.3.9"
|
||||
async-trait.workspace = true
|
||||
auto_impl.workspace = true
|
||||
base64.workspace = true
|
||||
bitflags = "2.13"
|
||||
bytecodec.workspace = true
|
||||
bytes.workspace = true
|
||||
chrono = { workspace = true, features = ["clock"] }
|
||||
cidr = { workspace = true, features = ["serde"] }
|
||||
crossbeam-utils.workspace = true
|
||||
dashmap.workspace = true
|
||||
bon.workspace = true
|
||||
easytier-proto = { workspace = true, features = ["core"] }
|
||||
futures = { workspace = true, features = ["std", "async-await"] }
|
||||
guarden.workspace = true
|
||||
hmac.workspace = true
|
||||
http-body-util = { workspace = true, optional = true }
|
||||
hyper = { workspace = true, features = ["client", "http1"], optional = true }
|
||||
hyper-util = { workspace = true, features = ["tokio"], optional = true }
|
||||
idna = "1.1"
|
||||
atomic-shim.workspace = true
|
||||
ordered_hash_map = "0.6.1"
|
||||
parking_lot.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
petgraph = "0.8.3"
|
||||
pin-project-lite.workspace = true
|
||||
prefix-trie = { version = "0.10.1", features = ["cidr"] }
|
||||
prost.workspace = true
|
||||
prost-types.workspace = true
|
||||
rand.workspace = true
|
||||
quanta.workspace = true
|
||||
ring = { version = "0.17", optional = true }
|
||||
rustls = { workspace = true, features = ["ring", "std", "tls12"], optional = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
smoltcp = { workspace = true, optional = true }
|
||||
# All core Noise handshakes use 25519_ChaChaPoly_SHA256. Snow's std feature
|
||||
# also enables unused ring and BLAKE2 dependencies, so use its alloc support.
|
||||
snow = { version = "0.10.0", default-features = false, features = [
|
||||
"use-chacha20poly1305",
|
||||
"use-sha2",
|
||||
"use-curve25519",
|
||||
"use-getrandom",
|
||||
] }
|
||||
stun_codec.workspace = true
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
strum = { workspace = true, features = ["derive"] }
|
||||
toml.workspace = true
|
||||
tokio = { workspace = true, features = [
|
||||
"rt",
|
||||
"time",
|
||||
"sync",
|
||||
"macros",
|
||||
"io-util",
|
||||
] }
|
||||
tokio-util = { workspace = true, features = ["io", "rt"] }
|
||||
tokio-rustls = { workspace = true, optional = true }
|
||||
url = { workspace = true, features = ["serde"] }
|
||||
wildmatch = "2.6.1"
|
||||
uuid = { workspace = true, features = ["v4", "serde"] }
|
||||
webpki-roots = { version = "1.0", optional = true }
|
||||
x25519-dalek = { workspace = true, features = ["static_secrets"] }
|
||||
zerocopy = { workspace = true, features = ["derive", "simd"] }
|
||||
zstd = { version = "0.14", optional = true }
|
||||
# Match snow 0.10's AEAD generation to share aead, cipher and crypto-common.
|
||||
# Upgrade together with snow rather than pulling in a second crypto stack.
|
||||
aes-gcm = { version = "0.10.3", optional = true }
|
||||
chacha20poly1305 = { version = "0.10.1", optional = true }
|
||||
openssl = { version = "0.10", optional = true, features = ["vendored"] }
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
|
||||
getrandom-02 = { package = "getrandom", version = "0.2.17", features = ["js"] }
|
||||
getrandom-03 = { package = "getrandom", version = "0.3.4", features = ["wasm_js"] }
|
||||
ring = { version = "0.17", features = ["wasm32_unknown_unknown_js"], optional = true }
|
||||
rustls-pki-types = { version = "1.15.1", features = ["web"], optional = true }
|
||||
uuid = { workspace = true, features = ["js"] }
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
[features]
|
||||
default = ["aes-gcm", "endpoint-discovery", "extended-services", "management", "tcp-hole-punch"]
|
||||
aes-gcm = ["dep:aes-gcm"]
|
||||
browser-config = ["config-write", "easytier-proto/api", "easytier-proto/json-rpc"]
|
||||
chacha20 = ["dep:chacha20poly1305"]
|
||||
openssl-crypto = ["dep:openssl"]
|
||||
ring-crypto = ["dep:ring"]
|
||||
wasi-crypto-offload = ["ring-crypto"]
|
||||
config-write = []
|
||||
endpoint-discovery = [
|
||||
"dep:http-body-util",
|
||||
"dep:hyper",
|
||||
"dep:hyper-util",
|
||||
"dep:ring",
|
||||
"dep:rustls",
|
||||
"dep:rustls-pki-types",
|
||||
"dep:tokio-rustls",
|
||||
"dep:webpki-roots",
|
||||
]
|
||||
dhcp-ipv4 = []
|
||||
public-ipv6-provider = []
|
||||
vpn-portal = []
|
||||
wrapped-transport = []
|
||||
extended-services = [
|
||||
"dhcp-ipv4",
|
||||
"public-ipv6-provider",
|
||||
"vpn-portal",
|
||||
"wrapped-transport",
|
||||
"proxy-cidr-monitor",
|
||||
]
|
||||
web-client = ["management-rpc", "config-write"]
|
||||
management = ["web-client", "extended-services", "rich-config-errors", "easytier-proto/json-rpc"]
|
||||
management-rpc = ["easytier-proto/api"]
|
||||
proxy-cidr-monitor = []
|
||||
rich-config-errors = ["dep:ariadne"]
|
||||
tcp-hole-punch = []
|
||||
proxy-packet = [
|
||||
"wrapped-transport",
|
||||
"dep:smoltcp",
|
||||
"smoltcp/std",
|
||||
"smoltcp/proto-ipv4",
|
||||
"smoltcp/proto-ipv4-fragmentation",
|
||||
"smoltcp/fragmentation-buffer-size-65536",
|
||||
"smoltcp/assembler-max-segment-count-16",
|
||||
"smoltcp/reassembly-buffer-size-65536",
|
||||
"smoltcp/reassembly-buffer-count-16",
|
||||
]
|
||||
proxy-smoltcp-stack = [
|
||||
"proxy-packet",
|
||||
"smoltcp/medium-ip",
|
||||
"smoltcp/socket-tcp",
|
||||
"smoltcp/socket-udp",
|
||||
"smoltcp/proto-ipv6",
|
||||
"smoltcp/async",
|
||||
]
|
||||
wasm-host-tunnel = []
|
||||
wasm-host-tunnel-outbound = ["wasm-host-tunnel"]
|
||||
test-utils = []
|
||||
tracing-log = ["tracing/log"]
|
||||
zstd = ["dep:zstd"]
|
||||
|
||||
[dev-dependencies]
|
||||
futures = { workspace = true, features = ["executor"] }
|
||||
|
||||
[target.'cfg(not(target_os = "wasi"))'.dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "test-util"] }
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = [
|
||||
# Enable browser entropy backends for transitive rand/snow/AEAD dependencies.
|
||||
"getrandom-02",
|
||||
"getrandom-03",
|
||||
# Enable browser time for rustls certificate validation.
|
||||
"rustls-pki-types",
|
||||
]
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Portable conversion between the shared TOML model and management schema.
|
||||
|
||||
use easytier_proto::api::manage::{
|
||||
self, NetworkConfig, NetworkingMethod, PortForwardConfig as ApiPortForwardConfig,
|
||||
};
|
||||
|
||||
use super::{
|
||||
api_input::managed_credential_to_proto,
|
||||
toml::{ConfigLoader as _, TomlConfig},
|
||||
};
|
||||
|
||||
pub fn network_config_from_toml(config: &TomlConfig) -> NetworkConfig {
|
||||
let default_config = TomlConfig::default();
|
||||
let mut result = NetworkConfig {
|
||||
instance_id: Some(config.get_id().to_string()),
|
||||
dhcp: Some(config.get_dhcp()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if config.get_hostname() != default_config.get_hostname() {
|
||||
result.hostname = Some(config.get_hostname());
|
||||
}
|
||||
|
||||
let network_identity = config.get_network_identity();
|
||||
result.network_name = Some(network_identity.network_name);
|
||||
result.network_secret = network_identity.network_secret;
|
||||
|
||||
if let Some(ipv4) = config.get_ipv4() {
|
||||
result.virtual_ipv4 = Some(ipv4.address().to_string());
|
||||
result.network_length = Some(ipv4.network_length() as i32);
|
||||
}
|
||||
|
||||
if config.get_ipv6_public_addr_provider() != default_config.get_ipv6_public_addr_provider() {
|
||||
result.ipv6_public_addr_provider = Some(config.get_ipv6_public_addr_provider());
|
||||
}
|
||||
if config.get_ipv6_public_addr_auto() != default_config.get_ipv6_public_addr_auto() {
|
||||
result.ipv6_public_addr_auto = Some(config.get_ipv6_public_addr_auto());
|
||||
}
|
||||
result.ipv6_public_addr_prefix = config
|
||||
.get_ipv6_public_addr_prefix()
|
||||
.map(|prefix| prefix.to_string());
|
||||
|
||||
let peers = config.get_peers();
|
||||
result.networking_method = Some(NetworkingMethod::Manual as i32);
|
||||
if !peers.is_empty() {
|
||||
result.peer_urls = peers.iter().map(|peer| peer.uri.to_string()).collect();
|
||||
result.peers = peers
|
||||
.iter()
|
||||
.map(|peer| manage::NetworkPeerConfig {
|
||||
uri: peer.uri.to_string(),
|
||||
peer_public_key: peer.peer_public_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
result.listener_urls = config
|
||||
.get_listeners()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect();
|
||||
result.proxy_cidrs = config
|
||||
.get_proxy_cidrs()
|
||||
.iter()
|
||||
.map(|proxy| match proxy.mapped_cidr {
|
||||
Some(mapped) => format!("{}->{}", proxy.cidr, mapped),
|
||||
None => proxy.cidr.to_string(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let port_forwards = config.get_port_forwards();
|
||||
if !port_forwards.is_empty() {
|
||||
result.port_forwards = port_forwards
|
||||
.iter()
|
||||
.map(|forward| ApiPortForwardConfig {
|
||||
proto: forward.proto.clone(),
|
||||
bind_ip: forward.bind_addr.ip().to_string(),
|
||||
bind_port: forward.bind_addr.port() as u32,
|
||||
dst_ip: forward.dst_addr.ip().to_string(),
|
||||
dst_port: forward.dst_addr.port() as u32,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(vpn_config) = config.get_vpn_portal_config() {
|
||||
result.vpn_portal_config = Some(manage::VpnPortalConfig {
|
||||
enabled: vpn_config.enabled,
|
||||
wireguard_listen: vpn_config.wireguard_listen.to_string(),
|
||||
wireguard_private_key: vpn_config.wireguard_private_key,
|
||||
clients: vpn_config
|
||||
.clients
|
||||
.into_iter()
|
||||
.map(|client| manage::VpnPortalClientConfig {
|
||||
name: client.name,
|
||||
virtual_ip: client.virtual_ip.to_string(),
|
||||
groups: client.groups,
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(routes) = config.get_routes()
|
||||
&& !routes.is_empty()
|
||||
{
|
||||
result.enable_manual_routes = Some(true);
|
||||
result.routes = routes.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
let exit_nodes = config.get_exit_nodes();
|
||||
if !exit_nodes.is_empty() {
|
||||
result.exit_nodes = exit_nodes.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
if let Some(socks5_portal) = config.get_socks5_portal() {
|
||||
result.enable_socks5 = Some(true);
|
||||
result.socks5_port = socks5_portal.port().map(|port| port as i32);
|
||||
}
|
||||
let mapped_listeners = config.get_mapped_listeners();
|
||||
if !mapped_listeners.is_empty() {
|
||||
result.mapped_listeners = mapped_listeners.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
|
||||
result.secure_mode = config.get_secure_mode();
|
||||
result.credential_file = config
|
||||
.get_credential_file()
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
result.managed_credentials = config
|
||||
.get_managed_credentials()
|
||||
.into_iter()
|
||||
.map(managed_credential_to_proto)
|
||||
.collect();
|
||||
|
||||
let flags = config.get_flags();
|
||||
let default_flags = default_config.get_flags();
|
||||
result.latency_first = Some(flags.latency_first);
|
||||
result.dev_name = Some(flags.dev_name.clone());
|
||||
result.use_smoltcp = Some(flags.use_smoltcp);
|
||||
result.disable_ipv6 = Some(!flags.enable_ipv6);
|
||||
result.enable_kcp_proxy = Some(flags.enable_kcp_proxy);
|
||||
result.disable_kcp_input = Some(flags.disable_kcp_input);
|
||||
result.enable_quic_proxy = Some(flags.enable_quic_proxy);
|
||||
result.disable_quic_input = Some(flags.disable_quic_input);
|
||||
result.disable_p2p = Some(flags.disable_p2p);
|
||||
result.p2p_only = Some(flags.p2p_only);
|
||||
result.lazy_p2p = Some(flags.lazy_p2p);
|
||||
result.bind_device = Some(flags.bind_device);
|
||||
result.socket_mark = flags.socket_mark;
|
||||
result.no_tun = Some(flags.no_tun);
|
||||
result.enable_exit_node = Some(flags.enable_exit_node);
|
||||
result.relay_all_peer_rpc = Some(flags.relay_all_peer_rpc);
|
||||
result.need_p2p = Some(flags.need_p2p);
|
||||
result.multi_thread = Some(flags.multi_thread);
|
||||
result.proxy_forward_by_system = Some(flags.proxy_forward_by_system);
|
||||
result.disable_encryption = Some(!flags.enable_encryption);
|
||||
result.disable_tcp_hole_punching = Some(flags.disable_tcp_hole_punching);
|
||||
result.disable_udp_hole_punching = Some(flags.disable_udp_hole_punching);
|
||||
result.disable_upnp = Some(flags.disable_upnp);
|
||||
result.disable_relay_data = Some(flags.disable_relay_data);
|
||||
result.prefer_peer_relay = Some(flags.prefer_peer_relay);
|
||||
result.enable_udp_broadcast_relay = Some(flags.enable_udp_broadcast_relay);
|
||||
result.disable_sym_hole_punching = Some(flags.disable_sym_hole_punching);
|
||||
result.enable_magic_dns = Some(flags.accept_dns);
|
||||
result.mtu = Some(flags.mtu as i32);
|
||||
result.data_compress_algo = (flags.data_compress_algo != default_flags.data_compress_algo)
|
||||
.then_some(flags.data_compress_algo);
|
||||
result.encryption_algorithm = (flags.encryption_algorithm
|
||||
!= default_flags.encryption_algorithm)
|
||||
.then_some(flags.encryption_algorithm);
|
||||
result.instance_recv_bps_limit =
|
||||
(flags.instance_recv_bps_limit != u64::MAX).then_some(flags.instance_recv_bps_limit);
|
||||
result.enable_private_mode = Some(flags.private_mode);
|
||||
result.acl = config.get_acl();
|
||||
|
||||
if flags.relay_network_whitelist == "*" {
|
||||
result.enable_relay_network_whitelist = Some(false);
|
||||
} else {
|
||||
result.enable_relay_network_whitelist = Some(true);
|
||||
result.relay_network_whitelist = flags
|
||||
.relay_network_whitelist
|
||||
.split_whitespace()
|
||||
.map(ToOwned::to_owned)
|
||||
.collect();
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::toml::ManagedCredentialConfig;
|
||||
|
||||
#[test]
|
||||
fn includes_managed_credentials() {
|
||||
let config = TomlConfig::default();
|
||||
config.set_managed_credentials(vec![ManagedCredentialConfig {
|
||||
credential_id: "managed-a".to_owned(),
|
||||
credential_secret: "credential-secret".to_owned(),
|
||||
groups: vec!["ops".to_owned()],
|
||||
allow_relay: true,
|
||||
allowed_proxy_cidrs: vec!["10.0.0.0/24".to_owned()],
|
||||
expiry_unix: 2_000_000_000,
|
||||
reusable: false,
|
||||
}]);
|
||||
|
||||
let projected = network_config_from_toml(&config);
|
||||
|
||||
assert_eq!(
|
||||
projected.managed_credentials,
|
||||
vec![manage::ManagedCredentialConfig {
|
||||
credential_id: "managed-a".to_owned(),
|
||||
credential_secret: "credential-secret".to_owned(),
|
||||
groups: vec!["ops".to_owned()],
|
||||
allow_relay: true,
|
||||
allowed_proxy_cidrs: vec!["10.0.0.0/24".to_owned()],
|
||||
expiry_unix: 2_000_000_000,
|
||||
reusable: Some(false),
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use super::{
|
||||
api_input::{NetworkConfig, NetworkConfigExt, merge_network_config_toml},
|
||||
toml::{ConfigLoader, TomlConfig},
|
||||
};
|
||||
|
||||
fn js_error(error: impl std::fmt::Debug) -> JsValue {
|
||||
JsValue::from_str(&format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn generate_config(config_json: &str) -> Result<String, JsValue> {
|
||||
let config: NetworkConfig = serde_json::from_str(config_json).map_err(js_error)?;
|
||||
config
|
||||
.gen_config()
|
||||
.map(|config| config.dump())
|
||||
.map_err(js_error)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn merge_config(original_toml: &str, config_json: &str) -> Result<String, JsValue> {
|
||||
let config: NetworkConfig = serde_json::from_str(config_json).map_err(js_error)?;
|
||||
merge_network_config_toml(original_toml, &config).map_err(js_error)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn parse_config(toml_config: &str) -> Result<String, JsValue> {
|
||||
let config = TomlConfig::new_from_str(toml_config)
|
||||
.and_then(|config| NetworkConfig::new_from_config(&config))
|
||||
.map_err(js_error)?;
|
||||
serde_json::to_string(&config).map_err(js_error)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use std::{fmt, str::FromStr};
|
||||
|
||||
use strum::VariantArray;
|
||||
|
||||
/// Stable configuration vocabulary for every known encryption algorithm.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, VariantArray)]
|
||||
pub enum EncryptionAlgorithm {
|
||||
Xor,
|
||||
#[default]
|
||||
AesGcm,
|
||||
Aes256Gcm,
|
||||
ChaCha20,
|
||||
}
|
||||
|
||||
impl EncryptionAlgorithm {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Xor => "xor",
|
||||
Self::AesGcm => "aes-gcm",
|
||||
Self::Aes256Gcm => "aes-256-gcm",
|
||||
Self::ChaCha20 => "chacha20",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EncryptionAlgorithm {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for EncryptionAlgorithm {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"xor" => Ok(Self::Xor),
|
||||
"aes-gcm" | "openssl-aes-gcm" => Ok(Self::AesGcm),
|
||||
"aes-256-gcm" | "openssl-aes-256-gcm" => Ok(Self::Aes256Gcm),
|
||||
"chacha20" | "chacha20-poly1305" | "openssl-chacha20" => Ok(Self::ChaCha20),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_algorithm_names_are_stable() {
|
||||
let cases = [
|
||||
("xor", EncryptionAlgorithm::Xor),
|
||||
("aes-gcm", EncryptionAlgorithm::AesGcm),
|
||||
("aes-256-gcm", EncryptionAlgorithm::Aes256Gcm),
|
||||
("chacha20", EncryptionAlgorithm::ChaCha20),
|
||||
("chacha20-poly1305", EncryptionAlgorithm::ChaCha20),
|
||||
("openssl-aes-gcm", EncryptionAlgorithm::AesGcm),
|
||||
("openssl-aes-256-gcm", EncryptionAlgorithm::Aes256Gcm),
|
||||
("openssl-chacha20", EncryptionAlgorithm::ChaCha20),
|
||||
];
|
||||
|
||||
for (name, expected) in cases {
|
||||
assert_eq!(name.parse(), Ok(expected));
|
||||
}
|
||||
assert_eq!(EncryptionAlgorithm::ChaCha20.to_string(), "chacha20");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aes_is_the_stable_default() {
|
||||
assert_eq!(EncryptionAlgorithm::default(), EncryptionAlgorithm::AesGcm);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use easytier_proto::common::{PortForwardConfigPb, SocketType};
|
||||
|
||||
/// Runtime configuration for the core-owned SOCKS and port-forward gateway.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GatewayRuntimeConfig {
|
||||
pub socks5_bind: Option<SocketAddr>,
|
||||
pub port_forwards: Vec<PortForwardConfig>,
|
||||
}
|
||||
|
||||
/// One TCP or UDP port-forward rule.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct PortForwardConfig {
|
||||
pub bind_addr: SocketAddr,
|
||||
pub dst_addr: SocketAddr,
|
||||
pub proto: String,
|
||||
}
|
||||
|
||||
impl From<PortForwardConfigPb> for PortForwardConfig {
|
||||
fn from(config: PortForwardConfigPb) -> Self {
|
||||
Self {
|
||||
bind_addr: config.bind_addr.unwrap_or_default().into(),
|
||||
dst_addr: config.dst_addr.unwrap_or_default().into(),
|
||||
proto: match SocketType::try_from(config.socket_type) {
|
||||
Ok(SocketType::Tcp) => "tcp".to_string(),
|
||||
Ok(SocketType::Udp) => "udp".to_string(),
|
||||
_ => "tcp".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PortForwardConfig> for PortForwardConfigPb {
|
||||
fn from(config: PortForwardConfig) -> Self {
|
||||
Self {
|
||||
bind_addr: Some(config.bind_addr.into()),
|
||||
dst_addr: Some(config.dst_addr.into()),
|
||||
socket_type: match config.proto.to_lowercase().as_str() {
|
||||
"tcp" => SocketType::Tcp as i32,
|
||||
"udp" => SocketType::Udp as i32,
|
||||
_ => SocketType::Tcp as i32,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProxyRuntimeConfig {
|
||||
pub enable_exit_node: bool,
|
||||
pub no_tun: bool,
|
||||
pub forward_by_system: bool,
|
||||
pub force_smoltcp: bool,
|
||||
pub icmp_failure_is_fatal: bool,
|
||||
pub udp_response_ipv4_mtu: usize,
|
||||
}
|
||||
|
||||
impl ProxyRuntimeConfig {
|
||||
pub fn should_start(self, has_proxy_networks: bool) -> bool {
|
||||
if !has_proxy_networks && !self.enable_exit_node && !self.no_tun {
|
||||
return false;
|
||||
}
|
||||
|
||||
!self.forward_by_system || self.no_tun
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ProxyRuntimeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enable_exit_node: false,
|
||||
no_tun: false,
|
||||
forward_by_system: false,
|
||||
force_smoltcp: false,
|
||||
icmp_failure_is_fatal: false,
|
||||
udp_response_ipv4_mtu: 1280,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ProxyRuntimeConfig;
|
||||
|
||||
#[test]
|
||||
fn proxy_startup_policy_preserves_runtime_modes() {
|
||||
assert!(!ProxyRuntimeConfig::default().should_start(false));
|
||||
assert!(ProxyRuntimeConfig::default().should_start(true));
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
enable_exit_node: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_startup_policy_preserves_system_forwarding_rules() {
|
||||
assert!(
|
||||
!ProxyRuntimeConfig {
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(true)
|
||||
);
|
||||
assert!(
|
||||
!ProxyRuntimeConfig {
|
||||
enable_exit_node: true,
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
no_tun: true,
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_runtime_defaults_preserve_udp_mtu() {
|
||||
assert_eq!(ProxyRuntimeConfig::default().udp_response_ipv4_mtu, 1280);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
//! Static configuration schema plus the live runtime configuration store.
|
||||
|
||||
#[cfg(feature = "web-client")]
|
||||
pub mod api;
|
||||
#[cfg(any(feature = "web-client", feature = "browser-config"))]
|
||||
pub mod api_input;
|
||||
#[cfg(all(
|
||||
feature = "browser-config",
|
||||
target_arch = "wasm32",
|
||||
target_os = "unknown"
|
||||
))]
|
||||
mod browser;
|
||||
mod encryption;
|
||||
pub mod gateway;
|
||||
pub mod peers;
|
||||
pub mod runtime;
|
||||
pub mod toml;
|
||||
|
||||
pub use encryption::EncryptionAlgorithm;
|
||||
|
||||
pub(crate) const DEFAULT_UDP_STUN_SERVERS: &[&str] = &[
|
||||
"txt:stun.easytier.cn",
|
||||
"stun.miwifi.com",
|
||||
"stun.chat.bilibili.com",
|
||||
"stun.hitv.com",
|
||||
];
|
||||
pub(crate) const DEFAULT_TCP_STUN_SERVERS: &[&str] = &[
|
||||
"stun.hot-chilli.net",
|
||||
"stun.fitauto.ru",
|
||||
"fwa.lifesizecloud.com",
|
||||
"global.turn.twilio.com",
|
||||
"turn.cloudflare.com",
|
||||
"stun.voip.blackberry.com",
|
||||
"stun.radiojar.com",
|
||||
];
|
||||
pub(crate) const DEFAULT_UDP_V6_STUN_SERVERS: &[&str] = &["txt:stun-v6.easytier.cn"];
|
||||
|
||||
pub(crate) fn default_stun_servers(servers: &[&str]) -> Vec<String> {
|
||||
servers.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
use std::{
|
||||
collections::{BTreeSet, hash_map::DefaultHasher},
|
||||
hash::{Hash, Hasher},
|
||||
net::IpAddr,
|
||||
};
|
||||
|
||||
use anyhow::Context as _;
|
||||
use base64::{Engine as _, prelude::BASE64_STANDARD};
|
||||
use easytier_proto::{common as common_pb, core_config as pb};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
pub type PeerId = u32;
|
||||
|
||||
pub type NetworkSecretDigest = [u8; 32];
|
||||
|
||||
/// Host capabilities used by the portable mapped-listener validation rule.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct MappedListenerPolicy {
|
||||
implicit_port_schemes: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl MappedListenerPolicy {
|
||||
pub fn new<I, S>(implicit_port_schemes: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Into<String>,
|
||||
{
|
||||
Self {
|
||||
implicit_port_schemes: implicit_port_schemes
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.map(|scheme: String| scheme.to_ascii_lowercase())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self, url: &Url) -> anyhow::Result<()> {
|
||||
if url.port().is_none() && !self.implicit_port_schemes.contains(url.scheme()) {
|
||||
anyhow::bail!("mapped listener port is missing: {}", url);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_urls(&self, mapped_listeners: &[String]) -> anyhow::Result<Vec<Url>> {
|
||||
mapped_listeners
|
||||
.iter()
|
||||
.map(|value| {
|
||||
let url: Url = value
|
||||
.parse()
|
||||
.with_context(|| format!("mapped listener is not a valid url: {}", value))?;
|
||||
self.validate(&url)?;
|
||||
Ok(url)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Completes and validates the portable secure-mode key configuration.
|
||||
pub fn normalize_secure_mode_config(
|
||||
mut config: common_pb::SecureModeConfig,
|
||||
) -> anyhow::Result<common_pb::SecureModeConfig> {
|
||||
if !config.enabled {
|
||||
return Ok(config);
|
||||
}
|
||||
|
||||
let private_key = if config.local_private_key.is_none() {
|
||||
let private = x25519_dalek::StaticSecret::random_from_rng(rand::rngs::OsRng);
|
||||
config.local_private_key = Some(BASE64_STANDARD.encode(private.as_bytes()));
|
||||
private
|
||||
} else {
|
||||
config.private_key()?
|
||||
};
|
||||
let generated_public_key = x25519_dalek::PublicKey::from(&private_key);
|
||||
let generated_public_key = BASE64_STANDARD.encode(generated_public_key.as_bytes());
|
||||
|
||||
match config.local_public_key.as_ref() {
|
||||
None => config.local_public_key = Some(generated_public_key),
|
||||
Some(configured_public_key) => {
|
||||
config.public_key()?;
|
||||
if configured_public_key != &generated_public_key {
|
||||
anyhow::bail!(
|
||||
"local public key {} does not match generated public key {}",
|
||||
configured_public_key,
|
||||
generated_public_key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NetworkIdentity {
|
||||
pub network_name: String,
|
||||
pub network_secret: Option<String>,
|
||||
pub network_secret_digest: Option<NetworkSecretDigest>,
|
||||
}
|
||||
|
||||
impl NetworkIdentity {
|
||||
pub fn new(network_name: String, network_secret: String) -> Self {
|
||||
Self {
|
||||
network_secret_digest: Some(network_secret_digest(&network_name, &network_secret)),
|
||||
network_name,
|
||||
network_secret: Some(network_secret),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_credential(network_name: String) -> Self {
|
||||
Self {
|
||||
network_name,
|
||||
network_secret: None,
|
||||
network_secret_digest: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn secret_digest(&self) -> Option<NetworkSecretDigest> {
|
||||
if self.network_secret_digest.is_some() {
|
||||
self.network_secret_digest
|
||||
} else if let Some(network_secret) = &self.network_secret {
|
||||
let mut network_secret_digest = [0u8; 32];
|
||||
generate_digest_from_str(
|
||||
&self.network_name,
|
||||
network_secret,
|
||||
&mut network_secret_digest,
|
||||
);
|
||||
Some(network_secret_digest)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_secret_digest(mut self) -> Self {
|
||||
self.network_secret_digest = self.secret_digest();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Hash)]
|
||||
struct NetworkIdentityWithOnlyDigest {
|
||||
network_name: String,
|
||||
network_secret_digest: Option<NetworkSecretDigest>,
|
||||
}
|
||||
|
||||
fn generate_digest_from_str(str1: &str, str2: &str, digest: &mut [u8]) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(str1.as_bytes());
|
||||
hasher.write(str2.as_bytes());
|
||||
|
||||
assert_eq!(digest.len() % 8, 0, "digest length must be multiple of 8");
|
||||
|
||||
let shard_count = digest.len() / 8;
|
||||
for i in 0..shard_count {
|
||||
digest[i * 8..(i + 1) * 8].copy_from_slice(&hasher.finish().to_be_bytes());
|
||||
hasher.write(&digest[..(i + 1) * 8]);
|
||||
}
|
||||
}
|
||||
|
||||
fn network_secret_digest(network_name: &str, network_secret: &str) -> NetworkSecretDigest {
|
||||
let mut digest = [0u8; 32];
|
||||
generate_digest_from_str(network_name, network_secret, &mut digest);
|
||||
digest
|
||||
}
|
||||
|
||||
impl From<NetworkIdentity> for NetworkIdentityWithOnlyDigest {
|
||||
fn from(identity: NetworkIdentity) -> Self {
|
||||
Self {
|
||||
network_secret_digest: identity.secret_digest(),
|
||||
network_name: identity.network_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for NetworkIdentity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let self_with_digest = NetworkIdentityWithOnlyDigest::from(self.clone());
|
||||
let other_with_digest = NetworkIdentityWithOnlyDigest::from(other.clone());
|
||||
self_with_digest == other_with_digest
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for NetworkIdentity {}
|
||||
|
||||
impl Hash for NetworkIdentity {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
let self_with_digest = NetworkIdentityWithOnlyDigest::from(self.clone());
|
||||
self_with_digest.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NetworkIdentity {
|
||||
fn default() -> Self {
|
||||
Self::new("default".to_string(), "".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct CoreConfig {
|
||||
pub node: NodeConfig,
|
||||
pub routes: RouteConfig,
|
||||
pub peer_policy: PeerPolicyConfig,
|
||||
pub traffic: TrafficConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct NodeConfig {
|
||||
pub peer_id: Option<PeerId>,
|
||||
pub instance_id: Option<[u8; 16]>,
|
||||
pub hostname: Option<String>,
|
||||
pub network_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct RouteConfig {
|
||||
pub ipv4: Option<IpPrefix>,
|
||||
pub ipv6: Option<IpPrefix>,
|
||||
pub advertised_routes: Vec<IpPrefix>,
|
||||
pub proxy_networks: Vec<ProxyNetworkConfig>,
|
||||
pub foreign_networks: Vec<ForeignNetworkConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct IpPrefix {
|
||||
pub address: IpAddr,
|
||||
pub prefix_len: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProxyNetworkConfig {
|
||||
pub real: IpPrefix,
|
||||
pub mapped: Option<IpPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ForeignNetworkConfig {
|
||||
pub name: String,
|
||||
pub cidrs: Vec<IpPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerPolicyConfig {
|
||||
pub p2p_enabled: bool,
|
||||
pub relay_peer_rpc: bool,
|
||||
pub relay_data: bool,
|
||||
pub latency_first: bool,
|
||||
pub encryption_required: bool,
|
||||
}
|
||||
|
||||
impl Default for PeerPolicyConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
p2p_enabled: true,
|
||||
relay_peer_rpc: false,
|
||||
relay_data: true,
|
||||
latency_first: false,
|
||||
encryption_required: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct P2pPolicyFlags {
|
||||
pub disable_udp_hole_punching: bool,
|
||||
pub disable_sym_hole_punching: bool,
|
||||
pub disable_upnp: bool,
|
||||
pub lazy_p2p: bool,
|
||||
pub disable_p2p: bool,
|
||||
pub need_p2p: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct TrafficConfig {
|
||||
pub mtu: Option<u16>,
|
||||
pub instance_recv_bps_limit: Option<u64>,
|
||||
pub foreign_relay_bps_limit: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("missing required field: {0}")]
|
||||
MissingField(&'static str),
|
||||
#[error("invalid IPv4 prefix length: {0}")]
|
||||
InvalidIpv4Prefix(u8),
|
||||
#[error("invalid IPv6 prefix length: {0}")]
|
||||
InvalidIpv6Prefix(u8),
|
||||
#[error("invalid MTU: {0}")]
|
||||
InvalidMtu(u32),
|
||||
}
|
||||
|
||||
impl IpPrefix {
|
||||
pub fn new(address: IpAddr, prefix_len: u8) -> Result<Self, ConfigError> {
|
||||
match address {
|
||||
IpAddr::V4(_) if prefix_len <= 32 => Ok(Self {
|
||||
address,
|
||||
prefix_len,
|
||||
}),
|
||||
IpAddr::V4(_) => Err(ConfigError::InvalidIpv4Prefix(prefix_len)),
|
||||
IpAddr::V6(_) if prefix_len <= 128 => Ok(Self {
|
||||
address,
|
||||
prefix_len,
|
||||
}),
|
||||
IpAddr::V6(_) => Err(ConfigError::InvalidIpv6Prefix(prefix_len)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::CoreConfig> for CoreConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::CoreConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
node: value
|
||||
.node
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
routes: value
|
||||
.routes
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
peer_policy: value.peer_policy.map(Into::into).unwrap_or_default(),
|
||||
traffic: value
|
||||
.traffic
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CoreConfig> for pb::CoreConfig {
|
||||
fn from(value: CoreConfig) -> Self {
|
||||
Self {
|
||||
node: Some(value.node.into()),
|
||||
routes: Some(value.routes.into()),
|
||||
peer_policy: Some(value.peer_policy.into()),
|
||||
traffic: Some(value.traffic.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::NodeConfig> for NodeConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::NodeConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
peer_id: value.peer_id,
|
||||
instance_id: value.instance_id.map(uuid_to_bytes),
|
||||
hostname: value.hostname,
|
||||
network_name: value.network_name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<NodeConfig> for pb::NodeConfig {
|
||||
fn from(value: NodeConfig) -> Self {
|
||||
Self {
|
||||
peer_id: value.peer_id,
|
||||
instance_id: value.instance_id.map(uuid_from_bytes),
|
||||
hostname: value.hostname,
|
||||
network_name: value.network_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::RouteConfig> for RouteConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::RouteConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
ipv4: value.ipv4.map(TryInto::try_into).transpose()?,
|
||||
ipv6: value.ipv6.map(TryInto::try_into).transpose()?,
|
||||
advertised_routes: value
|
||||
.advertised_routes
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
proxy_networks: value
|
||||
.proxy_networks
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
foreign_networks: value
|
||||
.foreign_networks
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RouteConfig> for pb::RouteConfig {
|
||||
fn from(value: RouteConfig) -> Self {
|
||||
Self {
|
||||
ipv4: value.ipv4.map(Into::into),
|
||||
ipv6: value.ipv6.map(Into::into),
|
||||
advertised_routes: value
|
||||
.advertised_routes
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
proxy_networks: value.proxy_networks.into_iter().map(Into::into).collect(),
|
||||
foreign_networks: value.foreign_networks.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::IpPrefix> for IpPrefix {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::IpPrefix) -> Result<Self, Self::Error> {
|
||||
let address = pb_ip_addr_to_std(
|
||||
value
|
||||
.address
|
||||
.ok_or(ConfigError::MissingField("IpPrefix.address"))?,
|
||||
)?;
|
||||
let prefix_len = u8::try_from(value.prefix_len)
|
||||
.map_err(|_| invalid_prefix_for_address(address, value.prefix_len))?;
|
||||
Self::new(address, prefix_len)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<IpPrefix> for pb::IpPrefix {
|
||||
fn from(value: IpPrefix) -> Self {
|
||||
Self {
|
||||
address: Some(value.address.into()),
|
||||
prefix_len: value.prefix_len.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::ProxyNetworkConfig> for ProxyNetworkConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::ProxyNetworkConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
real: value
|
||||
.real
|
||||
.ok_or(ConfigError::MissingField("ProxyNetworkConfig.real"))?
|
||||
.try_into()?,
|
||||
mapped: value.mapped.map(TryInto::try_into).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProxyNetworkConfig> for pb::ProxyNetworkConfig {
|
||||
fn from(value: ProxyNetworkConfig) -> Self {
|
||||
Self {
|
||||
real: Some(value.real.into()),
|
||||
mapped: value.mapped.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::ForeignNetworkConfig> for ForeignNetworkConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::ForeignNetworkConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
name: value.name,
|
||||
cidrs: value
|
||||
.cidrs
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ForeignNetworkConfig> for pb::ForeignNetworkConfig {
|
||||
fn from(value: ForeignNetworkConfig) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
cidrs: value.cidrs.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::PeerPolicyConfig> for PeerPolicyConfig {
|
||||
fn from(value: pb::PeerPolicyConfig) -> Self {
|
||||
let default = Self::default();
|
||||
Self {
|
||||
p2p_enabled: value.p2p_enabled.unwrap_or(default.p2p_enabled),
|
||||
relay_peer_rpc: value.relay_peer_rpc.unwrap_or(default.relay_peer_rpc),
|
||||
relay_data: value.relay_data.unwrap_or(default.relay_data),
|
||||
latency_first: value.latency_first.unwrap_or(default.latency_first),
|
||||
encryption_required: value
|
||||
.encryption_required
|
||||
.unwrap_or(default.encryption_required),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PeerPolicyConfig> for pb::PeerPolicyConfig {
|
||||
fn from(value: PeerPolicyConfig) -> Self {
|
||||
Self {
|
||||
p2p_enabled: Some(value.p2p_enabled),
|
||||
relay_peer_rpc: Some(value.relay_peer_rpc),
|
||||
relay_data: Some(value.relay_data),
|
||||
latency_first: Some(value.latency_first),
|
||||
encryption_required: Some(value.encryption_required),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::TrafficConfig> for TrafficConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::TrafficConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
mtu: value
|
||||
.mtu
|
||||
.map(|mtu| u16::try_from(mtu).map_err(|_| ConfigError::InvalidMtu(mtu)))
|
||||
.transpose()?,
|
||||
instance_recv_bps_limit: value.instance_recv_bps_limit,
|
||||
foreign_relay_bps_limit: value.foreign_relay_bps_limit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TrafficConfig> for pb::TrafficConfig {
|
||||
fn from(value: TrafficConfig) -> Self {
|
||||
Self {
|
||||
mtu: value.mtu.map(Into::into),
|
||||
instance_recv_bps_limit: value.instance_recv_bps_limit,
|
||||
foreign_relay_bps_limit: value.foreign_relay_bps_limit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pb_ip_addr_to_std(value: common_pb::IpAddr) -> Result<IpAddr, ConfigError> {
|
||||
match value.ip.ok_or(ConfigError::MissingField("IpAddr.ip"))? {
|
||||
common_pb::ip_addr::Ip::Ipv4(addr) => Ok(IpAddr::V4(addr.into())),
|
||||
common_pb::ip_addr::Ip::Ipv6(addr) => Ok(IpAddr::V6(addr.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_prefix_for_address(address: IpAddr, prefix_len: u32) -> ConfigError {
|
||||
let prefix_len = u8::try_from(prefix_len).unwrap_or(u8::MAX);
|
||||
match address {
|
||||
IpAddr::V4(_) => ConfigError::InvalidIpv4Prefix(prefix_len),
|
||||
IpAddr::V6(_) => ConfigError::InvalidIpv6Prefix(prefix_len),
|
||||
}
|
||||
}
|
||||
|
||||
fn uuid_to_bytes(value: common_pb::Uuid) -> [u8; 16] {
|
||||
let mut bytes = [0; 16];
|
||||
bytes[0..4].copy_from_slice(&value.part1.to_be_bytes());
|
||||
bytes[4..8].copy_from_slice(&value.part2.to_be_bytes());
|
||||
bytes[8..12].copy_from_slice(&value.part3.to_be_bytes());
|
||||
bytes[12..16].copy_from_slice(&value.part4.to_be_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
fn uuid_from_bytes(bytes: [u8; 16]) -> common_pb::Uuid {
|
||||
common_pb::Uuid {
|
||||
part1: u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
|
||||
part2: u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
|
||||
part3: u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
|
||||
part4: u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use x25519_dalek::{PublicKey, StaticSecret};
|
||||
|
||||
fn digest(network_name: &str, network_secret: &str) -> NetworkSecretDigest {
|
||||
let mut digest = [0u8; 32];
|
||||
generate_digest_from_str(network_name, network_secret, &mut digest);
|
||||
digest
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_matches_secret_to_digest_identity() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "secret")),
|
||||
};
|
||||
|
||||
assert_eq!(local, remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_rejects_different_digest() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "other")),
|
||||
};
|
||||
|
||||
assert_ne!(local, remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_equal_values_have_equal_hash() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "secret")),
|
||||
};
|
||||
let mut local_hasher = DefaultHasher::new();
|
||||
let mut remote_hasher = DefaultHasher::new();
|
||||
|
||||
local.hash(&mut local_hasher);
|
||||
remote.hash(&mut remote_hasher);
|
||||
|
||||
assert_eq!(local_hasher.finish(), remote_hasher.finish());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_derives_digest_from_plaintext_secret() {
|
||||
let identity = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
|
||||
assert_eq!(identity.secret_digest(), Some(digest("net", "secret")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_default_matches_native_default_network() {
|
||||
assert_eq!(
|
||||
NetworkIdentity::default(),
|
||||
NetworkIdentity::new("default".to_string(), "".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_listener_policy_uses_explicit_host_capabilities() {
|
||||
let policy = MappedListenerPolicy::new(["tcp", "ws", "wss"]);
|
||||
let parsed = policy
|
||||
.parse_urls(&[
|
||||
"tcp://127.0.0.1".to_string(),
|
||||
"ws://example.com".to_string(),
|
||||
"wss://example.com/path".to_string(),
|
||||
"ring://peer-id:1000".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(parsed.len(), 4);
|
||||
assert_eq!(parsed[0].scheme(), "tcp");
|
||||
assert_eq!(parsed[1].scheme(), "ws");
|
||||
assert_eq!(parsed[2].scheme(), "wss");
|
||||
assert_eq!(parsed[3].port(), Some(1000));
|
||||
|
||||
let error = policy
|
||||
.parse_urls(&["ring://peer-id".to_string()])
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("mapped listener port is missing")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_generates_missing_key_pair() {
|
||||
let normalized = normalize_secure_mode_config(common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: None,
|
||||
local_public_key: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let private_key = normalized.private_key().unwrap();
|
||||
let public_key = normalized.public_key().unwrap();
|
||||
assert_eq!(public_key, PublicKey::from(&private_key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_preserves_existing_key_configuration() {
|
||||
let private_key = StaticSecret::from([7; 32]);
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
let config = common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: Some(BASE64_STANDARD.encode(private_key.as_bytes())),
|
||||
local_public_key: Some(BASE64_STANDARD.encode(public_key.as_bytes())),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_secure_mode_config(config.clone()).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_rejects_mismatched_public_key() {
|
||||
let private_key = StaticSecret::from([7; 32]);
|
||||
let other_public_key = PublicKey::from(&StaticSecret::from([9; 32]));
|
||||
let error = normalize_secure_mode_config(common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: Some(BASE64_STANDARD.encode(private_key.as_bytes())),
|
||||
local_public_key: Some(BASE64_STANDARD.encode(other_public_key.as_bytes())),
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
assert!(
|
||||
error.contains("does not match generated public key"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_secure_mode_does_not_validate_keys() {
|
||||
let config = common_pb::SecureModeConfig {
|
||||
enabled: false,
|
||||
local_private_key: Some("not-base64".to_string()),
|
||||
local_public_key: Some("not-base64".to_string()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_secure_mode_config(config.clone()).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_ip_prefix_lengths() {
|
||||
assert!(IpPrefix::new("10.0.0.1".parse().unwrap(), 24).is_ok());
|
||||
assert_eq!(
|
||||
IpPrefix::new("10.0.0.1".parse().unwrap(), 33),
|
||||
Err(ConfigError::InvalidIpv4Prefix(33))
|
||||
);
|
||||
assert!(IpPrefix::new("2001:db8::1".parse().unwrap(), 64).is_ok());
|
||||
assert_eq!(
|
||||
IpPrefix::new("2001:db8::1".parse().unwrap(), 129),
|
||||
Err(ConfigError::InvalidIpv6Prefix(129))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_core_config_from_proto_defaults() {
|
||||
let config = CoreConfig::try_from(pb::CoreConfig {
|
||||
node: Some(pb::NodeConfig {
|
||||
peer_id: Some(7),
|
||||
instance_id: None,
|
||||
hostname: Some("node-a".to_string()),
|
||||
network_name: "net".to_string(),
|
||||
}),
|
||||
routes: None,
|
||||
peer_policy: None,
|
||||
traffic: Some(pb::TrafficConfig {
|
||||
mtu: Some(1380),
|
||||
instance_recv_bps_limit: Some(100),
|
||||
foreign_relay_bps_limit: None,
|
||||
}),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(config.node.peer_id, Some(7));
|
||||
assert_eq!(config.node.hostname.as_deref(), Some("node-a"));
|
||||
assert!(config.peer_policy.p2p_enabled);
|
||||
assert_eq!(config.traffic.mtu, Some(1380));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_ip_prefix_round_trip() {
|
||||
let prefix = IpPrefix::new("10.1.0.1".parse().unwrap(), 16).unwrap();
|
||||
let pb: pb::IpPrefix = prefix.clone().into();
|
||||
assert_eq!(IpPrefix::try_from(pb).unwrap(), prefix);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Peer-flavored configuration data owned by the config layer.
|
||||
//!
|
||||
//! These types are pure serializable configuration snapshots. Normalization
|
||||
//! and derivation behavior that depends on peer-domain logic stays in
|
||||
//! `crate::peers`.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use cidr::Ipv6Cidr;
|
||||
use easytier_proto::common::{FlagsInConfig, PeerFeatureFlag, SecureModeConfig, StunInfo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::proto::acl::{Acl, AclV1, Action, Chain, ChainType, GroupInfo, Protocol, Rule};
|
||||
|
||||
use super::{CoreConfig, NetworkIdentity};
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AclRuleConfig {
|
||||
pub acl: Option<Acl>,
|
||||
pub tcp_whitelist: Vec<String>,
|
||||
pub udp_whitelist: Vec<String>,
|
||||
pub whitelist_priority: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AclWhitelistSnapshot {
|
||||
pub tcp_ports: Vec<String>,
|
||||
pub udp_ports: Vec<String>,
|
||||
}
|
||||
|
||||
impl From<&AclRuleConfig> for AclWhitelistSnapshot {
|
||||
fn from(config: &AclRuleConfig) -> Self {
|
||||
Self {
|
||||
tcp_ports: config.tcp_whitelist.clone(),
|
||||
udp_ports: config.udp_whitelist.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AclRuleConfig {
|
||||
fn parse_port_list(port_list: &[String]) -> anyhow::Result<Vec<String>> {
|
||||
let mut ports = Vec::new();
|
||||
|
||||
for port_spec in port_list {
|
||||
if port_spec.contains('-') {
|
||||
let parts: Vec<&str> = port_spec.split('-').collect();
|
||||
if parts.len() != 2 {
|
||||
return Err(anyhow::anyhow!("Invalid port range format: {}", port_spec));
|
||||
}
|
||||
|
||||
let start: u16 = parts[0]
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid start port in range: {}", port_spec))?;
|
||||
let end: u16 = parts[1]
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid end port in range: {}", port_spec))?;
|
||||
|
||||
if start > end {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Start port must be <= end port in range: {}",
|
||||
port_spec
|
||||
));
|
||||
}
|
||||
ports.push(port_spec.clone());
|
||||
} else {
|
||||
let port: u16 = port_spec
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid port number: {}", port_spec))?;
|
||||
ports.push(port.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ports)
|
||||
}
|
||||
|
||||
fn generate_acl_from_whitelists(&mut self) -> anyhow::Result<()> {
|
||||
if self.tcp_whitelist.is_empty() && self.udp_whitelist.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut inbound_chain = Chain {
|
||||
name: "inbound_whitelist".to_string(),
|
||||
chain_type: ChainType::Inbound as i32,
|
||||
description: "Auto-generated inbound whitelist from CLI".to_string(),
|
||||
enabled: true,
|
||||
rules: vec![],
|
||||
default_action: Action::Allow as i32,
|
||||
};
|
||||
|
||||
let mut rule_priority = self.whitelist_priority.unwrap_or(1000u32);
|
||||
|
||||
if !self.tcp_whitelist.is_empty() {
|
||||
let tcp_ports = Self::parse_port_list(&self.tcp_whitelist)?;
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "tcp_whitelist".to_string(),
|
||||
description: "Auto-generated TCP whitelist rule".to_string(),
|
||||
priority: rule_priority,
|
||||
enabled: true,
|
||||
protocol: Protocol::Tcp as i32,
|
||||
ports: tcp_ports,
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Allow as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: true,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "tcp_whitelist_deny_other".to_string(),
|
||||
description: "Auto-generated TCP whitelist rule to deny other ports".to_string(),
|
||||
priority: 0,
|
||||
enabled: true,
|
||||
protocol: Protocol::Tcp as i32,
|
||||
ports: vec!["0-65535".to_string()],
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Drop as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
rule_priority -= 1;
|
||||
}
|
||||
|
||||
if !self.udp_whitelist.is_empty() {
|
||||
let udp_ports = Self::parse_port_list(&self.udp_whitelist)?;
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "udp_whitelist".to_string(),
|
||||
description: "Auto-generated UDP whitelist rule".to_string(),
|
||||
priority: rule_priority,
|
||||
enabled: true,
|
||||
protocol: Protocol::Udp as i32,
|
||||
ports: udp_ports,
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Allow as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "udp_whitelist_deny_other".to_string(),
|
||||
description: "Auto-generated UDP whitelist rule to deny other ports".to_string(),
|
||||
priority: 0,
|
||||
enabled: true,
|
||||
protocol: Protocol::Udp as i32,
|
||||
ports: vec!["0-65535".to_string()],
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Drop as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
}
|
||||
|
||||
if self.acl.is_none() {
|
||||
self.acl = Some(Acl::default());
|
||||
}
|
||||
|
||||
let acl = self.acl.as_mut().expect("ACL was initialized above");
|
||||
if let Some(acl_v1) = acl.acl_v1.as_mut() {
|
||||
acl_v1.chains.push(inbound_chain);
|
||||
} else {
|
||||
acl.acl_v1 = Some(AclV1 {
|
||||
chains: vec![inbound_chain],
|
||||
group: Some(GroupInfo {
|
||||
declares: vec![],
|
||||
members: vec![],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn for_credential_peer(&self) -> Self {
|
||||
let mut config = self.clone();
|
||||
if let Some(acl) = config.acl.as_mut().and_then(|acl| acl.acl_v1.as_mut()) {
|
||||
acl.group = None;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub fn build(&self) -> anyhow::Result<Option<Acl>> {
|
||||
let mut config = self.clone();
|
||||
config.generate_acl_from_whitelists()?;
|
||||
Ok(config.acl)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PublicIpv6ProviderConfig {
|
||||
pub provider_enabled: bool,
|
||||
pub configured_prefix: Option<Ipv6Cidr>,
|
||||
pub provider_supported: bool,
|
||||
}
|
||||
|
||||
impl PublicIpv6ProviderConfig {
|
||||
pub fn should_run_reconcile(self) -> bool {
|
||||
self.provider_enabled
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PeerRuntimeConfig {
|
||||
pub core: CoreConfig,
|
||||
pub network_identity: NetworkIdentity,
|
||||
pub stun_info: StunInfo,
|
||||
pub feature_flags: PeerFeatureFlag,
|
||||
pub secure_mode: Option<SecureModeConfig>,
|
||||
pub host_routing: HostRoutingPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HostRoutingPolicy {
|
||||
/// Route otherwise-unreachable external IPv4 traffic through this node and
|
||||
/// keep self-delivered packets eligible for the host TUN/proxy path.
|
||||
pub local_exit_node_fallback: bool,
|
||||
}
|
||||
|
||||
/// One normalized peer configuration version submitted by a host.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PeerRuntimeSnapshot {
|
||||
pub runtime: PeerRuntimeConfig,
|
||||
pub easytier_version: String,
|
||||
pub avoid_relay_data_preference: bool,
|
||||
pub flags: FlagsInConfig,
|
||||
pub pinned_peers: Vec<(url::Url, Option<String>)>,
|
||||
pub peer_group_memberships: Vec<PeerGroupIdentity>,
|
||||
pub acl_group_declarations: Vec<PeerGroupIdentity>,
|
||||
pub ospf_update_my_foreign_network_interval_sec: u64,
|
||||
pub max_direct_conns_per_peer_in_foreign_network: usize,
|
||||
pub hmac_secret_digest: bool,
|
||||
}
|
||||
|
||||
impl PeerRuntimeSnapshot {
|
||||
pub fn new(runtime: PeerRuntimeConfig, flags: FlagsInConfig) -> Self {
|
||||
let avoid_relay_data_preference = runtime.feature_flags.avoid_relay_data;
|
||||
Self {
|
||||
runtime,
|
||||
easytier_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
avoid_relay_data_preference,
|
||||
flags,
|
||||
pinned_peers: Vec::new(),
|
||||
peer_group_memberships: Vec::new(),
|
||||
acl_group_declarations: Vec::new(),
|
||||
ospf_update_my_foreign_network_interval_sec: 10,
|
||||
max_direct_conns_per_peer_in_foreign_network: 3,
|
||||
hmac_secret_digest: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PeerRuntimeSnapshot {
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
PeerRuntimeConfig {
|
||||
core: CoreConfig::default(),
|
||||
network_identity: NetworkIdentity::default(),
|
||||
stun_info: StunInfo::default(),
|
||||
feature_flags: PeerFeatureFlag::default(),
|
||||
secure_mode: None,
|
||||
host_routing: HostRoutingPolicy::default(),
|
||||
},
|
||||
FlagsInConfig::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerGroupIdentity {
|
||||
pub group_name: String,
|
||||
pub group_secret: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn whitelist_rules_are_built_in_core() {
|
||||
let acl = AclRuleConfig {
|
||||
tcp_whitelist: vec!["80".to_string(), "8000-9000".to_string()],
|
||||
udp_whitelist: vec!["53".to_string()],
|
||||
..Default::default()
|
||||
}
|
||||
.build()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let chain = &acl.acl_v1.unwrap().chains[0];
|
||||
assert_eq!(chain.name, "inbound_whitelist");
|
||||
assert_eq!(chain.rules.len(), 4);
|
||||
assert_eq!(chain.rules[0].ports, ["80", "8000-9000"]);
|
||||
assert_eq!(chain.rules[2].ports, ["53"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_whitelist_range_is_rejected() {
|
||||
let error = AclRuleConfig {
|
||||
tcp_whitelist: vec!["9000-8000".to_string()],
|
||||
..Default::default()
|
||||
}
|
||||
.build()
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("Start port must be <= end port"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_peer_acl_preserves_chains_without_group_secrets() {
|
||||
let config = AclRuleConfig {
|
||||
acl: Some(Acl {
|
||||
acl_v1: Some(AclV1 {
|
||||
chains: vec![Chain {
|
||||
name: "forward".to_owned(),
|
||||
chain_type: ChainType::Forward as i32,
|
||||
rules: vec![Rule {
|
||||
action: Action::Drop as i32,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
group: Some(GroupInfo {
|
||||
declares: vec![crate::proto::acl::GroupIdentity {
|
||||
group_name: "ops".to_owned(),
|
||||
group_secret: "secret".to_owned(),
|
||||
}],
|
||||
members: vec!["ops".to_owned()],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
tcp_whitelist: vec!["22".to_owned()],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let sanitized = config.for_credential_peer();
|
||||
|
||||
let acl = sanitized.acl.unwrap().acl_v1.unwrap();
|
||||
assert_eq!(acl.chains.len(), 1);
|
||||
assert_eq!(acl.chains[0].name, "forward");
|
||||
assert_eq!(acl.chains[0].rules[0].action, Action::Drop as i32);
|
||||
assert!(acl.group.is_none());
|
||||
assert_eq!(sanitized.tcp_whitelist, ["22"]);
|
||||
assert!(config.acl.unwrap().acl_v1.unwrap().group.is_some());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user