feat: add MeshPort overlay networking, item actions window, and AVA2 client enhancements
- add MeshPort peer-to-peer overlay networking SDK, C++ integration, and Python bindings - add item actions quick use/split/delete/lock overlay window (mt_item_actions) - add shop name range and NPC name visibility settings to system display options - support battlepass ticket activation and month validation in mt_battlepass - support boss tracking teleport destination button in mt_bosses - support asynchronous account registration cancellation and pending login cancellation - update AVA2 item conversion for attr lock scrolls and battlepass tickets - update .gitignore for local build outputs and caches
This commit is contained in:
@@ -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();
|
||||
}
|
||||
Reference in New Issue
Block a user