mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-25 03:25:56 +00:00
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
e7b466a977
commit
1609c4f6bf
14 files changed
+1154
-4
No files matched your search
@@ -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"] }
|
||||
|
||||
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
@@ -277,7 +277,7 @@ pub struct SnapshotInfo {
|
||||
files: Vec<SnapshotFile>,
|
||||
}
|
||||
|
||||
fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec<u8>)]) -> Result<String> {
|
||||
pub(crate) fn take_snapshot(meta_dir: &Path, scope: Scope, reason: &str, files: &[(PathBuf, Vec<u8>)]) -> Result<String> {
|
||||
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)?;
|
||||
|
||||
@@ -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<String> {
|
||||
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<Status> {
|
||||
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"));
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
}
|
||||
|
||||
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<PathBuf> {
|
||||
["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<bool> {
|
||||
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<String> = (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());
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<Ipv4Addr> {
|
||||
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<Ipv4Addr>, public: Option<Ipv4Addr>) -> 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<Ipv4Addr> {
|
||||
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<Exposure> {
|
||||
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<String>,
|
||||
pub connected: bool,
|
||||
}
|
||||
|
||||
fn tailscale_exe() -> Option<PathBuf> {
|
||||
["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<String> {
|
||||
out.lines().map(str::trim).find(|l| l.parse::<Ipv4Addr>().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"));
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,36 @@ mod sys {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Every TCP listener with its bind address class, IPv4 and IPv6.
|
||||
pub fn listeners_detailed() -> Vec<super::Listener> {
|
||||
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<super::Listener> {
|
||||
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();
|
||||
|
||||
@@ -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<String> {
|
||||
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<Ipv4Addr> {
|
||||
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<Gateway> {
|
||||
let mut rest = xml;
|
||||
while let Some(i) = rest.find("<service>") {
|
||||
let block = between(&rest[i..], "<service>", "</service>")?;
|
||||
let stype = between(block, "<serviceType>", "</serviceType>")?;
|
||||
if stype.contains("WANIPConnection") || stype.contains("WANPPPConnection") {
|
||||
let control = between(block, "<controlURL>", "</controlURL>")?;
|
||||
let origin = {
|
||||
let after = location.strip_prefix("http://")?;
|
||||
format!("http://{}", after.split('/').next()?)
|
||||
};
|
||||
let base = between(xml, "<URLBase>", "</URLBase>").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 + "<service>".len()..];
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn envelope(service: &str, action: &str, args: &[(&str, String)]) -> String {
|
||||
let body: String = args.iter().map(|(k, v)| format!("<{k}>{}</{k}>", v.replace('&', "&").replace('<', "<"))).collect();
|
||||
format!("<?xml version=\"1.0\"?><s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><s:Body><u:{action} xmlns:u=\"{service}\">{body}</u:{action}></s:Body></s:Envelope>")
|
||||
}
|
||||
|
||||
fn soap(gw: &Gateway, action: &str, args: &[(&str, String)]) -> Result<String> {
|
||||
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, "<errorDescription>", "</errorDescription>").unwrap_or("the router refused the request").to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Look for a UPnP router for a couple of seconds.
|
||||
pub fn discover() -> Option<Gateway> {
|
||||
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<Ipv4Addr> {
|
||||
let text = soap(gw, "GetExternalIPAddress", &[])?;
|
||||
between(&text, "<NewExternalIPAddress>", "</NewExternalIPAddress>")
|
||||
.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 = "<root><device><deviceList><device><deviceList><device><serviceList>\
|
||||
<service><serviceType>urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1</serviceType><controlURL>/ctl/common</controlURL></service>\
|
||||
<service><serviceType>urn:schemas-upnp-org:service:WANIPConnection:1</serviceType><controlURL>/ctl/IPConn</controlURL></service>\
|
||||
</serviceList></device></deviceList></device></deviceList></device></root>";
|
||||
|
||||
#[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("<root></root>", &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", "a<b&c".into())]);
|
||||
assert!(e.contains("<NewExternalPort>3724</NewExternalPort>") && e.contains("a<b&c"));
|
||||
assert!(e.contains("<u:AddPortMapping xmlns:u=\"urn:s\">"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user