From cf5ba34bed233da2ee5d2d57657cf48ee61b719f Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 22 Nov 2026 23:26:18 +0100 Subject: [PATCH] [core] Parsers: strict VDF, Steam, Epic, GOG, manual and Domi sources, WinPath, GameId, Launch URIs, merge --- README.md | 65 ++++ crates/arena-core/src/domi.rs | 24 +- crates/arena-core/src/epic.rs | 132 +++++++- crates/arena-core/src/gog.rs | 41 ++- crates/arena-core/src/id.rs | 35 ++- crates/arena-core/src/launch.rs | 183 ++++++++++-- crates/arena-core/src/manual.rs | 30 +- crates/arena-core/src/model.rs | 56 +++- crates/arena-core/src/path.rs | 87 +++++- crates/arena-core/src/steam.rs | 92 +++++- crates/arena-core/src/text.rs | 67 ++++- crates/arena-core/src/vdf.rs | 281 +++++++++++++++++- .../tests/fixtures/epic/absurd.item | 2 +- .../arena-core/tests/fixtures/epic/addon.item | 2 +- .../tests/fixtures/epic/badappname.item | 2 +- .../tests/fixtures/epic/dupkey.item | 2 +- .../tests/fixtures/epic/missing.item | 2 +- .../tests/fixtures/epic/trailing.item | 2 +- .../tests/fixtures/epic/traversal.item | 2 +- .../arena-core/tests/fixtures/epic/unc.item | 2 +- .../arena-core/tests/fixtures/epic/valid.item | 4 +- .../tests/fixtures/epic/wrongtype.item | 2 +- .../fixtures/steam/appmanifest_1234560.acf | 2 +- .../fixtures/steam/appmanifest_absolute.acf | 2 +- .../fixtures/steam/appmanifest_traversal.acf | 2 +- .../tests/fixtures/steam/libraryfolders.vdf | 4 +- .../fixtures/steam/libraryfolders_dup.vdf | 4 +- .../fixtures/steam/libraryfolders_old.vdf | 2 +- .../fixtures/steam/libraryfolders_unc.vdf | 2 +- crates/arena-core/tests/steam.rs | 2 +- docs/FORMATS.md | 203 +++++++++++++ docs/PORTABILITY.md | 37 +++ 32 files changed, 1275 insertions(+), 100 deletions(-) create mode 100644 docs/FORMATS.md create mode 100644 docs/PORTABILITY.md diff --git a/README.md b/README.md index 5d0cf70..7d264ba 100644 --- a/README.md +++ b/README.md @@ -6,3 +6,68 @@ frametime statistics and replay-ring logic. No I/O: inputs are bytes or values, Windows, Android and WebAssembly. Licence: MPL-2.0 (see LICENSE). + +## Crates + +| Crate | Lib | What it holds | +| :-- | :-- | :-- | +| `crates/arena-core` | `arena_core` | launcher parsers, `WinPath`, `GameId`, `Launch`, the `Game` / `Library` model, `merge` | + +## `arena-core` in one screen + +Pure: no `std::fs`, `std::process`, network, environment, registry or clock. The window app reads the files and +registry values (capped) and hands the bytes or values in. Every parser treats its input as hostile: caps on size, +depth, lengths and counts, typed errors, no panics, `#![forbid(unsafe_code)]`. + +```rust +use arena_core::{merge, steam, epic, gog, manual, domi, DomiLaunch, WinPath, Launch}; + +// Steam: the library folders, then one manifest per installed app. +let libraries: Vec = steam::library_folders(&vdf_bytes)?; +let game = steam::app_manifest(&acf_bytes, &libraries[0])?; // Err(NotAGame) for redistributables +let id = steam::app_id_from_manifest_name("appmanifest_10.acf"); // Some(10): filter a folder listing + +// Epic: one `.item` JSON manifest per app. +let game = epic::item(&item_bytes)?; // Err(NotAGame) for add-ons + +// GOG: registry values the app read. +let game = gog::game(&gog::GogEntry { game_id, name, path, exe, working_dir, launch_params })?; + +// A game the user picked, and a Domi game from the Atrium registry. +let game = manual::game(r"D:\Games\Old\old.exe", None)?; +let game = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" })?; +let game = domi::game("rosea", "Rosea", DomiLaunch::Web { url, allowed_hosts: &["rosea.example.org"] })?; + +// One library: the same id once, the same install folder kept for the best source +// (Steam > Epic > GOG > Domi > Manual), ordered by title. +let library = merge(vec![steam_games, epic_games, gog_games, domi_games, manual_games]); + +// Launching: a URI for the protocol variants, built only from validated fields. +match &game.launch { + Launch::Exe { exe, working_dir, args } => { /* Command::new(exe).current_dir(working_dir).args(args) */ } + Launch::Url(_) => { let uri = game.launch.uri_checked(&allowed_hosts); } + other => { let uri = other.uri(); } // steam://, com.epicgames.launcher://, domi-:// +} +``` + +| Type | Rule | +| :-- | :-- | +| `GameId` | `:`, `[a-z0-9:._-]`, at most 96 bytes, checked per source; `Display` + strict `FromStr` | +| `WinPath` | absolute with a drive letter; no UNC, `\\?\`, `..`, NUL, device names; at most 260 UTF-16 units | +| `Launch` | `SteamRunGameId(u32)`, `Epic { app_name }`, `Exe { exe, working_dir, args }`, `DomiLink { app }`, `Url` | +| `Game` | `{ id, source, title, install_dir, launch, cover }`; serde round trip validates every field | +| `ParseError` | typed, `Display`, never carries input text | + +`Game`, `Library`, `GameId`, `WinPath` and `Launch` serialise with serde, and deserialising runs the same checks +as the parsers, so a tampered `library.json` cannot smuggle in a bad path or launch string. + +Docs: [`docs/FORMATS.md`](docs/FORMATS.md) (what each parser accepts and refuses, every cap) and +[`docs/PORTABILITY.md`](docs/PORTABILITY.md) (the target checks). + +## Commands + +``` +cargo test # unit, hostile, property, launch and dedupe tests +cargo clippy --all-targets -- -D warnings +cargo fmt --check +``` diff --git a/crates/arena-core/src/domi.rs b/crates/arena-core/src/domi.rs index e268dc0..69bd092 100644 --- a/crates/arena-core/src/domi.rs +++ b/crates/arena-core/src/domi.rs @@ -6,7 +6,10 @@ //! web games (Rosea, Moin) opened by URL. use crate::error::ParseError; -use crate::model::Game; +use crate::id::{GameId, Source}; +use crate::launch::Launch; +use crate::model::{CoverHint, Game}; +use crate::text; /// How a Domi game starts. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -20,6 +23,21 @@ pub enum DomiLaunch<'a> { /// The game for one Domi entry. `id` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end) and /// becomes `domi:`; `name` is the title. No install folder. pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result { - let _ = (id, name, launch); - Err(ParseError::BadId) + if !text::is_atrium_id(id) { + return Err(ParseError::BadId); + } + let title = text::title(name, "name")?; + let launch = match launch { + DomiLaunch::Link { app } => Launch::domi_link(app)?, + DomiLaunch::Web { url, allowed_hosts } => Launch::web(url, allowed_hosts)?, + }; + let id = GameId::new(Source::Domi, id)?; + Ok(Game { + cover: Some(CoverHint::lettered(&title, &id)), + id, + source: Source::Domi, + title, + install_dir: None, + launch, + }) } diff --git a/crates/arena-core/src/epic.rs b/crates/arena-core/src/epic.rs index 48c3023..3770a55 100644 --- a/crates/arena-core/src/epic.rs +++ b/crates/arena-core/src/epic.rs @@ -7,12 +7,138 @@ //! `com.epicgames.launcher://apps/?action=launch&silent=true`. use crate::error::ParseError; -use crate::model::Game; +use crate::id::{GameId, Source}; +use crate::launch::Launch; +use crate::limits::{MAX_DEPTH, MAX_FILE}; +use crate::model::{CoverHint, Game}; +use crate::path::WinPath; +use crate::text; +use serde::de::IgnoredAny; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; + +/// The fields read from a manifest. Present-but-`null` is kept apart from absent, so `null` is a wrong type. +#[derive(Deserialize)] +struct Raw { + #[serde(rename = "AppName", default, deserialize_with = "present")] + app_name: Option, + #[serde(rename = "DisplayName", default, deserialize_with = "present")] + display_name: Option, + #[serde(rename = "InstallLocation", default, deserialize_with = "present")] + install_location: Option, + #[serde(rename = "MainGameAppName", default, deserialize_with = "present")] + main_game_app_name: Option, +} + +const FIELDS: [&str; 4] = ["AppName", "DisplayName", "InstallLocation", "MainGameAppName"]; + +fn present<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + Value::deserialize(d).map(Some) +} /// The game described by one `.item` manifest. Reads `AppName`, `DisplayName` and `InstallLocation` (all /// required strings) and `MainGameAppName` (optional; when it names another app the file is an add-on and gives /// [`ParseError::NotAGame`]). Other fields are ignored but must still be well-formed JSON within the caps. pub fn item(json: &[u8]) -> Result { - let _ = json; - Err(ParseError::Syntax { at: 0 }) + if json.len() > MAX_FILE { + return Err(ParseError::TooLarge); + } + let whole = std::str::from_utf8(json).map_err(|_| ParseError::NotUtf8)?; + let (bom, text) = match whole.strip_prefix('\u{feff}') { + Some(rest) => (3, rest), + None => (0, whole), + }; + check_depth(text)?; + // serde would read a struct from an array too; only an object is a manifest. + if !text.trim_start().starts_with('{') { + return Err(match serde_json::from_str::(text) { + Ok(_) => ParseError::WrongType("item"), + Err(e) => map_error(&e, text, bom), + }); + } + let raw: Raw = serde_json::from_str(text).map_err(|e| map_error(&e, text, bom))?; + + let app_name = required(raw.app_name.as_ref(), "AppName")?; + let display_name = required(raw.display_name.as_ref(), "DisplayName")?; + let install_location = required(raw.install_location.as_ref(), "InstallLocation")?; + let main_game = optional(raw.main_game_app_name.as_ref(), "MainGameAppName")?; + + let launch = Launch::epic(app_name)?; + let title = text::title(display_name, "DisplayName")?; + let install_dir = WinPath::parse(install_location).map_err(|_| ParseError::BadPath("InstallLocation"))?; + if main_game.is_some_and(|m| m != app_name) { + return Err(ParseError::NotAGame("Epic add-on")); + } + let id = GameId::new(Source::Epic, &app_name.to_ascii_lowercase())?; + Ok(Game { + cover: Some(CoverHint::lettered(&title, &id)), + id, + source: Source::Epic, + title, + install_dir: Some(install_dir), + launch, + }) +} + +fn required<'a>(v: Option<&'a Value>, field: &'static str) -> Result<&'a str, ParseError> { + optional(v, field)?.ok_or(ParseError::Missing(field)) +} + +fn optional<'a>(v: Option<&'a Value>, field: &'static str) -> Result, ParseError> { + match v { + None => Ok(None), + Some(Value::String(s)) => Ok(Some(s)), + Some(_) => Err(ParseError::WrongType(field)), + } +} + +/// Refuses nesting deeper than `MAX_DEPTH` before serde sees the text (objects and arrays both count; brackets +/// inside strings do not). +fn check_depth(text: &str) -> Result<(), ParseError> { + let mut depth = 0usize; + let mut in_string = false; + let mut escaped = false; + for b in text.bytes() { + if in_string { + match (escaped, b) { + (true, _) => escaped = false, + (false, b'\\') => escaped = true, + (false, b'"') => in_string = false, + _ => {} + } + continue; + } + match b { + b'"' => in_string = true, + b'{' | b'[' => { + depth += 1; + if depth > MAX_DEPTH { + return Err(ParseError::TooDeep); + } + } + b'}' | b']' => depth = depth.saturating_sub(1), + _ => {} + } + } + Ok(()) +} + +/// Turns a serde_json error into a typed one: a repeated field, a document that is not an object, or a syntax +/// error at a byte offset into the original input. +fn map_error(e: &serde_json::Error, text: &str, bom: usize) -> ParseError { + if e.is_data() { + let msg = e.to_string(); + if msg.starts_with("duplicate field") { + let field = FIELDS.into_iter().find(|f| msg.contains(&format!("`{f}`"))).unwrap_or("field"); + return ParseError::Duplicate(field); + } + return ParseError::WrongType("item"); + } + ParseError::Syntax { at: bom + offset(text, e.line(), e.column()) } +} + +/// The byte offset of serde_json's 1-based line and column, clamped to the text. +fn offset(text: &str, line: usize, column: usize) -> usize { + let line_start: usize = text.split_inclusive('\n').take(line.saturating_sub(1)).map(str::len).sum(); + (line_start + column.saturating_sub(1)).min(text.len().saturating_sub(1)) } diff --git a/crates/arena-core/src/gog.rs b/crates/arena-core/src/gog.rs index 101be8c..2f4be0c 100644 --- a/crates/arena-core/src/gog.rs +++ b/crates/arena-core/src/gog.rs @@ -7,7 +7,12 @@ //! `workingDir`, `launchParam`) and passes the values in. Launch is the `.exe` directly. use crate::error::ParseError; -use crate::model::Game; +use crate::id::{GameId, Source}; +use crate::launch::{Launch, split_args}; +use crate::limits::MAX_GOG_ID; +use crate::model::{CoverHint, Game}; +use crate::path::WinPath; +use crate::text; /// The registry values of one GOG game, as the app read them. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -28,6 +33,36 @@ pub struct GogEntry { /// The game for one GOG entry. pub fn game(e: &GogEntry) -> Result { - let _ = e; - Err(ParseError::BadId) + if !(1..=MAX_GOG_ID).contains(&e.game_id.len()) || !e.game_id.bytes().all(|b| b.is_ascii_digit()) { + return Err(ParseError::BadId); + } + let title = text::title(&e.name, "name")?; + let path = WinPath::parse(&e.path).map_err(|_| ParseError::BadPath("path"))?; + let exe = resolve(&path, &e.exe).map_err(|_| ParseError::BadPath("exe"))?; + if !exe.starts_with(&path) || exe == path || !text::is_exe(&exe) { + return Err(ParseError::BadPath("exe")); + } + let working_dir = match e.working_dir.as_deref().map(str::trim) { + None | Some("") => exe.parent().ok_or(ParseError::BadPath("exe"))?, + Some(w) => resolve(&path, w).map_err(|_| ParseError::BadPath("working_dir"))?, + }; + let args = match e.launch_params.as_deref() { + None => Vec::new(), + Some(line) => split_args(line)?, + }; + let id = GameId::new(Source::Gog, &e.game_id)?; + Ok(Game { + cover: Some(CoverHint::lettered(&title, &id)), + id, + source: Source::Gog, + title, + install_dir: Some(path), + launch: Launch::exe(exe, working_dir, args)?, + }) +} + +/// An absolute path as it is, a relative one inside `base`. +fn resolve(base: &WinPath, s: &str) -> Result { + let absolute = s.get(1..2) == Some(":") || s.starts_with(['\\', '/']); + if absolute { WinPath::parse(s) } else { base.join(s) } } diff --git a/crates/arena-core/src/id.rs b/crates/arena-core/src/id.rs index a175759..ceb75ed 100644 --- a/crates/arena-core/src/id.rs +++ b/crates/arena-core/src/id.rs @@ -3,6 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::error::ParseError; +use crate::limits::{MAX_GAME_ID, MAX_GOG_ID}; +use crate::text; use serde::{Deserialize, Serialize}; use std::fmt; use std::str::FromStr; @@ -72,8 +74,14 @@ pub struct GameId(String); impl GameId { /// Builds and checks `:`. pub fn new(source: Source, native: &str) -> Result { - let _ = (source, native); - Err(ParseError::BadId) + if !native_ok(source, native) { + return Err(ParseError::BadId); + } + let id = format!("{source}:{native}"); + if id.len() > MAX_GAME_ID { + return Err(ParseError::BadId); + } + Ok(GameId(id)) } pub fn as_str(&self) -> &str { @@ -82,12 +90,13 @@ impl GameId { /// The source named by the prefix. pub fn source(&self) -> Source { - Source::Manual + // Every GameId was built by `new`, so the prefix is a known source. + self.0.split_once(':').and_then(|(s, _)| s.parse().ok()).unwrap_or(Source::Manual) } /// The part after `:`. pub fn native(&self) -> &str { - "" + self.0.split_once(':').map_or("", |(_, n)| n) } } @@ -101,8 +110,22 @@ impl FromStr for GameId { type Err = ParseError; fn from_str(s: &str) -> Result { - let _ = s; - Err(ParseError::BadId) + if s.len() > MAX_GAME_ID { + return Err(ParseError::BadId); + } + let (source, native) = s.split_once(':').ok_or(ParseError::BadId)?; + GameId::new(source.parse()?, native) + } +} + +/// The per-source rule for the part after `:`. +fn native_ok(source: Source, native: &str) -> bool { + match source { + Source::Steam => text::canonical_u32(native).is_some(), + Source::Epic => text::is_epic_app(native) && !native.bytes().any(|b| b.is_ascii_uppercase()), + Source::Gog => (1..=MAX_GOG_ID).contains(&native.len()) && native.bytes().all(|b| b.is_ascii_digit()), + Source::Manual => native.len() == 16 && native.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')), + Source::Domi => text::is_atrium_id(native), } } diff --git a/crates/arena-core/src/launch.rs b/crates/arena-core/src/launch.rs index 9a185f1..e9cba8d 100644 --- a/crates/arena-core/src/launch.rs +++ b/crates/arena-core/src/launch.rs @@ -3,7 +3,9 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::error::ParseError; +use crate::limits::{MAX_ARG, MAX_ARGS, MAX_ARGS_LINE, MAX_HOST, MAX_URL}; use crate::path::WinPath; +use crate::text; use serde::{Deserialize, Serialize}; /// How to start a game. The protocol variants become a URI through [`Launch::uri`]; [`Launch::Exe`] is started @@ -30,50 +32,194 @@ pub enum Launch { impl Launch { /// A Steam launch; the app id may not be 0. pub fn steam(app_id: u32) -> Result { - let _ = app_id; - Err(ParseError::BadId) + if app_id == 0 { + return Err(ParseError::BadId); + } + Ok(Launch::SteamRunGameId(app_id)) } /// An Epic launch; `app_name` must match `[A-Za-z0-9_-]{1,64}`. pub fn epic(app_name: &str) -> Result { - let _ = app_name; - Err(ParseError::BadId) + if !text::is_epic_app(app_name) { + return Err(ParseError::BadId); + } + Ok(Launch::Epic { app_name: app_name.to_owned() }) } /// A direct launch. `exe` must end in `.exe` (so never a `.bat`, `.cmd` or `.lnk`, which Windows would hand to /// a shell); each argument is checked (no control characters, caps on count and length). pub fn exe(exe: WinPath, working_dir: WinPath, args: Vec) -> Result { - let _ = (exe, working_dir, args); - Err(ParseError::BadPath("exe")) + if !text::is_exe(&exe) { + return Err(ParseError::BadPath("exe")); + } + check_args(&args)?; + Ok(Launch::Exe { exe, working_dir, args }) } /// A Domi app link; `app` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end). pub fn domi_link(app: &str) -> Result { - let _ = app; - Err(ParseError::BadId) + if !text::is_atrium_id(app) { + return Err(ParseError::BadId); + } + Ok(Launch::DomiLink { app: app.to_owned() }) } /// A web game. The URL must be `https://[/path][?query][#fragment]` with no user info and no port, and /// `host` must equal (ignoring case) one of `allowed_hosts`. The scheme and host are lowercased. pub fn web(url: &str, allowed_hosts: &[&str]) -> Result { - let _ = (url, allowed_hosts); - Err(ParseError::BadValue("url")) + let (normal, host_len) = check_url(url)?; + if !host_allowed(&normal, host_len, allowed_hosts) { + return Err(ParseError::BadValue("url")); + } + Ok(Launch::Url(normal)) } /// The exact URI for the protocol variants, rebuilt from the validated fields; `None` for [`Launch::Exe`] and - /// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only; use - /// [`Launch::uri_checked`] to apply the host allow-list again. + /// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only (and that it is + /// already normalised); use [`Launch::uri_checked`] to apply the host allow-list again. pub fn uri(&self) -> Option { - None + match self { + Launch::SteamRunGameId(id) => (*id != 0).then(|| format!("steam://rungameid/{id}")), + Launch::Epic { app_name } => text::is_epic_app(app_name) + .then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true")), + Launch::DomiLink { app } => text::is_atrium_id(app).then(|| format!("domi-{app}://open")), + Launch::Url(url) => match check_url(url) { + Ok((normal, _)) if &normal == url => Some(normal), + _ => None, + }, + Launch::Exe { .. } => None, + } } /// As [`Launch::uri`], and a [`Launch::Url`] must also have its host in `allowed_hosts`. pub fn uri_checked(&self, allowed_hosts: &[&str]) -> Option { - let _ = allowed_hosts; - None + match self { + Launch::Url(url) => match check_url(url) { + Ok((normal, host_len)) if &normal == url && host_allowed(&normal, host_len, allowed_hosts) => { + Some(normal) + } + _ => None, + }, + other => other.uri(), + } } } +/// Arguments of an exe launch: at most `MAX_ARGS`, each at most `MAX_ARG` bytes, no control characters. +fn check_args(args: &[String]) -> Result<(), ParseError> { + if args.len() > MAX_ARGS { + return Err(ParseError::TooMany("args")); + } + for a in args { + if a.len() > MAX_ARG { + return Err(ParseError::TooLong("arg")); + } + if a.chars().any(char::is_control) { + return Err(ParseError::BadValue("args")); + } + } + Ok(()) +} + +/// Splits a launch-parameter line into arguments: spaces separate, `"` groups (and is removed), nothing else is +/// special. Refuses control characters (tabs included) and an unclosed quote. +pub(crate) fn split_args(line: &str) -> Result, ParseError> { + const BAD: ParseError = ParseError::BadValue("launch_params"); + if line.len() > MAX_ARGS_LINE { + return Err(ParseError::TooLong("launch_params")); + } + if line.chars().any(char::is_control) { + return Err(BAD); + } + let mut args = Vec::new(); + let mut cur = String::new(); + let mut quoted = false; + let mut started = false; + for c in line.chars() { + match c { + '"' => { + quoted = !quoted; + started = true; + } + ' ' if !quoted => { + if started { + args.push(std::mem::take(&mut cur)); + started = false; + } + } + _ => { + cur.push(c); + started = true; + } + } + } + if quoted { + return Err(BAD); + } + if started { + args.push(cur); + } + Ok(args) +} + +/// Bytes allowed after the host: RFC 3986 unreserved, reserved and `%`, minus nothing else. No spaces, quotes, +/// backslashes, angle brackets, braces, `|`, `^` or backticks; nothing outside ASCII (percent-encode it). +fn url_tail_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"-._~:/?#[]@!$&'()*+,;=%".contains(&b) +} + +/// Checks a web-game URL and returns it normalised (lowercase scheme and host) with the host's length. +fn check_url(url: &str) -> Result<(String, usize), ParseError> { + const BAD: ParseError = ParseError::BadValue("url"); + if url.len() > MAX_URL { + return Err(ParseError::TooLong("url")); + } + let scheme = url.get(..8).ok_or(BAD)?; + if !scheme.eq_ignore_ascii_case("https://") { + return Err(BAD); + } + let rest = url.get(8..).ok_or(BAD)?; + let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); + let host = rest.get(..host_end).ok_or(BAD)?.to_ascii_lowercase(); + let tail = rest.get(host_end..).ok_or(BAD)?; + if !host_ok(&host) { + return Err(BAD); + } + let tb = tail.as_bytes(); + for (i, &b) in tb.iter().enumerate() { + if !url_tail_byte(b) { + return Err(BAD); + } + if b == b'%' { + let hex = tb.get(i + 1..i + 3).ok_or(BAD)?; + if !hex.iter().all(u8::is_ascii_hexdigit) { + return Err(BAD); + } + } + } + let mut normal = String::with_capacity(url.len()); + normal.push_str("https://"); + normal.push_str(&host); + normal.push_str(tail); + Ok((normal, host.len())) +} + +/// A DNS name: dot-separated labels of `[a-z0-9-]{1,63}`, no `-` at either end of a label, at most `MAX_HOST`. +/// So no user info (`@`), no port (`:`), no IPv6 literal (`[`). +fn host_ok(host: &str) -> bool { + (1..=MAX_HOST).contains(&host.len()) + && host.split('.').all(|l| { + (1..=63).contains(&l.len()) + && !l.starts_with('-') + && !l.ends_with('-') + && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) +} + +fn host_allowed(normal: &str, host_len: usize, allowed: &[&str]) -> bool { + normal.get(8..8 + host_len).is_some_and(|host| allowed.iter().any(|a| a.eq_ignore_ascii_case(host))) +} + /// The wire shape of [`Launch`]; deserialising goes through it so every field is validated. #[derive(Deserialize)] #[serde(rename_all = "snake_case")] @@ -88,16 +234,15 @@ enum LaunchRepr { impl TryFrom for Launch { type Error = ParseError; + /// Validates like the builders. A URL's host cannot be checked here (no allow-list), so launching a web game + /// read back from storage should go through [`Launch::uri_checked`]. fn try_from(r: LaunchRepr) -> Result { match r { LaunchRepr::SteamRunGameId(id) => Launch::steam(id), LaunchRepr::Epic { app_name } => Launch::epic(&app_name), LaunchRepr::Exe { exe, working_dir, args } => Launch::exe(exe, working_dir, args), LaunchRepr::DomiLink { app } => Launch::domi_link(&app), - LaunchRepr::Url(url) => { - let _ = url; - Err(ParseError::BadValue("url")) - } + LaunchRepr::Url(url) => check_url(&url).map(|(normal, _)| Launch::Url(normal)), } } } diff --git a/crates/arena-core/src/manual.rs b/crates/arena-core/src/manual.rs index 85fd63a..16eb4c6 100644 --- a/crates/arena-core/src/manual.rs +++ b/crates/arena-core/src/manual.rs @@ -5,12 +5,36 @@ //! A game the user added by picking its `.exe`. use crate::error::ParseError; -use crate::model::Game; +use crate::id::{GameId, Source}; +use crate::launch::Launch; +use crate::model::{CoverHint, Game}; +use crate::path::WinPath; +use crate::text; /// The game for an `.exe` the user picked. The id is `manual:<16 hex>`, a stable hash of the path ignoring case, /// so adding the same file twice gives the same id. The title defaults to the file name without `.exe`; the /// install and working folder are the exe's folder; no arguments. pub fn game(exe: &str, title: Option<&str>) -> Result { - let _ = (exe, title); - Err(ParseError::BadPath("exe")) + const BAD: ParseError = ParseError::BadPath("exe"); + let exe = WinPath::parse(exe).map_err(|_| BAD)?; + if !text::is_exe(&exe) { + return Err(BAD); + } + let dir = exe.parent().ok_or(BAD)?; + let title = match title { + Some(t) => text::title(t, "title")?, + None => { + let name = exe.file_name().ok_or(BAD)?; + text::title(name.get(..name.len() - 4).ok_or(BAD)?, "title")? + } + }; + let id = GameId::new(Source::Manual, &format!("{:016x}", text::fnv1a64(exe.key().as_bytes())))?; + Ok(Game { + cover: Some(CoverHint::lettered(&title, &id)), + id, + source: Source::Manual, + title, + install_dir: Some(dir.clone()), + launch: Launch::exe(exe, dir, Vec::new())?, + }) } diff --git a/crates/arena-core/src/model.rs b/crates/arena-core/src/model.rs index 9055cc0..cbd4dc9 100644 --- a/crates/arena-core/src/model.rs +++ b/crates/arena-core/src/model.rs @@ -2,13 +2,18 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. +use crate::error::ParseError; use crate::id::{GameId, Source}; use crate::launch::Launch; +use crate::limits::MAX_GAMES; use crate::path::WinPath; +use crate::text; use serde::{Deserialize, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; /// One game in the library. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(try_from = "GameRepr")] pub struct Game { pub id: GameId, pub source: Source, @@ -19,6 +24,35 @@ pub struct Game { pub cover: Option, } +/// The wire shape of [`Game`]; deserialising goes through it so the title is checked and the id matches the source. +#[derive(Deserialize)] +struct GameRepr { + id: GameId, + source: Source, + title: String, + install_dir: Option, + launch: Launch, + cover: Option, +} + +impl TryFrom for Game { + type Error = ParseError; + + fn try_from(r: GameRepr) -> Result { + if r.id.source() != r.source { + return Err(ParseError::BadId); + } + Ok(Game { + title: text::title(&r.title, "title")?, + id: r.id, + source: r.source, + install_dir: r.install_dir, + launch: r.launch, + cover: r.cover, + }) + } +} + /// Where the tile's picture comes from. No online lookups, ever. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] @@ -69,6 +103,24 @@ impl Library { /// - The result is sorted by title (ignoring case), then by id, so the order does not depend on scan order. /// - At most [`crate::limits::MAX_GAMES`] games are considered; the rest are dropped. pub fn merge(scans: Vec>) -> Library { - let _ = scans; - Library::default() + let mut seen: BTreeSet = BTreeSet::new(); + let mut games: Vec = Vec::new(); + for g in scans.into_iter().flatten().take(MAX_GAMES) { + if seen.insert(g.id.clone()) { + games.push(g); + } + } + let mut best: BTreeMap = BTreeMap::new(); + for g in &games { + if let Some(dir) = &g.install_dir { + let e = best.entry(dir.key()).or_insert(0); + *e = (*e).max(g.source.priority()); + } + } + games.retain(|g| match &g.install_dir { + Some(dir) => best.get(&dir.key()).is_none_or(|&b| g.source.priority() >= b), + None => true, + }); + games.sort_by_cached_key(|g| (g.title.to_lowercase(), g.id.clone())); + Library { games } } diff --git a/crates/arena-core/src/path.rs b/crates/arena-core/src/path.rs index 752e526..ccf27d9 100644 --- a/crates/arena-core/src/path.rs +++ b/crates/arena-core/src/path.rs @@ -3,10 +3,22 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::error::ParseError; +use crate::limits::MAX_PATH; use serde::{Deserialize, Serialize}; use std::fmt; use std::str::FromStr; +const BAD: ParseError = ParseError::BadPath("path"); +const SEPARATORS: [char; 2] = ['\\', '/']; +/// `X:\` +const ROOT_LEN: usize = 3; +/// Device names Windows opens instead of a file, whatever the folder or extension. +const DEVICES: [&str; 32] = [ + "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", + "COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", + "LPT9", "LPT¹", "LPT²", "LPT³", +]; + /// An absolute Windows path with a drive letter, checked and normalised. /// /// Refused: anything not starting with `X:\` (so UNC `\\server\share`, `\\?\` and `\\.\` too), `.` and `..` @@ -23,8 +35,35 @@ pub struct WinPath(String); impl WinPath { /// Checks and normalises `s`. pub fn parse(s: &str) -> Result { - let _ = s; - Err(ParseError::BadPath("path")) + // Cheap bound first: no valid path has more than 4 bytes per UTF-16 unit. + if s.len() > 4 * MAX_PATH { + return Err(BAD); + } + let mut chars = s.chars(); + let drive = chars.next().filter(char::is_ascii_alphabetic).ok_or(BAD)?; + if chars.next() != Some(':') { + return Err(BAD); + } + let rest = chars.as_str(); + if !rest.starts_with(SEPARATORS) { + return Err(BAD); + } + let mut out = String::with_capacity(s.len()); + out.push(drive.to_ascii_uppercase()); + out.push_str(":\\"); + let mut first = true; + for comp in rest.split(SEPARATORS).filter(|c| !c.is_empty()) { + check_component(comp)?; + if !first { + out.push('\\'); + } + first = false; + out.push_str(comp); + } + if out.encode_utf16().count() > MAX_PATH { + return Err(BAD); + } + Ok(WinPath(out)) } pub fn as_str(&self) -> &str { @@ -33,23 +72,34 @@ impl WinPath { /// Appends a relative path (`a\b` or `a/b`); the same component rules apply and it may not climb out. pub fn join(&self, relative: &str) -> Result { - let _ = relative; - Err(ParseError::BadPath("path")) + if relative.is_empty() || relative.starts_with(SEPARATORS) { + return Err(BAD); + } + let mut joined = String::with_capacity(self.0.len() + 1 + relative.len()); + joined.push_str(&self.0); + if !joined.ends_with('\\') { + joined.push('\\'); + } + joined.push_str(relative); + WinPath::parse(&joined) } /// The containing folder, or `None` for a drive root. pub fn parent(&self) -> Option { - None + self.file_name()?; + let cut = self.0.rfind('\\')?; + let head = if cut < ROOT_LEN { self.0.get(..ROOT_LEN)? } else { self.0.get(..cut)? }; + Some(WinPath(head.to_owned())) } /// The last component, or `None` for a drive root. pub fn file_name(&self) -> Option<&str> { - None + self.components().last() } /// The components after the drive root. pub fn components(&self) -> impl Iterator { - std::iter::empty() + self.0.get(ROOT_LEN..).unwrap_or_default().split('\\').filter(|c| !c.is_empty()) } /// The case-folded form Windows treats as the same place, for comparing and deduping. @@ -64,11 +114,30 @@ impl WinPath { /// True when `self` is `base` or lies inside it (component-wise, ignoring case). pub fn starts_with(&self, base: &WinPath) -> bool { - let _ = base; - false + let same_drive = self.0.get(..1).zip(base.0.get(..1)).is_some_and(|(a, b)| a.eq_ignore_ascii_case(b)); + if !same_drive { + return false; + } + let mut mine = self.components(); + base.components().all(|b| mine.next().is_some_and(|m| m.to_lowercase() == b.to_lowercase())) } } +/// One path component, between separators. +fn check_component(c: &str) -> Result<(), ParseError> { + if c == "." || c == ".." || c.ends_with('.') || c.ends_with(' ') { + return Err(BAD); + } + if c.chars().any(|ch| ch.is_control() || matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*')) { + return Err(BAD); + } + let stem = c.split('.').next().unwrap_or(c).trim_end_matches(' '); + if DEVICES.iter().any(|d| d.eq_ignore_ascii_case(stem)) { + return Err(BAD); + } + Ok(()) +} + impl fmt::Display for WinPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) diff --git a/crates/arena-core/src/steam.rs b/crates/arena-core/src/steam.rs index 83d4470..1bb7c51 100644 --- a/crates/arena-core/src/steam.rs +++ b/crates/arena-core/src/steam.rs @@ -6,33 +6,107 @@ //! `/steamapps/appmanifest_.acf`. Launch is `steam://rungameid/`. use crate::error::ParseError; -use crate::model::Game; +use crate::id::{GameId, Source}; +use crate::launch::Launch; +use crate::limits::MAX_LIBRARIES; +use crate::model::{CoverHint, Game}; use crate::path::WinPath; +use crate::text; +use crate::vdf::{self, Obj, Value}; + +/// Steam's own redistributables and runtimes: installed like games, never played. +const TOOLS: [u32; 7] = [ + 228_980, // Steamworks Common Redistributables + 1_070_560, // Steam Linux Runtime 1.0 (scout) + 1_391_110, // Steam Linux Runtime 2.0 (soldier) + 1_628_350, // Steam Linux Runtime 3.0 (sniper) + 1_493_710, // Proton Experimental + 1_826_330, // Proton EasyAntiCheat Runtime + 1_161_040, // Proton BattlEye Runtime +]; /// The library folders listed in `libraryfolders.vdf` (both the current layout, `"0" { "path" "..." }`, and the /// old one, `"1" "D:\\SteamLibrary"`). At most [`crate::limits::MAX_LIBRARIES`]; a path listed twice is refused. +/// Keys under the root that are not plain numbers (`contentstatsid`, ...) are skipped. pub fn library_folders(vdf: &[u8]) -> Result, ParseError> { - let _ = vdf; - Err(ParseError::Syntax { at: 0 }) + let doc = vdf::parse(vdf)?; + let root = obj(&doc, "libraryfolders")?; + let mut out: Vec = Vec::new(); + for (key, value) in root.iter() { + if !key.bytes().all(|b| b.is_ascii_digit()) { + continue; + } + let raw = match value { + Value::Str(s) => s.as_str(), + Value::Obj(o) => string(o, "path")?, + }; + let path = WinPath::parse(raw).map_err(|_| ParseError::BadPath("path"))?; + if out.iter().any(|p| p.eq_ignore_case(&path)) { + return Err(ParseError::Duplicate("path")); + } + if out.len() >= MAX_LIBRARIES { + return Err(ParseError::TooMany("libraries")); + } + out.push(path); + } + Ok(out) } /// The game described by `appmanifest_.acf` inside `library` (the folder holding `steamapps`). The install /// folder is `\steamapps\common\`, where `installdir` must be one plain folder name. /// Steam's own redistributables and runtimes ([`is_tool`]) give [`ParseError::NotAGame`]. pub fn app_manifest(acf: &[u8], library: &WinPath) -> Result { - let _ = (acf, library); - Err(ParseError::Syntax { at: 0 }) + let doc = vdf::parse(acf)?; + let state = obj(&doc, "AppState")?; + let app_id = text::canonical_u32(string(state, "appid")?).ok_or(ParseError::BadId)?; + let title = text::title(string(state, "name")?, "name")?; + let installdir = string(state, "installdir")?; + if is_tool(app_id) { + return Err(ParseError::NotAGame("Steam redistributable or runtime")); + } + if installdir.is_empty() || installdir.contains(['\\', '/']) { + return Err(ParseError::BadPath("installdir")); + } + let install_dir = library + .join("steamapps") + .and_then(|p| p.join("common")) + .and_then(|p| p.join(installdir)) + .map_err(|_| ParseError::BadPath("installdir"))?; + Ok(Game { + id: GameId::new(Source::Steam, &app_id.to_string())?, + source: Source::Steam, + title, + install_dir: Some(install_dir), + launch: Launch::steam(app_id)?, + cover: Some(CoverHint::SteamLibraryCache { app_id }), + }) } /// The app id in a file name `appmanifest_.acf` (exact, lowercase, canonical id), for filtering a folder /// listing; `None` for any other name. pub fn app_id_from_manifest_name(name: &str) -> Option { - let _ = name; - None + text::canonical_u32(name.strip_prefix("appmanifest_")?.strip_suffix(".acf")?) } /// Steam apps that are not games: the common redistributables and the Linux runtimes. pub fn is_tool(app_id: u32) -> bool { - let _ = app_id; - false + TOOLS.contains(&app_id) +} + +/// The object under `key`. +fn obj<'a>(o: &'a Obj, key: &'static str) -> Result<&'a Obj, ParseError> { + match o.get(key) { + Some(Value::Obj(inner)) => Ok(inner), + Some(Value::Str(_)) => Err(ParseError::WrongType(key)), + None => Err(ParseError::Missing(key)), + } +} + +/// The string under `key`. +fn string<'a>(o: &'a Obj, key: &'static str) -> Result<&'a str, ParseError> { + match o.get(key) { + Some(Value::Str(s)) => Ok(s), + Some(Value::Obj(_)) => Err(ParseError::WrongType(key)), + None => Err(ParseError::Missing(key)), + } } diff --git a/crates/arena-core/src/text.rs b/crates/arena-core/src/text.rs index 245d9db..4a69037 100644 --- a/crates/arena-core/src/text.rs +++ b/crates/arena-core/src/text.rs @@ -2,16 +2,60 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -//! Small shared helpers: title checks, a stable hash, the lettered cover. +//! Small shared checks: titles, ids, numbers, a stable hash, the lettered cover. use crate::error::ParseError; use crate::id::GameId; +use crate::limits::{MAX_DOMI_ID, MAX_EPIC_APP, MAX_TITLE}; use crate::model::CoverHint; +use crate::path::WinPath; -/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control characters. +/// Bidirectional-override characters, which could make a title display as something else. +fn is_bidi_control(c: char) -> bool { + matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{200e}' | '\u{200f}' | '\u{061c}') +} + +/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control or bidi-override characters. pub(crate) fn title(s: &str, field: &'static str) -> Result { - let _ = s; - Err(ParseError::Missing(field)) + let t = s.trim(); + if t.is_empty() { + return Err(ParseError::Missing(field)); + } + if t.chars().nth(MAX_TITLE).is_some() { + return Err(ParseError::TooLong(field)); + } + if t.chars().any(|c| c.is_control() || is_bidi_control(c)) { + return Err(ParseError::BadValue(field)); + } + Ok(t.to_owned()) +} + +/// A canonical decimal `u32` other than 0: digits only, no sign, no leading zero, no whitespace. +pub(crate) fn canonical_u32(s: &str) -> Option { + let b = s.as_bytes(); + if b.is_empty() || b.len() > 10 || !b.iter().all(u8::is_ascii_digit) || b.first() == Some(&b'0') { + return None; + } + s.parse::().ok() +} + +/// `[A-Za-z0-9_-]{1,64}`. +pub(crate) fn is_epic_app(s: &str) -> bool { + (1..=MAX_EPIC_APP).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +/// Atrium id rules: `[a-z0-9-]{1,32}`, not starting or ending with `-`. +pub(crate) fn is_atrium_id(s: &str) -> bool { + (1..=MAX_DOMI_ID).contains(&s.len()) + && !s.starts_with('-') + && !s.ends_with('-') + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// True when the last component ends in `.exe` (ignoring case) and has a name before it. +pub(crate) fn is_exe(p: &WinPath) -> bool { + p.file_name() + .is_some_and(|n| n.len() > 4 && n.get(n.len() - 4..).is_some_and(|ext| ext.eq_ignore_ascii_case(".exe"))) } /// FNV-1a, 64 bit: stable across builds and platforms (unlike `std`'s hasher). @@ -25,6 +69,17 @@ pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 { } pub(crate) fn lettered(title: &str, id: &GameId) -> CoverHint { - let _ = (title, id); - CoverHint::Lettered { letter: '#', hue: 0 } + let letter = title + .chars() + .find(|c| c.is_alphanumeric()) + .map(|c| { + let mut up = c.to_uppercase(); + match (up.next(), up.next()) { + (Some(u), None) => u, + _ => c, + } + }) + .unwrap_or('#'); + let hue = u16::try_from(fnv1a64(id.as_str().as_bytes()) % 360).unwrap_or(0); + CoverHint::Lettered { letter, hue } } diff --git a/crates/arena-core/src/vdf.rs b/crates/arena-core/src/vdf.rs index ed00a76..44bd083 100644 --- a/crates/arena-core/src/vdf.rs +++ b/crates/arena-core/src/vdf.rs @@ -6,12 +6,14 @@ //! `libraryfolders.vdf` and `appmanifest_.acf`. //! //! Accepted: quoted strings with the escapes `\\`, `\"`, `\n`, `\t` and `\r`; `{` and `}`; whitespace (space, tab, -//! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: unquoted -//! tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control characters or line breaks inside -//! a string, NUL anywhere, empty keys, a key repeated on the same level (ignoring ASCII case), and anything over the -//! caps in [`crate::limits`]. +//! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: input that is not +//! UTF-8 as a whole, unquoted tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control +//! characters (other than tab) or line breaks inside a string, NUL anywhere, empty keys, a key repeated in the same +//! object (ignoring ASCII case), and anything over the caps in [`crate::limits`]. use crate::error::ParseError; +use crate::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE}; +use std::collections::BTreeMap; /// One token and the byte offset where it starts. #[derive(Debug, Clone, PartialEq, Eq)] @@ -37,26 +39,73 @@ pub enum Value { Obj(Obj), } -/// An ordered list of key/value pairs with unique keys (ignoring ASCII case). -#[derive(Debug, Clone, Default, PartialEq, Eq)] +/// An ordered list of key/value pairs with unique keys (ignoring ASCII case). It carries its own caps: at most +/// [`MAX_DEPTH`] levels of objects below it and [`MAX_ENTRIES`] pairs in total, so every `Obj` can be written and +/// read back. +#[derive(Debug, Clone, Default)] pub struct Obj { entries: Vec<(String, Value)>, + /// ASCII-lowercased key -> position in `entries`. + index: BTreeMap, + /// Levels of objects inside this one (0 when it holds only strings). + depth: usize, + /// Pairs at every level, this one included. + total: usize, } +impl PartialEq for Obj { + fn eq(&self, other: &Obj) -> bool { + self.entries == other.entries + } +} + +impl Eq for Obj {} + impl Obj { pub fn new() -> Obj { Obj::default() } - /// Appends a pair. Refuses an empty key, a key or value over its cap, and a key already present. + /// Appends a pair. Refuses an empty key, a key or value over its cap, a key already present, an object value + /// that would nest deeper than [`MAX_DEPTH`], and more than [`MAX_ENTRIES`] pairs in total. pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> { - let _ = (key, value); - Err(ParseError::Missing("key")) + if key.is_empty() { + return Err(ParseError::Missing("key")); + } + if key.len() > MAX_KEY { + return Err(ParseError::TooLong("key")); + } + writable(&key, "key")?; + let (depth, added) = match &value { + Value::Str(s) if s.len() > MAX_VALUE => return Err(ParseError::TooLong("value")), + Value::Str(s) => { + writable(s, "value")?; + (0, 1) + } + Value::Obj(o) => (o.depth + 1, o.total + 1), + }; + if depth > MAX_DEPTH { + return Err(ParseError::TooDeep); + } + let total = self.total + added; + if total > MAX_ENTRIES { + return Err(ParseError::TooMany("entries")); + } + let folded = key.to_ascii_lowercase(); + if self.index.contains_key(&folded) { + return Err(ParseError::Duplicate("key")); + } + self.index.insert(folded, self.entries.len()); + self.entries.push((key, value)); + self.depth = self.depth.max(depth); + self.total = total; + Ok(()) } /// The value under `key`, ignoring ASCII case. pub fn get(&self, key: &str) -> Option<&Value> { - self.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v) + let i = *self.index.get(&key.to_ascii_lowercase())?; + self.entries.get(i).map(|(_, v)| v) } /// The pairs in file order. @@ -73,20 +122,220 @@ impl Obj { } } +/// A string [`write`] can carry and [`parse`] reads back: no control characters other than tab, CR and LF, and at +/// most [`MAX_ESCAPES`] characters that need an escape. +fn writable(s: &str, what: &'static str) -> Result<(), ParseError> { + let mut escapes = 0usize; + for c in s.chars() { + match c { + '\\' | '"' | '\n' | '\r' => escapes += 1, + '\t' => {} + c if c.is_ascii_control() => return Err(ParseError::BadValue(what)), + _ => {} + } + } + if escapes > MAX_ESCAPES { + return Err(ParseError::TooMany("escapes")); + } + Ok(()) +} + +/// Reads tokens one at a time. +struct Lexer<'a> { + input: &'a [u8], + pos: usize, +} + +impl<'a> Lexer<'a> { + fn new(input: &'a [u8]) -> Result, ParseError> { + if input.len() > MAX_FILE { + return Err(ParseError::TooLarge); + } + if std::str::from_utf8(input).is_err() { + return Err(ParseError::NotUtf8); + } + let pos = if input.starts_with(b"\xEF\xBB\xBF") { 3 } else { 0 }; + Ok(Lexer { input, pos }) + } + + fn peek(&self, ahead: usize) -> Option { + self.input.get(self.pos + ahead).copied() + } + + fn next_token(&mut self) -> Result, ParseError> { + loop { + let at = self.pos; + let Some(b) = self.peek(0) else { return Ok(None) }; + match b { + b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1, + b'/' if self.peek(1) == Some(b'/') => self.skip_comment()?, + b'{' => { + self.pos += 1; + return Ok(Some(Token { kind: TokenKind::Open, at })); + } + b'}' => { + self.pos += 1; + return Ok(Some(Token { kind: TokenKind::Close, at })); + } + b'"' => { + let s = self.string()?; + return Ok(Some(Token { kind: TokenKind::Str(s), at })); + } + _ => return Err(ParseError::Syntax { at }), + } + } + } + + /// Skips `//...` up to (not including) the line break. NUL is refused here too. + fn skip_comment(&mut self) -> Result<(), ParseError> { + while let Some(b) = self.peek(0) { + match b { + b'\n' => break, + 0 => return Err(ParseError::Syntax { at: self.pos }), + _ => self.pos += 1, + } + } + Ok(()) + } + + /// A quoted string starting at `self.pos`; an unterminated one is reported at its opening quote. + fn string(&mut self) -> Result { + let start = self.pos; + self.pos += 1; + let mut buf: Vec = Vec::new(); + let mut escapes = 0usize; + loop { + let Some(b) = self.peek(0) else { return Err(ParseError::Syntax { at: start }) }; + match b { + b'"' => { + self.pos += 1; + break; + } + b'\\' => { + let decoded = match self.peek(1) { + None => return Err(ParseError::Syntax { at: start }), + Some(b'\\') => b'\\', + Some(b'"') => b'"', + Some(b'n') => b'\n', + Some(b't') => b'\t', + Some(b'r') => b'\r', + Some(_) => return Err(ParseError::Syntax { at: self.pos }), + }; + escapes += 1; + if escapes > MAX_ESCAPES { + return Err(ParseError::TooMany("escapes")); + } + buf.push(decoded); + self.pos += 2; + } + b'\t' => { + buf.push(b); + self.pos += 1; + } + 0x00..=0x1f | 0x7f => return Err(ParseError::Syntax { at: self.pos }), + _ => { + buf.push(b); + self.pos += 1; + } + } + if buf.len() > MAX_VALUE { + return Err(ParseError::TooLong("value")); + } + } + String::from_utf8(buf).map_err(|_| ParseError::NotUtf8) + } +} + /// Splits `input` into tokens. Checks size, UTF-8, escapes and string lengths; not nesting. pub fn tokenize(input: &[u8]) -> Result, ParseError> { - let _ = input; - Err(ParseError::Syntax { at: 0 }) + let mut lx = Lexer::new(input)?; + let mut out = Vec::new(); + while let Some(t) = lx.next_token()? { + out.push(t); + } + Ok(out) } /// Parses a whole document: a sequence of top-level pairs. pub fn parse(input: &[u8]) -> Result { - let _ = input; - Err(ParseError::Syntax { at: 0 }) + let mut lx = Lexer::new(input)?; + parse_obj(&mut lx, 0) +} + +/// Reads pairs until `}` (inside an object, `depth > 0`) or the end of input (at the top, `depth == 0`). +/// Recursion is bounded by `MAX_DEPTH`. +fn parse_obj(lx: &mut Lexer<'_>, depth: usize) -> Result { + let end = lx.input.len(); + let mut obj = Obj::new(); + loop { + let key = match lx.next_token()? { + None if depth == 0 => return Ok(obj), + None => return Err(ParseError::Syntax { at: end }), + Some(Token { kind: TokenKind::Close, .. }) if depth > 0 => return Ok(obj), + Some(Token { kind: TokenKind::Close | TokenKind::Open, at }) => return Err(ParseError::Syntax { at }), + Some(Token { kind: TokenKind::Str(k), .. }) => k, + }; + if key.len() > MAX_KEY { + return Err(ParseError::TooLong("key")); + } + let value = match lx.next_token()? { + None => return Err(ParseError::Syntax { at: end }), + Some(Token { kind: TokenKind::Str(s), .. }) => Value::Str(s), + Some(Token { kind: TokenKind::Open, .. }) => { + if depth >= MAX_DEPTH { + return Err(ParseError::TooDeep); + } + Value::Obj(parse_obj(lx, depth + 1)?) + } + Some(Token { kind: TokenKind::Close, at }) => return Err(ParseError::Syntax { at }), + }; + obj.insert(key, value)?; + } } /// Writes a document in Valve's layout (tabs, one pair per line). [`parse`] of the result gives `doc` back. pub fn write(doc: &Obj) -> String { - let _ = doc; - String::new() + let mut out = String::new(); + write_obj(doc, 0, &mut out); + out +} + +fn write_obj(o: &Obj, indent: usize, out: &mut String) { + for (k, v) in &o.entries { + push_tabs(out, indent); + push_quoted(out, k); + match v { + Value::Str(s) => { + out.push_str("\t\t"); + push_quoted(out, s); + out.push('\n'); + } + Value::Obj(inner) => { + out.push('\n'); + push_tabs(out, indent); + out.push_str("{\n"); + write_obj(inner, indent + 1, out); + push_tabs(out, indent); + out.push_str("}\n"); + } + } + } +} + +fn push_tabs(out: &mut String, n: usize) { + out.extend(std::iter::repeat_n('\t', n)); +} + +fn push_quoted(out: &mut String, s: &str) { + out.push('"'); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + _ => out.push(c), + } + } + out.push('"'); } diff --git a/crates/arena-core/tests/fixtures/epic/absurd.item b/crates/arena-core/tests/fixtures/epic/absurd.item index b258722..88f890d 100644 --- a/crates/arena-core/tests/fixtures/epic/absurd.item +++ b/crates/arena-core/tests/fixtures/epic/absurd.item @@ -1,6 +1,6 @@ { "FormatVersion": 0, "DisplayName": "Absurd Number", - "InstallLocation": "C:\Games\Absurd", + "InstallLocation": "C:\\Games\\Absurd", "AppName": 1e999999 } diff --git a/crates/arena-core/tests/fixtures/epic/addon.item b/crates/arena-core/tests/fixtures/epic/addon.item index 32c6eb8..a4da2e1 100644 --- a/crates/arena-core/tests/fixtures/epic/addon.item +++ b/crates/arena-core/tests/fixtures/epic/addon.item @@ -1,7 +1,7 @@ { "FormatVersion": 0, "DisplayName": "Example Racer - Bonus Cars", - "InstallLocation": "C:\Program Files\Epic Games\ExampleRacer", + "InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer", "AppName": "ExampleRacerBonusCars", "MainGameAppName": "ExampleRacer_Main-01" } diff --git a/crates/arena-core/tests/fixtures/epic/badappname.item b/crates/arena-core/tests/fixtures/epic/badappname.item index 2c18832..cd338a1 100644 --- a/crates/arena-core/tests/fixtures/epic/badappname.item +++ b/crates/arena-core/tests/fixtures/epic/badappname.item @@ -1,5 +1,5 @@ { "DisplayName": "Injected", - "InstallLocation": "C:\Games\Injected", + "InstallLocation": "C:\\Games\\Injected", "AppName": "x?action=uninstall&a=../../" } diff --git a/crates/arena-core/tests/fixtures/epic/dupkey.item b/crates/arena-core/tests/fixtures/epic/dupkey.item index c92b489..58e34e2 100644 --- a/crates/arena-core/tests/fixtures/epic/dupkey.item +++ b/crates/arena-core/tests/fixtures/epic/dupkey.item @@ -1,6 +1,6 @@ { "DisplayName": "Twice", - "InstallLocation": "C:\Games\Twice", + "InstallLocation": "C:\\Games\\Twice", "AppName": "TwiceA", "AppName": "TwiceB" } diff --git a/crates/arena-core/tests/fixtures/epic/missing.item b/crates/arena-core/tests/fixtures/epic/missing.item index 64a76b6..320d62a 100644 --- a/crates/arena-core/tests/fixtures/epic/missing.item +++ b/crates/arena-core/tests/fixtures/epic/missing.item @@ -1,4 +1,4 @@ { "DisplayName": "No App Name", - "InstallLocation": "C:\Games\NoAppName" + "InstallLocation": "C:\\Games\\NoAppName" } diff --git a/crates/arena-core/tests/fixtures/epic/trailing.item b/crates/arena-core/tests/fixtures/epic/trailing.item index c1dd1d5..2e85922 100644 --- a/crates/arena-core/tests/fixtures/epic/trailing.item +++ b/crates/arena-core/tests/fixtures/epic/trailing.item @@ -1,5 +1,5 @@ { "DisplayName": "Trailing", - "InstallLocation": "C:\Games\Trailing", + "InstallLocation": "C:\\Games\\Trailing", "AppName": "Trailing" } {"AppName": "Second"} diff --git a/crates/arena-core/tests/fixtures/epic/traversal.item b/crates/arena-core/tests/fixtures/epic/traversal.item index 04c2771..d0a875e 100644 --- a/crates/arena-core/tests/fixtures/epic/traversal.item +++ b/crates/arena-core/tests/fixtures/epic/traversal.item @@ -1,5 +1,5 @@ { "DisplayName": "Escape Artist", - "InstallLocation": "C:\Games\..\Windows\System32", + "InstallLocation": "C:\\Games\\..\\Windows\\System32", "AppName": "EscapeArtist" } diff --git a/crates/arena-core/tests/fixtures/epic/unc.item b/crates/arena-core/tests/fixtures/epic/unc.item index 131faa6..3e75ff4 100644 --- a/crates/arena-core/tests/fixtures/epic/unc.item +++ b/crates/arena-core/tests/fixtures/epic/unc.item @@ -1,5 +1,5 @@ { "DisplayName": "Remote", - "InstallLocation": "\\evil-server\share\Game", + "InstallLocation": "\\\\evil-server\\share\\Game", "AppName": "Remote" } diff --git a/crates/arena-core/tests/fixtures/epic/valid.item b/crates/arena-core/tests/fixtures/epic/valid.item index d794eac..07fba43 100644 --- a/crates/arena-core/tests/fixtures/epic/valid.item +++ b/crates/arena-core/tests/fixtures/epic/valid.item @@ -3,7 +3,7 @@ "bIsIncompleteInstall": false, "LaunchCommand": "", "LaunchExecutable": "ExampleRacer/Binaries/Win64/ExampleRacer.exe", - "ManifestLocation": "C:\ProgramData\Epic\EpicGamesLauncher\Data\Manifests", + "ManifestLocation": "C:\\ProgramData\\Epic\\EpicGamesLauncher\\Data\\Manifests", "bIsApplication": true, "bIsExecutable": true, "bIsManaged": false, @@ -12,7 +12,7 @@ "bCanRunOffline": true, "DisplayName": "Example Racer", "InstallationGuid": "00000000000000000000000000000001", - "InstallLocation": "C:\Program Files\Epic Games\ExampleRacer", + "InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer", "CatalogNamespace": "example", "CatalogItemId": "00000000000000000000000000000002", "AppName": "ExampleRacer_Main-01", diff --git a/crates/arena-core/tests/fixtures/epic/wrongtype.item b/crates/arena-core/tests/fixtures/epic/wrongtype.item index aa7aa21..5c18e50 100644 --- a/crates/arena-core/tests/fixtures/epic/wrongtype.item +++ b/crates/arena-core/tests/fixtures/epic/wrongtype.item @@ -1,5 +1,5 @@ { "DisplayName": "Wrong Type", - "InstallLocation": "C:\Games\WrongType", + "InstallLocation": "C:\\Games\\WrongType", "AppName": 12345 } diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf index 6b13a3a..70a56e4 100644 --- a/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_1234560.acf @@ -2,7 +2,7 @@ { "appid" "1234560" "universe" "1" - "LauncherPath" "C:\Program Files (x86)\Steam\steam.exe" + "LauncherPath" "C:\\Program Files (x86)\\Steam\\steam.exe" "name" "Example Quest: The \"Quoted\" Edition" "StateFlags" "4" "installdir" "Example Quest" diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf index 2d3c18c..264fa6f 100644 --- a/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_absolute.acf @@ -2,5 +2,5 @@ { "appid" "1234571" "name" "Somewhere Else" - "installdir" "C:\Windows" + "installdir" "C:\\Windows" } diff --git a/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf b/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf index 8fcdde2..d8aacbb 100644 --- a/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf +++ b/crates/arena-core/tests/fixtures/steam/appmanifest_traversal.acf @@ -2,5 +2,5 @@ { "appid" "1234570" "name" "Escape Artist" - "installdir" "..\..\..\Windows\System32" + "installdir" "..\\..\\..\\Windows\\System32" } diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf index e7f9aa0..6b25b69 100644 --- a/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders.vdf @@ -2,7 +2,7 @@ { "0" { - "path" "C:\Program Files (x86)\Steam" + "path" "C:\\Program Files (x86)\\Steam" "label" "" "contentid" "1111111111111111111" "totalsize" "0" @@ -16,7 +16,7 @@ } "1" { - "path" "D:\SteamLibrary" + "path" "D:\\SteamLibrary" "label" "Games" "contentid" "2222222222222222222" "totalsize" "1000000000000" diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf index 7d2d726..635b117 100644 --- a/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_dup.vdf @@ -2,10 +2,10 @@ { "0" { - "path" "D:\SteamLibrary" + "path" "D:\\SteamLibrary" } "1" { - "path" "d:\steamlibrary\\" + "path" "d:\\steamlibrary\\" } } diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf index e00b0d2..295a091 100644 --- a/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_old.vdf @@ -3,6 +3,6 @@ { "TimeNextStatsReport" "0" "ContentStatsID" "-1" - "1" "D:\SteamLibrary" + "1" "D:\\SteamLibrary" "2" "E:/Games/Steam" } diff --git a/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf b/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf index 7683d08..eb15a2a 100644 --- a/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf +++ b/crates/arena-core/tests/fixtures/steam/libraryfolders_unc.vdf @@ -2,6 +2,6 @@ { "0" { - "path" "\\evil-server\share\Steam" + "path" "\\\\evil-server\\share\\Steam" } } diff --git a/crates/arena-core/tests/steam.rs b/crates/arena-core/tests/steam.rs index 4872ef2..6676f87 100644 --- a/crates/arena-core/tests/steam.rs +++ b/crates/arena-core/tests/steam.rs @@ -156,7 +156,7 @@ fn app_manifest_refuses_blank_or_control_title() { #[test] fn app_manifest_refuses_device_name_installdir() { - for bad in ["CON", "nul", "COM1", "lpt9.txt", "a/b", "a\\b", ".", "..", "x:", "dots.", ""] { + for bad in ["CON", "nul", "COM1", "lpt9.txt", "a/b", r"a\\b", ".", "..", "x:", "dots.", ""] { let acf = format!("\"AppState\" {{ \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"{bad}\" }}"); assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadPath("installdir")), "{bad:?}"); } diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 0000000..bcde79b --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,203 @@ +# Formats: what `arena-core` accepts and refuses + +Every launcher file and value is hostile input. Each parser below either returns a fully validated `Game` (or list +of paths) or a typed `ParseError`; it never truncates, guesses or panics. Nothing is read from disk here: the app +reads capped bytes and passes them in. + +## Caps (`arena_core::limits`) + +| Constant | Value | Applies to | Error when exceeded | +| :-- | :-- | :-- | :-- | +| `MAX_FILE` | 1 MiB (1 048 576 bytes) | whole VDF, ACF or `.item` input | `TooLarge` | +| `MAX_DEPTH` | 32 | nesting of VDF objects; JSON objects and arrays together | `TooDeep` | +| `MAX_KEY` | 256 bytes | a VDF key, after unescaping | `TooLong("key")` | +| `MAX_VALUE` | 4096 bytes | any VDF string, after unescaping | `TooLong("value")` | +| `MAX_ESCAPES` | 256 | escape sequences in one VDF string | `TooMany("escapes")` | +| `MAX_ENTRIES` | 65 536 | key/value pairs in one VDF document, all levels | `TooMany("entries")` | +| `MAX_LIBRARIES` | 64 | Steam library folders | `TooMany("libraries")` | +| `MAX_PATH` | 260 UTF-16 units | every `WinPath` | `BadPath(field)` | +| `MAX_TITLE` | 256 characters | every title, after trimming | `TooLong(field)` | +| `MAX_GAME_ID` | 96 bytes | `GameId` | `BadId` | +| `MAX_EPIC_APP` | 64 bytes | Epic `AppName` | `BadId` | +| `MAX_DOMI_ID` | 32 bytes | Domi / Atrium id | `BadId` | +| `MAX_GOG_ID` | 20 digits | GOG `gameID` | `BadId` | +| `MAX_ARGS_LINE` | 4096 bytes | GOG `launchParam` | `TooLong("launch_params")` | +| `MAX_ARGS` | 32 | arguments of an exe launch | `TooMany("args")` | +| `MAX_ARG` | 1024 bytes | one argument | `TooLong("arg")` | +| `MAX_URL` | 2048 bytes | a web-game URL | `TooLong("url")` | +| `MAX_HOST` | 253 bytes | the URL's host | `BadValue("url")` | +| `MAX_GAMES` | 100 000 | games one `merge` call considers | the rest are dropped | + +## Errors + +`ParseError` is `#[non_exhaustive]` and implements `Display` and `std::error::Error`. The `&'static str` names +the field; an error never carries input text, so it is always safe to log. + +| Variant | Meaning | +| :-- | :-- | +| `TooLarge` | input over `MAX_FILE` | +| `TooDeep` | nesting over `MAX_DEPTH` | +| `NotUtf8` | the input (VDF: as a whole; JSON: as a whole) is not valid UTF-8 | +| `Syntax { at }` | malformed at byte offset `at` of the input (BOM included) | +| `Missing(field)` | a required field is absent (or a title is blank) | +| `WrongType(field)` | an object where a string belongs, a number for a string, a non-object `.item`, ... | +| `BadPath(field)` | not a valid `WinPath`, or a path that leaves where it must stay | +| `BadId` | Steam app id, Epic app name, GOG id, Domi id or `GameId` malformed or out of range | +| `Duplicate(field)` | a key or entry appears twice (`"key"` for VDF keys, the field name for JSON) | +| `TooLong(field)` / `TooMany(field)` | over a cap above | +| `BadValue(field)` | control or bidi-override characters in a title, a bad URL, a bad argument | +| `NotAGame(why)` | a valid file for something that is not a game: callers skip it quietly | + +## Shared rules + +**Titles** (Steam `name`, Epic `DisplayName`, GOG `gameName`, manual title, Domi name): trimmed; blank is +`Missing`; over 256 characters is `TooLong`; any control character (C0, DEL, C1) or bidi override (U+202A–202E, +U+2066–2069, U+200E, U+200F, U+061C) is `BadValue`. + +**`WinPath`**: must start `X:\` or `X:/` with an ASCII drive letter. Refused: UNC (`\\server\share`), `\\?\`, +`\\.\`, `\??\`, drive-relative `C:x`, rooted `\x`, components `.` and `..`, components ending in `.` or space, +control characters, `< > : " | ? *` (a `:` only after the drive letter, so no alternate data streams), device names +as the stem of any component (`CON PRN AUX NUL CONIN$ CONOUT$ COM0-9 COM¹²³ LPT0-9 LPT¹²³`, any case, any +extension, trailing spaces ignored), more than 260 UTF-16 units. Normalised: `/` to `\`, repeated separators +collapsed, drive letter uppercase, trailing separator dropped (`C:\` stays). `join` takes a relative path under the +same rules (so it cannot climb out); `starts_with` compares component-wise ignoring case. + +**`GameId`**: `:` with the source one of `steam epic gog manual domi`, at most 96 bytes. Native +part: Steam a canonical non-zero `u32` (no sign, no leading zero); Epic `[a-z0-9_-]{1,64}` (the app name lowercased, +so two Epic apps differing only in case share an id and dedupe); GOG 1–20 digits; Manual exactly 16 lowercase hex +digits (FNV-1a 64 of the exe path, case-folded); Domi the Atrium id rule. + +**Atrium id** (Domi ids and `domi-://` links): `[a-z0-9-]{1,32}`, not starting or ending with `-`. + +## VDF / KeyValues text (`arena_core::vdf`) + +Accepted: +- one optional UTF-8 BOM at the very start; +- whitespace: space, tab, CR, LF; +- `//` comments to the end of the line; +- `{`, `}` and quoted strings `"..."`; +- escapes `\\`, `\"`, `\n`, `\t`, `\r`; +- a raw tab inside a string. + +Refused (`Syntax { at }` unless noted): +- input that is not UTF-8 anywhere, comments included (`NotUtf8`); +- NUL anywhere, raw control characters other than tab inside a string, raw CR or LF inside a string; +- any other escape (`\x`, `\0`, `\'`, ...), a backslash at end of input; +- unterminated strings (reported at the opening quote) and unclosed objects (reported at end of input); +- unquoted tokens, `#include`, `#base`, `[$CONDITION]` tags, a single `/`; +- a `{` or `}` where a key belongs, a `}` where a value belongs, a key with no value; +- an empty key (`Missing("key")`), a key repeated in the same object, ignoring ASCII case (`Duplicate("key")`); +- anything over `MAX_FILE`, `MAX_DEPTH`, `MAX_KEY`, `MAX_VALUE`, `MAX_ESCAPES`, `MAX_ENTRIES`. + +`vdf::write` emits Valve's layout (tabs, `"key"\t\t"value"`, `{` / `}` on their own lines) and escapes `\`, `"`, +LF and CR. `Obj::insert` applies the same caps and character rules as the parser, so any `Obj` built in code writes +and parses back to itself (property-tested), provided the written text stays under `MAX_FILE`. + +## Steam `libraryfolders.vdf` (`steam::library_folders`) + +Accepted: a root key `libraryfolders` (any case) holding an object. Under it, every key made only of digits is a +library: either the current layout `"0" { "path" "C:\\..." ... }` or the old one `"1" "D:\\SteamLibrary"`. Other +keys (`contentstatsid`, `TimeNextStatsReport`, ...) and every other field of a library (`label`, `apps`, ...) are +ignored, though they must still parse within the caps. + +Refused: no root (`Missing("libraryfolders")`), a string root (`WrongType("libraryfolders")`), a library object +without `path` (`Missing("path")`) or with an object `path` (`WrongType("path")`), a path that is not a `WinPath` +(`BadPath("path")`), the same folder twice ignoring case and trailing separators (`Duplicate("path")`), more than +64 libraries (`TooMany("libraries")`). + +## Steam `appmanifest_.acf` (`steam::app_manifest`) + +Reads `AppState` → `appid`, `name`, `installdir` (all required strings). Everything else is ignored. + +- `appid`: canonical non-zero `u32`; else `BadId` (so `0`, `01`, `+5`, `-1`, ` 5`, `1e3`, `4294967296` and longer + are refused). +- `name`: the title rules. +- `installdir`: one plain folder name (no `\` or `/`, not `.` or `..`, no device name, ...); the install folder is + `\steamapps\common\` and must still be a valid `WinPath`; else `BadPath("installdir")`. +- Steam's redistributables and runtimes (`steam::is_tool`: 228980, 1070560, 1391110, 1628350, 1493710, 1826330, + 1161040) give `NotAGame`. + +Result: `steam:`, launch `steam://rungameid/`, cover `SteamLibraryCache { app_id }`. + +`steam::app_id_from_manifest_name` accepts exactly `appmanifest_.acf` (lowercase), for filtering a +folder listing before reading anything. + +## Epic `.item` (`epic::item`) + +The input must be UTF-8 (one BOM allowed), at most 1 MiB and at most 32 levels of objects and arrays (checked +before parsing; brackets inside strings do not count), a single JSON object with nothing after it. + +Reads `AppName`, `DisplayName`, `InstallLocation` (required strings) and `MainGameAppName` (optional string). +Unknown fields are ignored but must be valid JSON. Refused: `null` or any non-string for those fields +(`WrongType(field)`), a missing one (`Missing(field)`), any of them twice (`Duplicate(field)`), a document that is +not an object (`WrongType("item")`), syntax errors including trailing data and out-of-range numbers in read fields +(`Syntax { at }`). + +- `AppName`: `[A-Za-z0-9_-]{1,64}`; else `BadId`. It is the only field that reaches the launch URI. +- `DisplayName`: the title rules (error field `DisplayName`). +- `InstallLocation`: a `WinPath`; else `BadPath("InstallLocation")`. +- `MainGameAppName` present and different from `AppName`: an add-on, `NotAGame`. + +Result: `epic:`, launch `com.epicgames.launcher://apps/?action=launch&silent=true`, +a lettered cover. `bIsIncompleteInstall` is not read: the Epic launcher handles a half-installed game itself. + +## GOG (`gog::game`) + +Values the app reads from the registry (assumption, verify on the PC: `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\ +` and the HKCU twin), passed in as `GogEntry`. + +- `game_id`: 1–20 ASCII digits; else `BadId`. +- `name`: the title rules (error field `name`). +- `path`: a `WinPath`; else `BadPath("path")`. It becomes the install folder. +- `exe`: absolute, or relative to `path`; must lie strictly inside `path` (component-wise, ignoring case) and end in + `.exe` (ignoring case), so never a `.bat`, `.cmd` or `.lnk`; else `BadPath("exe")`. +- `working_dir`: absent or blank means the exe's folder; otherwise absolute or relative to `path`; else + `BadPath("working_dir")`. +- `launch_params`: at most 4096 bytes (`TooLong("launch_params")`), no control characters (tabs included) and no + unclosed `"` (`BadValue("launch_params")`). Split on spaces; `"` groups and is removed; nothing else (no + backslash escapes, no variables) is special. Then at most 32 arguments of at most 1024 bytes each. + +Result: `gog:`, `Launch::Exe` (started directly, never through a shell), a lettered cover. + +## Manual (`manual::game`) + +`exe` must be a `WinPath` ending in `.exe` (ignoring case) with a name before the extension; else `BadPath("exe")`. +The title is the given one, or the file name without `.exe`; title rules with error field `title`. Install and +working folder: the exe's folder; no arguments. Id: `manual:`, so the +same file added twice (any case, `/` or `\`) is the same game. + +## Domi (`domi::game`) + +`id` and a `DomiLaunch::Link { app }` follow the Atrium id rule; else `BadId`. `name` follows the title rules +(error field `name`). No install folder. + +`DomiLaunch::Web { url, allowed_hosts }`: `https://` (scheme any case) + host + optional path, query and fragment. +The host is lowercased and must be a DNS name (labels `[a-z0-9-]{1,63}`, no `-` at either end, no empty label, at +most 253 bytes) equal, ignoring case, to one of `allowed_hosts`; subdomains are not implied. Refused: other schemes, +user info (`@`), ports, IP-literal brackets, spaces, `"`, `\`, `<`, `>`, `^`, `` ` ``, `{`, `|`, `}`, any non-ASCII +byte (percent-encode it), `%` not followed by two hex digits, more than 2048 bytes. Errors: `BadValue("url")` or +`TooLong("url")`. + +## Launch strings + +`Launch::uri` rebuilds the URI from the variant's fields and re-validates them every time, so a hand-built or +tampered value yields `None`: + +| Variant | URI | Field rule | +| :-- | :-- | :-- | +| `SteamRunGameId(id)` | `steam://rungameid/` | `id != 0` | +| `Epic { app_name }` | `com.epicgames.launcher://apps/?action=launch&silent=true` | `[A-Za-z0-9_-]{1,64}` | +| `DomiLink { app }` | `domi-://open` | Atrium id | +| `Url(url)` | the URL itself | the URL rules, already normalised; `uri_checked(hosts)` also checks the host | +| `Exe { .. }` | none | `.exe` only; arguments checked as above | + +Deserialising a `Launch`, `Game` or `Library` runs the same checks; a stored URL's host cannot be checked without +the allow-list, so launching a stored web game goes through `uri_checked`. + +## Dedupe (`merge`) + +1. Scans are concatenated in order (at most `MAX_GAMES`); a `GameId` seen before is dropped (first wins). +2. For each install folder (compared ignoring case), only the games of the highest-priority source stay: + Steam > Epic > GOG > Domi > Manual. Games of the same source are never dropped for sharing a folder; games + without an install folder are never dropped here. +3. The result is sorted by title (lowercased, by code point), then by id, so it does not depend on scan order. diff --git a/docs/PORTABILITY.md b/docs/PORTABILITY.md new file mode 100644 index 0000000..38151c6 --- /dev/null +++ b/docs/PORTABILITY.md @@ -0,0 +1,37 @@ +# Portability + +Decision 15: `arena-core` stays pure (no I/O, no OS calls) and builds for Windows, Android and WebAssembly. It +uses only `core`/`alloc`/`std` collections and strings plus `serde` and `serde_json`; no `std::fs`, +`std::process`, `std::net`, `std::env`, `std::time` and no `unsafe`. + +## Targets checked + +| Target | Why | +| :-- | :-- | +| `x86_64-pc-windows-msvc` | the window app on the PC | +| `wasm32-unknown-unknown` | the PWA companion | +| `aarch64-linux-android` | the Android companion | + +## Commands + +From the repository root (both targets are installed with `rustup target add wasm32-unknown-unknown +aarch64-linux-android`): + +``` +cargo check -p arena-core +cargo check -p arena-core --target wasm32-unknown-unknown +cargo check -p arena-core --target aarch64-linux-android +``` + +`cargo check` needs no Android NDK: the crate has no build script and no C dependency, so nothing links. + +## Keeping it pure + +A quick audit that no I/O crept in (should print nothing): + +``` +grep -rnE "std::(fs|process|net|env|time)|SystemTime|Instant|Command" crates/arena-core/src +``` + +Decision 15 asks CI to run the three `cargo check` lines from `core-v0.1.0` on; this repository has no CI file +yet, so for now they are run by hand before each tag.