From 1609c4f6bf83a5a3b0edf11d07c22c13576e6be5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Wed, 30 Sep 2026 10:54:18 +0500 Subject: [PATCH] Phase 9: Play with Friends (LAN/direct/private modes, exposure check, firewall rules, UPnP discovery, friend package, realm address reapplied after start) Verified read-only on the live server: database and console listen on loopback only; login/world are loopback until the owner enables sharing. Elevation and router changes only happen on explicit action. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 50 ++++++ crates/coa-core/Cargo.toml | 1 + crates/coa-core/examples/net_check.rs | 14 ++ crates/coa-core/src/config/mod.rs | 2 +- crates/coa-core/src/firewall.rs | 135 +++++++++++++++ crates/coa-core/src/friends.rs | 227 ++++++++++++++++++++++++++ crates/coa-core/src/lib.rs | 4 + crates/coa-core/src/net.rs | 159 ++++++++++++++++++ crates/coa-core/src/process.rs | 53 +++++- crates/coa-core/src/upnp.rs | 177 ++++++++++++++++++++ src-tauri/src/lib.rs | 139 +++++++++++++++- src/lib/api.ts | 24 +++ src/screens/FriendsPage.tsx | 170 +++++++++++++++++++ src/screens/Shell.tsx | 3 + 14 files changed, 1154 insertions(+), 4 deletions(-) create mode 100644 crates/coa-core/examples/net_check.rs create mode 100644 crates/coa-core/src/firewall.rs create mode 100644 crates/coa-core/src/friends.rs create mode 100644 crates/coa-core/src/net.rs create mode 100644 crates/coa-core/src/upnp.rs create mode 100644 src/screens/FriendsPage.tsx diff --git a/Cargo.lock b/Cargo.lock index a5fe51c..dc5e64d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,6 +47,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + [[package]] name = "atk" version = "0.18.2" @@ -360,6 +369,7 @@ dependencies = [ "tracing-subscriber", "uuid", "windows-sys 0.60.2", + "zip", "zstd", ] @@ -645,6 +655,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -5083,6 +5104,23 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "zip" +version = "2.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "displaydoc", + "flate2", + "indexmap 2.14.2", + "memchr", + "thiserror 2.0.21", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5095,6 +5133,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zstd" version = "0.13.3" diff --git a/crates/coa-core/Cargo.toml b/crates/coa-core/Cargo.toml index ed4bd8c..2d820ad 100644 --- a/crates/coa-core/Cargo.toml +++ b/crates/coa-core/Cargo.toml @@ -20,6 +20,7 @@ zstd = { version = "0.13", features = ["zstdmt"] } reqwest = { version = "0.12", default-features = false, features = ["blocking", "native-tls"] } tar = "0.4" num-bigint = "0.4" +zip = { version = "2", default-features = false, features = ["deflate"] } sha1 = "0.10" tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] } diff --git a/crates/coa-core/examples/net_check.rs b/crates/coa-core/examples/net_check.rs new file mode 100644 index 0000000..ff76581 --- /dev/null +++ b/crates/coa-core/examples/net_check.rs @@ -0,0 +1,14 @@ +fn main() { + let root = std::env::args().nth(1).expect("server folder"); + let ports = coa_core::layout::read_ports(std::path::Path::new(&root)); + println!("LAN address: {:?}", coa_core::net::lan_ip()); + for e in coa_core::net::exposure(&ports) { + println!("{:<14} port {:<5} listening={} reachable_from_network={}", e.what, e.port, e.listening, e.reachable_from_network); + } + println!("{:?}", coa_core::net::tailscale()); + println!("firewall rules: {:?}", coa_core::firewall::status()); + match coa_core::upnp::discover() { + Some(gw) => println!("UPnP router: {} -> outside address {:?}", gw.control_url, coa_core::upnp::external_ip(&gw)), + None => println!("UPnP router: none answered"), + } +} diff --git a/crates/coa-core/src/config/mod.rs b/crates/coa-core/src/config/mod.rs index 71d63db..891976a 100644 --- a/crates/coa-core/src/config/mod.rs +++ b/crates/coa-core/src/config/mod.rs @@ -277,7 +277,7 @@ pub struct SnapshotInfo { files: Vec, } -fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec)]) -> Result { +pub(crate) fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec)]) -> Result { let id = format!("{}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"), scope.name()); let dir = snapshot_root(meta_dir).join(&id); fs::create_dir_all(&dir)?; diff --git a/crates/coa-core/src/firewall.rs b/crates/coa-core/src/firewall.rs new file mode 100644 index 0000000..9b352e7 --- /dev/null +++ b/crates/coa-core/src/firewall.rs @@ -0,0 +1,135 @@ +//! Windows Firewall rules for the game ports, owned by the Manager: fixed names, added only when missing (no duplicates), +//! removable by exact name (other rules are never touched). Reading needs no rights; changing needs one UAC confirmation. + +use std::process::Command; + +use serde::Serialize; + +use crate::error::{Error, Result}; +use crate::layout::Ports; + +pub const RULE_AUTH: &str = "CoA Server Manager - Auth"; +pub const RULE_WORLD: &str = "CoA Server Manager - World"; + +#[derive(Debug, Clone, Serialize)] +pub struct Status { + pub auth: bool, + pub world: bool, +} + +fn hidden(cmd: &mut Command) { + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + cmd.creation_flags(0x0800_0000); + } + #[cfg(not(windows))] + let _ = cmd; +} + +/// `netsh ... show rule name=X` exits with 0 when at least one rule has exactly that name (locale independent). +pub fn rule_exists(name: &str) -> bool { + let mut c = Command::new("netsh"); + c.args(["advfirewall", "firewall", "show", "rule"]).arg(format!("name={name}")); + hidden(&mut c); + c.output().map(|o| o.status.success()).unwrap_or(false) +} + +pub fn status() -> Status { + Status { auth: rule_exists(RULE_AUTH), world: rule_exists(RULE_WORLD) } +} + +fn add_cmd(name: &str, port: u16) -> String { + format!("netsh advfirewall firewall add rule name=\"{name}\" dir=in action=allow protocol=TCP localport={port} profile=private,domain") +} + +fn delete_cmd(name: &str) -> String { + format!("netsh advfirewall firewall delete rule name=\"{name}\"") +} + +/// Commands that would make the rules match `ports`, given what exists now. +pub fn plan(ports: &Ports, have: &Status) -> Vec { + let mut v = Vec::new(); + if !have.auth { + v.push(add_cmd(RULE_AUTH, ports.auth)); + } + if !have.world { + v.push(add_cmd(RULE_WORLD, ports.world)); + } + v +} + +/// Run `commands` with administrator rights (one UAC prompt). Fails cleanly if the user declines. +fn run_elevated(commands: &[String]) -> Result<()> { + let script = std::env::temp_dir().join(format!("coa-firewall-{}.cmd", std::process::id())); + std::fs::write(&script, format!("@echo off\r\n{}\r\n", commands.join("\r\n")))?; + let ps = format!("try {{ $p = Start-Process -FilePath cmd.exe -ArgumentList '/c','\"{}\"' -Verb RunAs -Wait -PassThru -WindowStyle Hidden; exit $p.ExitCode }} catch {{ exit 1223 }}", script.display()); + let mut c = Command::new("powershell"); + c.args(["-NoProfile", "-NonInteractive", "-Command", &ps]); + hidden(&mut c); + let out = c.output(); + let _ = std::fs::remove_file(&script); + match out { + Ok(o) if o.status.success() => Ok(()), + Ok(o) if o.status.code() == Some(1223) => Err(Error::Invalid("Windows asked for permission and it was not given, so the firewall was not changed.".into())), + _ => Err(Error::Invalid("The firewall could not be changed.".into())), + } +} + +/// Make sure both rules exist (adds only the missing ones) and confirm afterwards. +pub fn ensure_rules(ports: &Ports) -> Result { + let have = status(); + let cmds = plan(ports, &have); + if !cmds.is_empty() { + run_elevated(&cmds)?; + } + let now = status(); + if now.auth && now.world { + Ok(now) + } else { + Err(Error::Invalid("The firewall rules could not be confirmed after the change.".into())) + } +} + +/// Remove only the Manager's own rules. +pub fn remove_rules() -> Result<()> { + let have = status(); + let mut cmds = Vec::new(); + if have.auth { + cmds.push(delete_cmd(RULE_AUTH)); + } + if have.world { + cmds.push(delete_cmd(RULE_WORLD)); + } + if cmds.is_empty() { + return Ok(()); + } + run_elevated(&cmds) +} + + +#[cfg(test)] +mod tests { + use super::*; + + fn ports() -> Ports { + Ports { mysql: 3307, auth: 3724, world: 8085, ra: 3443 } + } + + #[test] + fn only_missing_rules_are_planned_and_only_game_ports_are_opened() { + let all = plan(&ports(), &Status { auth: false, world: false }); + assert_eq!(all.len(), 2); + assert!(all[0].contains("localport=3724") && all[1].contains("localport=8085")); + assert!(!all.iter().any(|c| c.contains("3307") || c.contains("3443")), "database and console ports are never opened"); + assert!(all.iter().all(|c| c.contains("profile=private,domain") && c.contains("action=allow") && c.contains("dir=in"))); + assert_eq!(plan(&ports(), &Status { auth: true, world: false }).len(), 1); + assert!(plan(&ports(), &Status { auth: true, world: true }).is_empty(), "no duplicates"); + assert_eq!(delete_cmd(RULE_AUTH), "netsh advfirewall firewall delete rule name=\"CoA Server Manager - Auth\""); + } + + #[test] + fn reading_the_rules_needs_no_rights_and_finds_nothing_that_does_not_exist() { + assert!(!rule_exists("CoA Server Manager - definitely not a rule")); + } +} diff --git a/crates/coa-core/src/friends.rs b/crates/coa-core/src/friends.rs new file mode 100644 index 0000000..e87fda7 --- /dev/null +++ b/crates/coa-core/src/friends.rs @@ -0,0 +1,227 @@ +//! "Play with Friends": which address friends use, opening the login/world servers to the network (and only those), +//! keeping the realm's advertised address right after every start, and the small package a friend needs. + +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::config::parser::ConfFile; +use crate::config::{take_snapshot, Scope}; +use crate::db::{Account, Db}; +use crate::error::{Error, Result}; +use crate::fsx; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Mode { + /// Only this computer. + Local, + /// Friends on the same home network. + Lan, + /// Friends over the internet through this connection (needs open ports). + Direct, + /// Friends join a private network (Tailscale); no router setup. + Private, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Settings { + pub mode: Mode, + /// The address friends type into their client for this mode. + pub host: Option, +} + +impl Default for Settings { + fn default() -> Self { + Settings { mode: Mode::Local, host: None } + } +} + +fn file(meta: &Path) -> PathBuf { + meta.join("friends.json") +} + +pub fn load(meta: &Path) -> Settings { + fsx::read_json(&file(meta)).unwrap_or_default() +} + +pub fn save(meta: &Path, s: &Settings) -> Result<()> { + fsx::atomic_write_json(&file(meta), s) +} + +fn host_ok(h: &str) -> bool { + !h.is_empty() && h.len() <= 253 && h.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) && !h.starts_with('-') +} + +/// The files whose `BindIP` decides who can reach the login and world servers. +fn bind_targets(root: &Path) -> Vec { + ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf", "Settings/authserver.conf.template", "Core/configs/authserver.conf"] + .iter() + .map(|r| root.join(r)) + .filter(|p| p.is_file()) + .collect() +} + +/// Whether the configuration currently lets other computers reach the login and world servers. +pub fn bind_is_open(root: &Path) -> bool { + let files = bind_targets(root); + !files.is_empty() + && files + .iter() + .all(|p| fs::read(p).ok().and_then(|b| ConfFile::parse_bytes(&b).ok()).and_then(|c| c.get("BindIP").map(|v| v.trim() == "\"0.0.0.0\"")).unwrap_or(false)) +} + +/// Open (`0.0.0.0`) or close (`127.0.0.1`) the login and world servers to other computers. The database and the server +/// console are never touched. Returns true if anything changed (a restart is then needed). The old files are snapshotted. +pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result { + let want = if open { "\"0.0.0.0\"" } else { "\"127.0.0.1\"" }; + let mut originals = Vec::new(); + let mut edits = Vec::new(); + for p in bind_targets(root) { + let bytes = fs::read(&p)?; + let mut conf = ConfFile::parse_bytes(&bytes)?; + if conf.get("BindIP").map(str::trim) == Some(want) { + continue; + } + conf.set("BindIP", want, &["Added by CoA Server Manager"]); + originals.push((p.clone(), bytes)); + edits.push((p, conf.to_text())); + } + if edits.is_empty() { + return Ok(false); + } + take_snapshot(meta, Scope::Server, if open { "before opening the servers to friends" } else { "before closing the servers to friends" }, &originals)?; + for (p, text) in edits { + fsx::atomic_write(&p, text.as_bytes())?; + } + Ok(true) +} + +/// Make the realm list advertise `host` (the launcher resets it to 127.0.0.1 at every start, so this runs after each start). +pub fn apply_realm_address(root: &Path, host: &str) -> Result<()> { + if !host_ok(host) { + return Err(Error::Invalid("That address is not valid.".into())); + } + let db = Db::from_repack(root, Account::Admin)?; + db.query(&format!("UPDATE acore_auth.realmlist SET address='{host}', localAddress='{host}' WHERE id=1;"))?; + Ok(()) +} + +/// After every server start: put the chosen address back into the realm list (the launcher resets it to 127.0.0.1). +pub fn reapply(root: &Path, meta: &Path) -> Result<()> { + let s = load(meta); + match (s.mode, s.host) { + (Mode::Local, _) | (_, None) => Ok(()), + (_, Some(host)) => apply_realm_address(root, &host), + } +} + +/// Build the friend's package: instructions, a ready realmlist file and (optionally) the companion addon. +/// Only whitelisted content goes in - never credentials, configuration or database files. +pub fn make_friend_package(root: &Path, host: &str, include_addon: bool, out_zip: &Path) -> Result<()> { + if !host_ok(host) { + return Err(Error::Invalid("That address is not valid.".into())); + } + let file = fs::File::create(out_zip)?; + let mut zip = zip::ZipWriter::new(file); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let mut add = |name: &str, bytes: &[u8]| -> Result<()> { + zip.start_file(name, opts).map_err(|e| Error::Invalid(e.to_string()))?; + zip.write_all(bytes)?; + Ok(()) + }; + add("HOW-TO-CONNECT.txt", crate::net::instructions(host).replace('\n', "\r\n").as_bytes())?; + add("realmlist.wtf", format!("set realmlist {host}\r\n").as_bytes())?; + if include_addon { + if let Some(src) = crate::client::addon_source(root) { + let mut stack = vec![src.clone()]; + while let Some(dir) = stack.pop() { + for e in fs::read_dir(&dir)? { + let p = e?.path(); + if p.is_dir() { + stack.push(p); + } else { + let rel = p.strip_prefix(&src).unwrap().to_string_lossy().replace('\\', "/"); + add(&format!("Interface/AddOns/CoABotUI/{rel}"), &fs::read(&p)?)?; + } + } + } + } + } + zip.finish().map_err(|e| Error::Invalid(e.to_string()))?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn setup() -> (tempfile::TempDir, PathBuf, PathBuf) { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("srv"); + let meta = d.path().join("srv.manager"); + fs::create_dir_all(root.join("Settings")).unwrap(); + fs::create_dir_all(root.join("Core/configs")).unwrap(); + fs::create_dir_all(&meta).unwrap(); + for (f, body) in [ + ("Settings/worldserver.conf.template", "[worldserver]\r\nBindIP = \"127.0.0.1\"\r\nRa.IP = \"127.0.0.1\"\r\n"), + ("Core/configs/worldserver.conf", "[worldserver]\r\nBindIP = \"127.0.0.1\"\r\nRa.IP = \"127.0.0.1\"\r\n"), + ("Settings/authserver.conf.template", "[authserver]\nBindIP = \"127.0.0.1\"\n"), + ("Core/configs/authserver.conf", "[authserver]\nBindIP = \"127.0.0.1\"\n"), + ] { + fs::write(root.join(f), body).unwrap(); + } + (d, root, meta) + } + + #[test] + fn opening_changes_only_bind_ip_of_login_and_world_and_never_the_console() { + let (_d, root, meta) = setup(); + assert!(set_open(&root, &meta, true).unwrap()); + let w = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap(); + assert_eq!(w, "[worldserver]\r\nBindIP = \"0.0.0.0\"\r\nRa.IP = \"127.0.0.1\"\r\n", "console address untouched, line endings kept"); + assert_eq!(fs::read_to_string(root.join("Settings/authserver.conf.template")).unwrap(), "[authserver]\nBindIP = \"0.0.0.0\"\n"); + assert!(!set_open(&root, &meta, true).unwrap(), "idempotent"); + assert!(crate::config::list_snapshots(&meta).iter().any(|s| s.reason.contains("opening")), "a snapshot was taken first"); + assert!(set_open(&root, &meta, false).unwrap()); + assert!(fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap().contains("BindIP = \"127.0.0.1\"")); + } + + #[test] + fn settings_round_trip_and_default_to_local() { + let d = tempfile::tempdir().unwrap(); + assert_eq!(load(d.path()).mode, Mode::Local); + save(d.path(), &Settings { mode: Mode::Private, host: Some("100.64.1.2".into()) }).unwrap(); + let s = load(d.path()); + assert_eq!((s.mode, s.host.as_deref()), (Mode::Private, Some("100.64.1.2"))); + } + + #[test] + fn friend_package_contains_only_whitelisted_files() { + let (d, root, _m) = setup(); + fs::write(root.join("Settings/database.json"), "{\"rootPassword\":\"SECRET\"}").unwrap(); + fs::write(root.join("Settings/repack.json"), "{\"raPassword\":\"SECRET\"}").unwrap(); + let addon = root.join("Extras/CoABotUI"); + fs::create_dir_all(addon.join("Libs")).unwrap(); + fs::write(addon.join("CoABotUI.toc"), "## Version: 1").unwrap(); + fs::write(addon.join("Libs/x.lua"), "-- lib").unwrap(); + let out = d.path().join("friend.zip"); + make_friend_package(&root, "203.0.113.7", true, &out).unwrap(); + let mut z = zip::ZipArchive::new(fs::File::open(&out).unwrap()).unwrap(); + let names: Vec = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect(); + assert!(names.contains(&"HOW-TO-CONNECT.txt".to_string()) && names.contains(&"realmlist.wtf".to_string())); + assert!(names.contains(&"Interface/AddOns/CoABotUI/Libs/x.lua".to_string())); + assert!(!names.iter().any(|n| n.contains("database") || n.contains("repack") || n.contains("conf")), "{names:?}"); + let mut realm = String::new(); + std::io::Read::read_to_string(&mut z.by_name("realmlist.wtf").unwrap(), &mut realm).unwrap(); + assert_eq!(realm, "set realmlist 203.0.113.7\r\n"); + for i in 0..z.len() { + let mut body = String::new(); + let _ = std::io::Read::read_to_string(&mut z.by_index(i).unwrap(), &mut body); + assert!(!body.contains("SECRET")); + } + assert!(make_friend_package(&root, "bad host; x", false, &d.path().join("x.zip")).is_err()); + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 62f9a37..6f05f4a 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -6,6 +6,8 @@ pub mod db; pub mod download; pub mod driver; pub mod error; +pub mod firewall; +pub mod friends; pub mod fsx; pub mod health; pub mod install; @@ -16,11 +18,13 @@ pub mod population; pub mod process; pub mod manifest; pub mod migrations; +pub mod net; pub mod package; pub mod ra; pub mod registry; pub mod release; pub mod update; +pub mod upnp; pub mod signing; pub mod srp6; diff --git a/crates/coa-core/src/net.rs b/crates/coa-core/src/net.rs new file mode 100644 index 0000000..6b7bf0b --- /dev/null +++ b/crates/coa-core/src/net.rs @@ -0,0 +1,159 @@ +//! Network facts for "Play with Friends": addresses, carrier-grade NAT detection, whether internal services are exposed, +//! and Tailscale (private network) detection. Nothing here changes any setting. + +use std::net::{IpAddr, Ipv4Addr, UdpSocket}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde::Serialize; + +use crate::error::{Error, Result}; + +/// This computer's address on the local network (the interface the default route uses). No packet is sent. +pub fn lan_ip() -> Option { + let s = UdpSocket::bind("0.0.0.0:0").ok()?; + s.connect("192.0.2.1:9").ok()?; // TEST-NET-1: only selects the outgoing interface + match s.local_addr().ok()?.ip() { + IpAddr::V4(v4) if !v4.is_unspecified() && !v4.is_loopback() => Some(v4), + _ => None, + } +} + +pub fn is_private(ip: Ipv4Addr) -> bool { + ip.is_private() || ip.is_loopback() || ip.is_link_local() +} + +/// 100.64.0.0/10: shared address space used by carriers for CGNAT (and by Tailscale for its own network). +pub fn is_cgnat_range(ip: Ipv4Addr) -> bool { + let o = ip.octets(); + o[0] == 100 && (64..=127).contains(&o[1]) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum Reachability { + /// The router's outside address is a normal public address that matches the one the internet sees. + DirectPossible, + /// The router's outside address is private/shared: the provider shares one public address between customers. + Cgnat, + /// Not enough information (no router answer). + Unknown, +} + +/// `router_external`: the address the router reports for its internet side (UPnP); `public`: what an outside service sees. +pub fn classify(router_external: Option, public: Option) -> Reachability { + match (router_external, public) { + (Some(r), _) if is_private(r) || is_cgnat_range(r) => Reachability::Cgnat, + (Some(r), Some(p)) if r != p => Reachability::Cgnat, + (Some(_), Some(_)) => Reachability::DirectPossible, + (Some(r), None) => { + let _ = r; + Reachability::Unknown + } + _ => Reachability::Unknown, + } +} + +/// Ask an outside service which public address this connection comes from. Only called when the user asks. +pub fn public_ip() -> Result { + let client = reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(8)).build().map_err(|e| Error::Invalid(e.to_string()))?; + let text = client.get("https://api.ipify.org").send().and_then(|r| r.text()).map_err(|_| Error::Invalid("Could not reach the internet to find your public address.".into()))?; + text.trim().parse().map_err(|_| Error::Invalid("The address service gave an unexpected answer.".into())) +} + +#[derive(Debug, Clone, Serialize)] +pub struct Exposure { + pub port: u16, + pub what: &'static str, + /// The service accepts connections from other computers. + pub reachable_from_network: bool, + pub listening: bool, +} + +/// For each internal service port: does it listen on more than the loopback interface? MySQL and the server console must not. +pub fn exposure(ports: &crate::layout::Ports) -> Vec { + let all = crate::process::listeners_detailed(); + let check = |port: u16, what: &'static str| { + let rows: Vec<_> = all.iter().filter(|l| l.port == port).collect(); + Exposure { port, what, listening: !rows.is_empty(), reachable_from_network: rows.iter().any(|l| !l.loopback_only) } + }; + vec![check(ports.mysql, "database"), check(ports.ra, "server console"), check(ports.auth, "login server"), check(ports.world, "game world")] +} + +#[derive(Debug, Clone, Serialize)] +pub struct Tailscale { + pub installed: bool, + /// This computer's private address (100.x.y.z) when connected. + pub ip: Option, + pub connected: bool, +} + +fn tailscale_exe() -> Option { + ["C:/Program Files/Tailscale/tailscale.exe", "C:/Program Files (x86)/Tailscale/tailscale.exe"].iter().map(PathBuf::from).find(|p| p.is_file()) +} + +pub fn parse_tailscale_ip(out: &str) -> Option { + out.lines().map(str::trim).find(|l| l.parse::().map(is_cgnat_range).unwrap_or(false)).map(str::to_string) +} + +pub fn tailscale() -> Tailscale { + let Some(exe) = tailscale_exe() else { return Tailscale { installed: false, ip: None, connected: false } }; + let mut c = Command::new(exe); + c.args(["ip", "-4"]); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + c.creation_flags(0x0800_0000); + } + let ip = c.output().ok().filter(|o| o.status.success()).and_then(|o| parse_tailscale_ip(&String::from_utf8_lossy(&o.stdout))); + Tailscale { installed: true, connected: ip.is_some(), ip } +} + +/// Connection text a friend can use: the address to put in the game client. +pub fn instructions(host: &str) -> String { + format!("1. Close the game.\n2. Open the file Data\\enUS\\realmlist.wtf in your game folder (any language folder under Data).\n3. Replace its content with:\n\n set realmlist {host}\n\n4. Start the game and log in with the account your host created for you.\n") +} + +pub fn locate_realmlist_dir(_root: &Path) -> &'static str { + "Data\\enUS\\realmlist.wtf" +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ip(s: &str) -> Ipv4Addr { + s.parse().unwrap() + } + + #[test] + fn address_classes() { + assert!(is_private(ip("192.168.1.5")) && is_private(ip("10.0.0.2")) && is_private(ip("172.16.4.4")) && is_private(ip("127.0.0.1"))); + assert!(!is_private(ip("8.8.8.8"))); + assert!(is_cgnat_range(ip("100.64.0.1")) && is_cgnat_range(ip("100.127.255.254")) && !is_cgnat_range(ip("100.128.0.1")) && !is_cgnat_range(ip("100.63.0.1"))); + } + + #[test] + fn cgnat_detection_from_router_and_public_addresses() { + assert_eq!(classify(Some(ip("203.0.113.9")), Some(ip("203.0.113.9"))), Reachability::DirectPossible); + assert_eq!(classify(Some(ip("100.70.1.1")), Some(ip("203.0.113.9"))), Reachability::Cgnat); + assert_eq!(classify(Some(ip("10.5.5.5")), None), Reachability::Cgnat); + assert_eq!(classify(Some(ip("203.0.113.9")), Some(ip("198.51.100.4"))), Reachability::Cgnat, "router thinks one address, the internet sees another"); + assert_eq!(classify(None, Some(ip("203.0.113.9"))), Reachability::Unknown); + } + + #[test] + fn lan_ip_is_a_private_address_when_present() { + if let Some(a) = lan_ip() { + assert!(!a.is_loopback() && !a.is_unspecified()); + } + } + + #[test] + fn tailscale_output_parsing_and_instructions() { + assert_eq!(parse_tailscale_ip("100.101.102.103\n"), Some("100.101.102.103".into())); + assert_eq!(parse_tailscale_ip("192.168.1.2\n"), None); + assert_eq!(parse_tailscale_ip(""), None); + assert!(instructions("play.example.com").contains("set realmlist play.example.com")); + } +} diff --git a/crates/coa-core/src/process.rs b/crates/coa-core/src/process.rs index 6335400..7d267cd 100644 --- a/crates/coa-core/src/process.rs +++ b/crates/coa-core/src/process.rs @@ -154,6 +154,36 @@ mod sys { Vec::new() } + /// Every TCP listener with its bind address class, IPv4 and IPv6. + pub fn listeners_detailed() -> Vec { + let mut out = Vec::new(); + let u32_at = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()); + let v4 = table(2); + if v4.len() >= 4 { + for i in 0..u32_at(&v4, 0) as usize { + let o = 4 + 24 * i; + if o + 24 > v4.len() { + break; + } + let addr = u32_at(&v4, o + 4).to_le_bytes(); // network order bytes + out.push(super::Listener { port: u16::from_be((u32_at(&v4, o + 8) & 0xFFFF) as u16), pid: u32_at(&v4, o + 20), loopback_only: addr[0] == 127 }); + } + } + let v6 = table(23); + if v6.len() >= 4 { + for i in 0..u32_at(&v6, 0) as usize { + let o = 4 + 56 * i; + if o + 56 > v6.len() { + break; + } + let a = &v6[o..o + 16]; + let loopback = a[..15].iter().all(|b| *b == 0) && a[15] == 1; + out.push(super::Listener { port: u16::from_be((u32_at(&v6, o + 20) & 0xFFFF) as u16), pid: u32_at(&v6, o + 52), loopback_only: loopback }); + } + } + out + } + /// (port, owning pid) for every TCP listener, IPv4 and IPv6. pub fn listeners() -> Vec<(u16, u32)> { let mut out = Vec::new(); @@ -199,9 +229,20 @@ mod sys { pub fn listeners() -> Vec<(u16, u32)> { Vec::new() } + pub fn listeners_detailed() -> Vec { + Vec::new() + } } -pub use sys::{identity, listeners}; +pub use sys::{identity, listeners, listeners_detailed}; + +#[derive(Debug, Clone)] +pub struct Listener { + pub port: u16, + pub pid: u32, + /// Bound to the loopback address only (not reachable from other computers). + pub loopback_only: bool, +} /// True if the recorded identity still describes a live process (same exe and creation time). pub fn is_alive(record: &ProcessIdentity) -> bool { @@ -280,6 +321,16 @@ mod tests { assert!(identity(0xFFFF_FF00).is_none()); } + #[test] + fn detailed_listeners_tell_loopback_from_all_interfaces() { + let lo = TcpListener::bind("127.0.0.1:0").unwrap(); + let any = TcpListener::bind("0.0.0.0:0").unwrap(); + let (p_lo, p_any) = (lo.local_addr().unwrap().port(), any.local_addr().unwrap().port()); + let all = listeners_detailed(); + assert!(all.iter().any(|l| l.port == p_lo && l.pid == std::process::id() && l.loopback_only)); + assert!(all.iter().any(|l| l.port == p_any && !l.loopback_only)); + } + #[test] fn finds_own_listener_and_exe() { let l = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/coa-core/src/upnp.rs b/crates/coa-core/src/upnp.rs new file mode 100644 index 0000000..1cbc771 --- /dev/null +++ b/crates/coa-core/src/upnp.rs @@ -0,0 +1,177 @@ +//! Router port forwarding through UPnP (IGD), for players whose router supports it. Discovery and reading the router's +//! outside address change nothing; adding a mapping only ever touches the login and world ports, with a Manager-owned +//! description so the mappings can be recognised and removed again. + +use std::net::{Ipv4Addr, SocketAddr, UdpSocket}; +use std::time::{Duration, Instant}; + +use crate::error::{Error, Result}; + +pub const DESCRIPTION_PREFIX: &str = "CoA Server Manager"; + +#[derive(Debug, Clone)] +pub struct Gateway { + pub control_url: String, + pub service: String, +} + +fn between<'a>(s: &'a str, open: &str, close: &str) -> Option<&'a str> { + let i = s.find(open)? + open.len(); + let j = s[i..].find(close)? + i; + Some(s[i..j].trim()) +} + +/// `LOCATION:` header of an SSDP response (case-insensitive). +pub fn parse_location(response: &str) -> Option { + response.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + k.trim().eq_ignore_ascii_case("location").then(|| v.trim().to_string()) + }) +} + +fn host_of(url: &str) -> Option { + let rest = url.strip_prefix("http://")?; + rest.split(['/', ':']).next()?.parse().ok() +} + +/// Only devices on the local network are ever contacted (an SSDP answer must not be able to point us elsewhere). +pub fn is_lan_url(url: &str) -> bool { + host_of(url).map(crate::net::is_private).unwrap_or(false) +} + +/// From a device description document: the WAN connection service and its absolute control URL. +pub fn parse_description(xml: &str, location: &str) -> Option { + let mut rest = xml; + while let Some(i) = rest.find("") { + let block = between(&rest[i..], "", "")?; + let stype = between(block, "", "")?; + if stype.contains("WANIPConnection") || stype.contains("WANPPPConnection") { + let control = between(block, "", "")?; + let origin = { + let after = location.strip_prefix("http://")?; + format!("http://{}", after.split('/').next()?) + }; + let base = between(xml, "", "").map(|b| b.trim_end_matches('/').to_string()).unwrap_or(origin); + let url = if control.starts_with("http://") { control.to_string() } else { format!("{base}/{}", control.trim_start_matches('/')) }; + return Some(Gateway { control_url: url, service: stype.to_string() }); + } + rest = &rest[i + "".len()..]; + } + None +} + +fn envelope(service: &str, action: &str, args: &[(&str, String)]) -> String { + let body: String = args.iter().map(|(k, v)| format!("<{k}>{}", v.replace('&', "&").replace('<', "<"))).collect(); + format!("{body}") +} + +fn soap(gw: &Gateway, action: &str, args: &[(&str, String)]) -> Result { + if !is_lan_url(&gw.control_url) { + return Err(Error::Invalid("The router address is not on your network; refusing to contact it.".into())); + } + let client = reqwest::blocking::Client::builder().timeout(Duration::from_secs(6)).build().map_err(|e| Error::Invalid(e.to_string()))?; + let resp = client + .post(&gw.control_url) + .header("Content-Type", "text/xml; charset=\"utf-8\"") + .header("SOAPAction", format!("\"{}#{action}\"", gw.service)) + .body(envelope(&gw.service, action, args)) + .send() + .map_err(|_| Error::Invalid("The router did not answer.".into()))?; + let ok = resp.status().is_success(); + let text = resp.text().unwrap_or_default(); + if ok { + Ok(text) + } else { + Err(Error::Invalid(between(&text, "", "").unwrap_or("the router refused the request").to_string())) + } +} + +/// Look for a UPnP router for a couple of seconds. +pub fn discover() -> Option { + let sock = UdpSocket::bind("0.0.0.0:0").ok()?; + sock.set_read_timeout(Some(Duration::from_millis(600))).ok()?; + let msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 2\r\nST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n\r\n"; + let target: SocketAddr = "239.255.255.250:1900".parse().ok()?; + let _ = sock.send_to(msg.as_bytes(), target); + let deadline = Instant::now() + Duration::from_secs(3); + let mut buf = [0u8; 2048]; + let client = reqwest::blocking::Client::builder().timeout(Duration::from_secs(4)).build().ok()?; + while Instant::now() < deadline { + let Ok((n, _)) = sock.recv_from(&mut buf) else { continue }; + let Some(loc) = parse_location(&String::from_utf8_lossy(&buf[..n])) else { continue }; + if !is_lan_url(&loc) { + continue; + } + if let Some(gw) = client.get(&loc).send().ok().and_then(|r| r.text().ok()).and_then(|x| parse_description(&x, &loc)) { + return Some(gw); + } + } + None +} + +/// The address the router has on the internet side. +pub fn external_ip(gw: &Gateway) -> Result { + let text = soap(gw, "GetExternalIPAddress", &[])?; + between(&text, "", "") + .and_then(|s| s.parse().ok()) + .ok_or_else(|| Error::Invalid("The router did not report an outside address.".into())) +} + +pub fn add_mapping(gw: &Gateway, port: u16, lan: Ipv4Addr, what: &str) -> Result<()> { + soap( + gw, + "AddPortMapping", + &[ + ("NewRemoteHost", String::new()), + ("NewExternalPort", port.to_string()), + ("NewProtocol", "TCP".into()), + ("NewInternalPort", port.to_string()), + ("NewInternalClient", lan.to_string()), + ("NewEnabled", "1".into()), + ("NewPortMappingDescription", format!("{DESCRIPTION_PREFIX} - {what}")), + ("NewLeaseDuration", "0".into()), + ], + ) + .map(|_| ()) +} + +pub fn remove_mapping(gw: &Gateway, port: u16) -> Result<()> { + soap(gw, "DeletePortMapping", &[("NewRemoteHost", String::new()), ("NewExternalPort", port.to_string()), ("NewProtocol", "TCP".into())]).map(|_| ()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const DESC: &str = "\ + urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1/ctl/common\ + urn:schemas-upnp-org:service:WANIPConnection:1/ctl/IPConn\ + "; + + #[test] + fn parses_ssdp_location_and_description() { + let resp = "HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age=120\r\nLocation: http://192.168.1.1:5000/rootDesc.xml\r\nST: x\r\n\r\n"; + let loc = parse_location(resp).unwrap(); + assert_eq!(loc, "http://192.168.1.1:5000/rootDesc.xml"); + let gw = parse_description(DESC, &loc).unwrap(); + assert_eq!(gw.control_url, "http://192.168.1.1:5000/ctl/IPConn"); + assert!(gw.service.ends_with("WANIPConnection:1")); + assert!(parse_description("", &loc).is_none()); + } + + #[test] + fn only_lan_devices_are_contacted() { + assert!(is_lan_url("http://192.168.1.1:5000/x") && is_lan_url("http://10.0.0.1/x")); + assert!(!is_lan_url("http://8.8.8.8/x") && !is_lan_url("https://192.168.1.1/x") && !is_lan_url("http://example.com/x")); + let evil = Gateway { control_url: "http://203.0.113.5/ctl".into(), service: "urn:x".into() }; + assert!(external_ip(&evil).is_err(), "a public address is refused before any request"); + assert!(add_mapping(&evil, 3724, "192.168.1.5".parse().unwrap(), "Auth").is_err()); + } + + #[test] + fn envelopes_carry_only_the_requested_port_and_escape_values() { + let e = envelope("urn:s", "AddPortMapping", &[("NewExternalPort", "3724".into()), ("NewPortMappingDescription", "a3724") && e.contains("a<b&c")); + assert!(e.contains("")); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6463c7b..543ce61 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -187,7 +187,13 @@ async fn run_verb(state: &AppState, id: String, verb: Verb) -> std::result::Resu #[tauri::command] async fn start_server(state: State<'_, AppState>, id: String) -> std::result::Result { - run_verb(&state, id, Verb::StartAll).await + let out = run_verb(&state, id.clone(), Verb::StartAll).await?; + if out.ok { + if let Ok(root) = path_of(&state, &id) { + let _ = tauri::async_runtime::spawn_blocking(move || meta_dir(&root).and_then(|m| coa_core::friends::reapply(&root, &m))).await; + } + } + Ok(out) } #[tauri::command] @@ -585,6 +591,131 @@ async fn play(state: State<'_, AppState>, id: String) -> std::result::Result, + exposure: Vec, + /// The configuration lets other computers reach the login and world servers. + servers_open: bool, + firewall: coa_core::firewall::Status, + tailscale: coa_core::net::Tailscale, + server_running: bool, +} + +#[tauri::command] +async fn friends_status(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let meta = meta_dir(&root)?; + let ports = layout::read_ports(&root); + Ok(FriendsStatus { + settings: coa_core::friends::load(&meta), + lan_ip: coa_core::net::lan_ip().map(|a| a.to_string()), + exposure: coa_core::net::exposure(&ports), + servers_open: coa_core::friends::bind_is_open(&root), + firewall: coa_core::firewall::status(), + tailscale: coa_core::net::tailscale(), + server_running: coa_core::process::observe(&root, &ports).world.state == coa_core::process::ServiceState::Running, + }) + }) + .await +} + +#[derive(Serialize)] +struct InternetCheck { + public_ip: Option, + router_ip: Option, + reachability: coa_core::net::Reachability, + router_found: bool, +} + +/// Talks to an outside address service and to the router. Only runs when the user presses the button. +#[tauri::command] +async fn friends_check_internet() -> std::result::Result { + blocking(move || { + let public = coa_core::net::public_ip().ok(); + let gw = coa_core::upnp::discover(); + let router = gw.as_ref().and_then(|g| coa_core::upnp::external_ip(g).ok()); + Ok(InternetCheck { + public_ip: public.map(|a| a.to_string()), + router_ip: router.map(|a| a.to_string()), + reachability: coa_core::net::classify(router, public), + router_found: gw.is_some(), + }) + }) + .await +} + +#[derive(Serialize)] +struct FriendsResult { + host: String, + restart_required: bool, + note: Option, +} + +/// Switch how friends connect. `host` is only needed for the internet mode (the public address from the check). +#[tauri::command] +async fn friends_enable( + state: State<'_, AppState>, + id: String, + mode: coa_core::friends::Mode, + host: Option, + use_upnp: bool, +) -> std::result::Result { + use coa_core::friends::{self, Mode, Settings}; + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let meta = meta_dir(&root)?; + let ports = layout::read_ports(&root); + let mut note = None; + let host = match mode { + Mode::Local => "127.0.0.1".to_string(), + Mode::Lan => coa_core::net::lan_ip().ok_or_else(|| Error::Invalid("This computer has no network address.".into()))?.to_string(), + Mode::Direct => host.filter(|h| !h.is_empty()).ok_or_else(|| Error::Invalid("Check your connection first to learn your public address.".into()))?, + Mode::Private => coa_core::net::tailscale().ip.ok_or_else(|| Error::Invalid("Tailscale is not connected. Install it, sign in, then try again.".into()))?, + }; + let open = mode != Mode::Local; + let changed = friends::set_open(&root, &meta, open)?; + if open { + coa_core::firewall::ensure_rules(&ports)?; + } + if mode == Mode::Direct && use_upnp { + match coa_core::upnp::discover() { + Some(gw) => { + let lan = coa_core::net::lan_ip().ok_or_else(|| Error::Invalid("No local address.".into()))?; + coa_core::upnp::add_mapping(&gw, ports.auth, lan, "Auth")?; + coa_core::upnp::add_mapping(&gw, ports.world, lan, "World")?; + note = Some("Your router was asked to forward the game ports.".to_string()); + } + None => note = Some("Your router does not support automatic setup; forward the two game ports by hand or use the private network.".to_string()), + } + } + friends::save(&meta, &Settings { mode, host: Some(host.clone()) })?; + let running = coa_core::process::observe(&root, &ports).world.state == coa_core::process::ServiceState::Running; + if running { + friends::apply_realm_address(&root, &host)?; + } + Ok(FriendsResult { host, restart_required: changed && running, note }) + }) + .await +} + +#[tauri::command] +async fn friends_package(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let meta = meta_dir(&root)?; + let host = coa_core::friends::load(&meta).host.ok_or_else(|| Error::Invalid("Choose how friends connect first.".into()))?; + let desktop = std::env::var_os("USERPROFILE").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("Desktop"); + let out = if desktop.is_dir() { desktop } else { std::env::temp_dir() }.join("CoA-Friend-Setup.zip"); + coa_core::friends::make_friend_package(&root, &host, true, &out)?; + Ok(out.to_string_lossy().into_owned()) + }) + .await +} + pub fn run() { let dir = data_dir(); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); @@ -627,7 +758,11 @@ pub fn run() { set_client, client_realmlist, client_install_addon, - play + play, + friends_status, + friends_check_internet, + friends_enable, + friends_package ]) .run(tauri::generate_context!()) .expect("error while running CoA Server Manager"); diff --git a/src/lib/api.ts b/src/lib/api.ts index 87cb038..256fb17 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -217,6 +217,25 @@ export interface ClientInfo { other_addons: number; } +export type FriendsMode = "local" | "lan" | "direct" | "private"; + +export interface FriendsStatus { + settings: { mode: FriendsMode; host: string | null }; + lan_ip: string | null; + exposure: { port: number; what: string; reachable_from_network: boolean; listening: boolean }[]; + servers_open: boolean; + firewall: { auth: boolean; world: boolean }; + tailscale: { installed: boolean; ip: string | null; connected: boolean }; + server_running: boolean; +} + +export interface InternetCheck { + public_ip: string | null; + router_ip: string | null; + reachability: "direct_possible" | "cgnat" | "unknown"; + router_found: boolean; +} + export const api = { defaultInstallDir: () => invoke("default_install_dir"), scan: (path: string) => invoke("scan_server", { path }), @@ -253,6 +272,11 @@ export const api = { setRealmlist: (id: string, host: string) => invoke("client_realmlist", { id, host }), installAddon: (id: string) => invoke("client_install_addon", { id }), play: (id: string) => invoke("play", { id }), + friendsStatus: (id: string) => invoke("friends_status", { id }), + friendsCheckInternet: () => invoke("friends_check_internet"), + friendsEnable: (id: string, mode: FriendsMode, host?: string, useUpnp = false) => + invoke<{ host: string; restart_required: boolean; note: string | null }>("friends_enable", { id, mode, host: host ?? null, useUpnp }), + friendsPackage: (id: string) => invoke("friends_package", { id }), previewPreset: (id: string, scope: Scope, preset: string) => invoke("preview_preset", { id, scope, preset }), }; diff --git a/src/screens/FriendsPage.tsx b/src/screens/FriendsPage.tsx new file mode 100644 index 0000000..4b491c7 --- /dev/null +++ b/src/screens/FriendsPage.tsx @@ -0,0 +1,170 @@ +import { useCallback, useEffect, useState } from "react"; +import { Check, Loader2, Minus } from "lucide-react"; +import { api, asUiError, type FriendsMode, type FriendsStatus, type InternetCheck, type UiError } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; + +function Line({ ok, children, warn }: { ok: boolean; warn?: boolean; children: React.ReactNode }) { + return ( +
  • + {ok ? : } + {children} + {ok ? "OK" : "not yet"} +
  • + ); +} + +const MODES: { id: FriendsMode; title: string; text: string }[] = [ + { id: "lan", title: "Local network", text: "Friends on the same home network or Wi-Fi." }, + { id: "direct", title: "Over the internet", text: "Friends anywhere, through your internet connection. Needs your router to allow it." }, + { id: "private", title: "Private network", text: "Friends anywhere, no router setup. Uses the free Tailscale app." }, +]; + +export function FriendsPage({ serverId }: { serverId: string }) { + const [st, setSt] = useState(null); + const [net, setNet] = useState(null); + const [busy, setBusy] = useState(null); + const [error, setError] = useState(null); + const [note, setNote] = useState(null); + const [copied, setCopied] = useState(false); + + const refresh = useCallback(() => api.friendsStatus(serverId).then(setSt).catch((e) => setError(asUiError(e))), [serverId]); + useEffect(() => { + void refresh(); + }, [refresh]); + + async function run(label: string, fn: () => Promise) { + setBusy(label); + setError(null); + setNote(null); + try { + const msg = await fn(); + if (msg) setNote(msg); + await refresh(); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + } + } + + const check = () => + run("check", async () => { + setNet(await api.friendsCheckInternet()); + }); + + const enable = (mode: FriendsMode) => + run(`enable-${mode}`, async () => { + const r = await api.friendsEnable(serverId, mode, net?.public_ip ?? undefined, mode === "direct" && !!net?.router_found); + return [r.restart_required ? "Restart the server to apply this." : null, r.note].filter(Boolean).join(" ") || "Ready for friends."; + }); + + if (!st) return

    {error ? error.human.message : "Looking at your connection…"}

    ; + + const cur = st.settings; + const exposed = st.exposure.filter((e) => (e.what === "database" || e.what === "server console") && e.reachable_from_network); + const connection = cur.mode === "local" ? null : `set realmlist ${cur.host}`; + + return ( +
    +

    Play with Friends

    +

    How can my friend join?

    + + {exposed.length > 0 && ( + +

    Something private is reachable from your network

    +

    {exposed.map((e) => e.what).join(" and ")} accept connections from other computers. Restart the server from this program to close them.

    +
    + )} + + +

    Status

    +
      + Server is running + Login and game servers are open to other computers + Windows Firewall allows the game ports + e.what === "database" || e.what === "server console").every((e) => !e.reachable_from_network)}> + Database and server console are private to this computer + +
    +
    + +
    + {MODES.map((m) => ( + +
    +
    +

    + {m.title} {cur.mode === m.id && In use} +

    +

    {m.text}

    + + {m.id === "lan" &&

    Your address on this network: {st.lan_ip ?? "unknown"}

    } + + {m.id === "direct" && ( +
    + + {net && net.reachability === "cgnat" && ( +

    + Your internet provider does not allow direct hosting. Use the private network instead. +

    + )} + {net?.public_ip && net.reachability !== "cgnat" && ( +

    Your public address: {net.public_ip}{!net.router_found && · your router cannot be set up automatically; forward the two game ports by hand}

    + )} + {net && !net.public_ip &&

    Could not reach the internet to find your address.

    } +
    + )} + + {m.id === "private" && ( +

    + {!st.tailscale.installed && Tailscale is not installed. Install the free app from tailscale.com/download, sign in, then come back.} + {st.tailscale.installed && !st.tailscale.connected && Tailscale is installed but not connected. Sign in to it first.} + {st.tailscale.connected && <>Your private address: {st.tailscale.ip}} +

    + )} +
    + +
    +
    + ))} + {cur.mode !== "local" && ( + + )} +
    + + {connection && ( + +

    Give this to your friend

    +

    They put this line in their game's realmlist.wtf file. Passwords and settings are never shared.

    +
    {connection}
    +
    + + +
    +
    + )} + + {note &&

    {note}

    } + {error &&

    {error.human.code === "unknown" ? error.technical : error.human.message}

    } +
    + ); +} diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index dd51b13..007fac3 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -8,6 +8,7 @@ import { SettingsPage } from "@/screens/SettingsPage"; import { BackupsPage } from "@/screens/BackupsPage"; import { PlayersPage } from "@/screens/PlayersPage"; import { SettingsHome } from "@/screens/SettingsHome"; +import { FriendsPage } from "@/screens/FriendsPage"; import { Button } from "@/components/ui/button"; type Page = "overview" | "bots" | "server" | "players" | "friends" | "backups" | "console" | "settings"; @@ -82,6 +83,8 @@ export function Shell(props: { props.onForget(server.id)} /> ) : page === "bots" || page === "server" ? ( + ) : page === "friends" ? ( + ) : page === "settings" ? ( ) : page === "players" ? (