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:
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()));
|
||||
}
|
||||
Reference in New Issue
Block a user