[repo] Merge: feature/core (arena-core 0.1.0: strict launcher parsers, library model, merge, PR #1)

This commit is contained in:
2026-11-22 23:37:58 +01:00
55 changed files with 4265 additions and 1 deletions
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
Generated
+238
View File
@@ -0,0 +1,238 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "arena-core"
version = "0.1.0"
dependencies = [
"proptest",
"serde",
"serde_json",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "proptest"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
dependencies = [
"bitflags",
"chacha20",
"core_detect",
"num-traits",
"rand",
"rand_xorshift",
"regex-syntax",
"unarray",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"getrandom",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_xorshift"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
dependencies = [
"rand_core",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unarray"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+7 -1
View File
@@ -1,3 +1,9 @@
[workspace] [workspace]
resolver = "2" resolver = "3"
members = ["crates/*"] members = ["crates/*"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/ArenaPublic"
+65
View File
@@ -6,3 +6,68 @@ frametime statistics and replay-ring logic. No I/O: inputs are bytes or values,
Windows, Android and WebAssembly. Windows, Android and WebAssembly.
Licence: MPL-2.0 (see LICENSE). 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<WinPath> = 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-<app>://
}
```
| Type | Rule |
| :-- | :-- |
| `GameId` | `<source>:<native>`, `[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
```
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "arena-core"
description = "Arena Domi core: strict parsers for game launcher files and the game library model. Pure, no I/O."
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[lib]
name = "arena_core"
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
proptest = { version = "1.12", default-features = false, features = ["std"] }
[lints.rust]
unsafe_code = "forbid"
+43
View File
@@ -0,0 +1,43 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Domi games: Atrium registry entries with `kind = "game"`, launched through their `domi-<app>://open` link, or
//! web games (Rosea, Moin) opened by URL.
use crate::error::ParseError;
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)]
pub enum DomiLaunch<'a> {
/// `domi-<app>://open`; `app` follows the Atrium id rules.
Link { app: &'a str },
/// A web game: `https://` only, the host must be one of `allowed_hosts`.
Web { url: &'a str, allowed_hosts: &'a [&'a str] },
}
/// The game for one Domi entry. `id` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end) and
/// becomes `domi:<id>`; `name` is the title. No install folder.
pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result<Game, ParseError> {
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,
})
}
+144
View File
@@ -0,0 +1,144 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Epic Games Launcher: one JSON `.item` manifest per installed app in
//! `%ProgramData%\Epic\EpicGamesLauncher\Data\Manifests`. Launch is
//! `com.epicgames.launcher://apps/<AppName>?action=launch&silent=true`.
use crate::error::ParseError;
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<Value>,
#[serde(rename = "DisplayName", default, deserialize_with = "present")]
display_name: Option<Value>,
#[serde(rename = "InstallLocation", default, deserialize_with = "present")]
install_location: Option<Value>,
#[serde(rename = "MainGameAppName", default, deserialize_with = "present")]
main_game_app_name: Option<Value>,
}
const FIELDS: [&str; 4] = ["AppName", "DisplayName", "InstallLocation", "MainGameAppName"];
fn present<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, 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<Game, ParseError> {
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::<IgnoredAny>(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<Option<&'a str>, 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))
}
+61
View File
@@ -0,0 +1,61 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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 std::fmt;
/// Why an input was refused. The `&'static str` names the field or the token kind; it never carries input text,
/// so an error is always safe to log.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseError {
/// The input is larger than [`crate::limits::MAX_FILE`].
TooLarge,
/// Objects are nested deeper than [`crate::limits::MAX_DEPTH`].
TooDeep,
/// A string or the whole input is not valid UTF-8.
NotUtf8,
/// The text is malformed at this byte offset.
Syntax { at: usize },
/// A required field is absent.
Missing(&'static str),
/// A field has the wrong type (an object where a string belongs, a number where a string belongs, ...).
WrongType(&'static str),
/// A path field is not a valid [`crate::WinPath`] or escapes where it must stay.
BadPath(&'static str),
/// An id (Steam app id, Epic app name, GOG id, Domi id, [`crate::GameId`]) is malformed or out of range.
BadId,
/// A key or an entry appears twice.
Duplicate(&'static str),
/// A key, value or field is longer than its cap.
TooLong(&'static str),
/// More entries than the cap allows.
TooMany(&'static str),
/// A text field, URL or argument holds characters it may not hold.
BadValue(&'static str),
/// The file is valid but describes something that is not a game (a Steam redistributable, an Epic add-on).
/// Callers skip these quietly.
NotAGame(&'static str),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::TooLarge => write!(f, "input is larger than {} bytes", crate::limits::MAX_FILE),
ParseError::TooDeep => write!(f, "nesting is deeper than {} levels", crate::limits::MAX_DEPTH),
ParseError::NotUtf8 => f.write_str("text is not valid UTF-8"),
ParseError::Syntax { at } => write!(f, "syntax error at byte {at}"),
ParseError::Missing(what) => write!(f, "missing field: {what}"),
ParseError::WrongType(what) => write!(f, "wrong type for field: {what}"),
ParseError::BadPath(what) => write!(f, "invalid path: {what}"),
ParseError::BadId => f.write_str("invalid id"),
ParseError::Duplicate(what) => write!(f, "duplicate: {what}"),
ParseError::TooLong(what) => write!(f, "too long: {what}"),
ParseError::TooMany(what) => write!(f, "too many: {what}"),
ParseError::BadValue(what) => write!(f, "invalid value: {what}"),
ParseError::NotAGame(what) => write!(f, "not a game: {what}"),
}
}
}
impl std::error::Error for ParseError {}
+68
View File
@@ -0,0 +1,68 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! GOG: the app reads one registry key per installed game (assumption, verify on the PC:
//! `HKLM\SOFTWARE\WOW6432Node\GOG.com\Games\<gameID>` with the values `gameID`, `gameName`, `path`, `exe`,
//! `workingDir`, `launchParam`) and passes the values in. Launch is the `.exe` directly.
use crate::error::ParseError;
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)]
pub struct GogEntry {
/// `gameID`: 1 to 20 digits.
pub game_id: String,
/// `gameName`: the title.
pub name: String,
/// `path`: the install folder, absolute.
pub path: String,
/// `exe`: the program, absolute or relative to `path`; must end in `.exe` and lie inside `path`.
pub exe: String,
/// `workingDir`: absolute or relative to `path`; empty or absent means the exe's folder.
pub working_dir: Option<String>,
/// `launchParam`: arguments, split on spaces with `"` grouping.
pub launch_params: Option<String>,
}
/// The game for one GOG entry.
pub fn game(e: &GogEntry) -> Result<Game, ParseError> {
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<WinPath, ParseError> {
let absolute = s.get(1..2) == Some(":") || s.starts_with(['\\', '/']);
if absolute { WinPath::parse(s) } else { base.join(s) }
}
+150
View File
@@ -0,0 +1,150 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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::limits::{MAX_GAME_ID, MAX_GOG_ID};
use crate::text;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
/// Where a game came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Source {
Steam,
Epic,
Gog,
Manual,
Domi,
}
impl Source {
/// Every source, in declaration order.
pub const ALL: [Source; 5] = [Source::Steam, Source::Epic, Source::Gog, Source::Manual, Source::Domi];
/// The lowercase name used in a [`GameId`] and in JSON: `steam`, `epic`, `gog`, `manual`, `domi`.
pub fn as_str(self) -> &'static str {
match self {
Source::Steam => "steam",
Source::Epic => "epic",
Source::Gog => "gog",
Source::Manual => "manual",
Source::Domi => "domi",
}
}
/// Which source wins when two games share an install folder: Steam > Epic > GOG > Domi > Manual.
pub fn priority(self) -> u8 {
match self {
Source::Steam => 5,
Source::Epic => 4,
Source::Gog => 3,
Source::Domi => 2,
Source::Manual => 1,
}
}
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Source {
type Err = ParseError;
/// Strict: exactly one of the lowercase names.
fn from_str(s: &str) -> Result<Self, Self::Err> {
Source::ALL.into_iter().find(|src| src.as_str() == s).ok_or(ParseError::BadId)
}
}
/// A game's id: `<source>:<native id>`, only `[a-z0-9:._-]`, at most [`crate::limits::MAX_GAME_ID`] bytes.
///
/// The native part is checked per source: Steam a canonical non-zero `u32`, Epic `[a-z0-9_-]{1,64}` (the app
/// name, lowercased), GOG 1 to 20 digits, Manual 16 lowercase hex digits, Domi an Atrium id.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct GameId(String);
impl GameId {
/// Builds and checks `<source>:<native>`.
pub fn new(source: Source, native: &str) -> Result<GameId, ParseError> {
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 {
&self.0
}
/// The source named by the prefix.
pub fn source(&self) -> Source {
// 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 `<source>:`.
pub fn native(&self) -> &str {
self.0.split_once(':').map_or("", |(_, n)| n)
}
}
impl fmt::Display for GameId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for GameId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
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 `<source>:`.
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),
}
}
impl TryFrom<String> for GameId {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
impl From<GameId> for String {
fn from(id: GameId) -> String {
id.0
}
}
impl AsRef<str> for GameId {
fn as_ref(&self) -> &str {
&self.0
}
}
+248
View File
@@ -0,0 +1,248 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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::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
/// directly (never through a shell) with an explicit working folder.
///
/// The fields are public so callers can match on them, but every builder ([`Launch::steam`], [`Launch::epic`],
/// [`Launch::exe`], [`Launch::domi_link`], [`Launch::web`]) validates, deserialising validates, and
/// [`Launch::uri`] validates again, so a hand-built bad value yields no URI.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", try_from = "LaunchRepr")]
pub enum Launch {
/// `steam://rungameid/<id>`.
SteamRunGameId(u32),
/// `com.epicgames.launcher://apps/<app_name>?action=launch&silent=true`; `app_name` is `[A-Za-z0-9_-]{1,64}`.
Epic { app_name: String },
/// GOG and manual games: the `.exe`, its working folder and the arguments, passed as separate arguments.
Exe { exe: WinPath, working_dir: WinPath, args: Vec<String> },
/// `domi-<app>://open`; `app` follows the Atrium id rules.
DomiLink { app: String },
/// A web game: `https://` only, the host on an allow-list the caller passes in.
Url(String),
}
impl Launch {
/// A Steam launch; the app id may not be 0.
pub fn steam(app_id: u32) -> Result<Launch, ParseError> {
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<Launch, ParseError> {
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<String>) -> Result<Launch, ParseError> {
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<Launch, ParseError> {
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://<host>[/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<Launch, ParseError> {
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 (and that it is
/// already normalised); use [`Launch::uri_checked`] to apply the host allow-list again.
pub fn uri(&self) -> Option<String> {
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<String> {
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<Vec<String>, 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")]
enum LaunchRepr {
SteamRunGameId(u32),
Epic { app_name: String },
Exe { exe: WinPath, working_dir: WinPath, args: Vec<String> },
DomiLink { app: String },
Url(String),
}
impl TryFrom<LaunchRepr> 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<Self, Self::Error> {
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) => check_url(&url).map(|(normal, _)| Launch::Url(normal)),
}
}
}
+50
View File
@@ -0,0 +1,50 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! The pure core of Arena Domi: strict parsers for game launcher files and the game library model.
//!
//! Nothing here touches the file system, processes, the network, the environment, the registry or the clock.
//! Inputs are bytes or values; outputs are [`Game`]s and a merged [`Library`]. Every parser treats its input as
//! hostile: sizes, depth, lengths and counts are capped ([`limits`]), errors are typed ([`ParseError`]) and no input
//! can make the crate panic.
//!
//! Sources: [`steam`] (`libraryfolders.vdf`, `appmanifest_<id>.acf`), [`epic`] (`.item` JSON), [`gog`] (registry
//! values the app passes in), [`manual`] (an `.exe` the user picked) and [`domi`] (Domi games from the Atrium
//! registry). [`merge`] dedupes the scans into one library.
//!
//! Launch strings are built by [`Launch::uri`] only from validated, parsed fields.
#![forbid(unsafe_code)]
#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::string_slice,
clippy::panic,
clippy::todo,
clippy::unimplemented,
clippy::unreachable
)]
mod error;
mod id;
mod launch;
pub mod limits;
mod model;
mod path;
mod text;
pub mod vdf;
pub mod domi;
pub mod epic;
pub mod gog;
pub mod manual;
pub mod steam;
pub use domi::DomiLaunch;
pub use error::ParseError;
pub use id::{GameId, Source};
pub use launch::Launch;
pub use model::{CoverHint, Game, Library, merge};
pub use path::WinPath;
+45
View File
@@ -0,0 +1,45 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Every cap the parsers enforce. Anything over a cap is refused, never truncated. `docs/FORMATS.md` lists them
//! with the error each one gives.
/// Largest input file (VDF, ACF, `.item` JSON), in bytes.
pub const MAX_FILE: usize = 1 << 20;
/// Deepest nesting of objects (VDF `{`, JSON `{` and `[`).
pub const MAX_DEPTH: usize = 32;
/// Longest VDF key, in bytes after unescaping.
pub const MAX_KEY: usize = 256;
/// Longest VDF value, in bytes after unescaping.
pub const MAX_VALUE: usize = 4096;
/// Most escape sequences in one VDF string.
pub const MAX_ESCAPES: usize = 256;
/// Most key/value pairs in one VDF document, counted over every level.
pub const MAX_ENTRIES: usize = 65_536;
/// Most Steam library folders in one `libraryfolders.vdf`.
pub const MAX_LIBRARIES: usize = 64;
/// Longest Windows path, in UTF-16 code units (`MAX_PATH`).
pub const MAX_PATH: usize = 260;
/// Longest game title, in characters after trimming.
pub const MAX_TITLE: usize = 256;
/// Longest [`crate::GameId`], in bytes.
pub const MAX_GAME_ID: usize = 96;
/// Longest Epic app name, in bytes (`[A-Za-z0-9_-]{1,64}`).
pub const MAX_EPIC_APP: usize = 64;
/// Longest Domi app id, in bytes (Atrium id rules: `[a-z0-9-]{1,32}`, no `-` at either end).
pub const MAX_DOMI_ID: usize = 32;
/// Longest GOG game id, in digits.
pub const MAX_GOG_ID: usize = 20;
/// Longest launch-parameter string a GOG entry may carry, in bytes.
pub const MAX_ARGS_LINE: usize = 4096;
/// Most arguments an [`crate::Launch::Exe`] may carry.
pub const MAX_ARGS: usize = 32;
/// Longest single argument, in bytes.
pub const MAX_ARG: usize = 1024;
/// Longest web-game URL, in bytes.
pub const MAX_URL: usize = 2048;
/// Longest host name in a web-game URL, in bytes.
pub const MAX_HOST: usize = 253;
/// Most games one [`crate::merge`] call accepts over all scans; the rest are dropped.
pub const MAX_GAMES: usize = 100_000;
+40
View File
@@ -0,0 +1,40 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! A game the user added by picking its `.exe`.
use crate::error::ParseError;
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<Game, ParseError> {
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())?,
})
}
+126
View File
@@ -0,0 +1,126 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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,
/// Display title: trimmed, 1 to [`crate::limits::MAX_TITLE`] characters, no control characters.
pub title: String,
pub install_dir: Option<WinPath>,
pub launch: Launch,
pub cover: Option<CoverHint>,
}
/// 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<WinPath>,
launch: Launch,
cover: Option<CoverHint>,
}
impl TryFrom<GameRepr> for Game {
type Error = ParseError;
fn try_from(r: GameRepr) -> Result<Self, Self::Error> {
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")]
pub enum CoverHint {
/// Steam's own local library cache for this app id (the app finds the file).
SteamLibraryCache { app_id: u32 },
/// A picture file on disk.
LocalFile(WinPath),
/// A lettered tile: the title's first letter or digit on a colour of this hue (0 to 359).
Lettered { letter: char, hue: u16 },
}
impl CoverHint {
/// The lettered tile for a game: the first letter or digit of `title` (uppercased; `#` when there is none) and a
/// hue derived from `id`, so a game keeps its colour across scans.
pub fn lettered(title: &str, id: &GameId) -> CoverHint {
crate::text::lettered(title, id)
}
}
/// The merged library, ordered by title.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Library {
pub games: Vec<Game>,
}
impl Library {
/// The game with this id.
pub fn get(&self, id: &GameId) -> Option<&Game> {
self.games.iter().find(|g| &g.id == id)
}
pub fn len(&self) -> usize {
self.games.len()
}
pub fn is_empty(&self) -> bool {
self.games.is_empty()
}
}
/// Merges per-source scans into one library.
///
/// - The same [`GameId`] is kept once (its first occurrence).
/// - Games of different sources with the same install folder (compared ignoring case): only the highest
/// [`Source::priority`] stays (Steam > Epic > GOG > Domi > Manual). Games of the same source are never dropped
/// for sharing a folder.
/// - 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<Vec<Game>>) -> Library {
let mut seen: BTreeSet<GameId> = BTreeSet::new();
let mut games: Vec<Game> = 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<String, u8> = 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 }
}
+173
View File
@@ -0,0 +1,173 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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::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 `..`
/// components, NUL and other control characters, `<>:"|?*` (a `:` only after the drive letter), device names
/// (`CON`, `NUL`, `COM1`, ...) as any component, components ending in a dot or a space, and paths over
/// [`crate::limits::MAX_PATH`] UTF-16 units. Normalised: `/` becomes `\`, repeated separators collapse, the drive
/// letter is uppercase and a trailing separator is dropped (except on the drive root `X:\`).
///
/// Equality is exact on the normalised text; [`WinPath::eq_ignore_case`] compares the way Windows does.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct WinPath(String);
impl WinPath {
/// Checks and normalises `s`.
pub fn parse(s: &str) -> Result<WinPath, ParseError> {
// 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 {
&self.0
}
/// 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<WinPath, ParseError> {
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<WinPath> {
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> {
self.components().last()
}
/// The components after the drive root.
pub fn components(&self) -> impl Iterator<Item = &str> {
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.
pub fn key(&self) -> String {
self.0.to_lowercase()
}
/// True when both name the same place, ignoring case.
pub fn eq_ignore_case(&self, other: &WinPath) -> bool {
self.key() == other.key()
}
/// True when `self` is `base` or lies inside it (component-wise, ignoring case).
pub fn starts_with(&self, base: &WinPath) -> bool {
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)
}
}
impl FromStr for WinPath {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
WinPath::parse(s)
}
}
impl TryFrom<String> for WinPath {
type Error = ParseError;
fn try_from(s: String) -> Result<Self, Self::Error> {
WinPath::parse(&s)
}
}
impl From<WinPath> for String {
fn from(p: WinPath) -> String {
p.0
}
}
impl AsRef<str> for WinPath {
fn as_ref(&self) -> &str {
&self.0
}
}
+112
View File
@@ -0,0 +1,112 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Steam: `config/libraryfolders.vdf` lists the library folders; each installed app has
//! `<library>/steamapps/appmanifest_<id>.acf`. Launch is `steam://rungameid/<id>`.
use crate::error::ParseError;
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<Vec<WinPath>, ParseError> {
let doc = vdf::parse(vdf)?;
let root = obj(&doc, "libraryfolders")?;
let mut out: Vec<WinPath> = 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_<id>.acf` inside `library` (the folder holding `steamapps`). The install
/// folder is `<library>\steamapps\common\<installdir>`, 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<Game, ParseError> {
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_<id>.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<u32> {
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 {
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)),
}
}
+85
View File
@@ -0,0 +1,85 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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 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;
/// 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<String, ParseError> {
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<u32> {
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::<u32>().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).
pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for &b in bytes {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub(crate) fn lettered(title: &str, id: &GameId) -> CoverHint {
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 }
}
+341
View File
@@ -0,0 +1,341 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! A strict tokenizer, parser and writer for Valve's KeyValues text format (VDF), as used by Steam's
//! `libraryfolders.vdf` and `appmanifest_<id>.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: 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)]
pub struct Token {
pub kind: TokenKind,
pub at: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenKind {
/// `{`
Open,
/// `}`
Close,
/// A quoted string, unescaped.
Str(String),
}
/// A value: a string or a nested object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Value {
Str(String),
Obj(Obj),
}
/// 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<String, usize>,
/// 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, 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> {
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> {
let i = *self.index.get(&key.to_ascii_lowercase())?;
self.entries.get(i).map(|(_, v)| v)
}
/// The pairs in file order.
pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
self.entries.iter().map(|(k, v)| (k.as_str(), v))
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
/// 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<Lexer<'a>, 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<u8> {
self.input.get(self.pos + ahead).copied()
}
fn next_token(&mut self) -> Result<Option<Token>, 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<String, ParseError> {
let start = self.pos;
self.pos += 1;
let mut buf: Vec<u8> = 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<Vec<Token>, ParseError> {
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<Obj, ParseError> {
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<Obj, ParseError> {
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 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('"');
}
+120
View File
@@ -0,0 +1,120 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Epic `.item` manifests: valid fixtures and the hostile ones that are Epic-specific.
use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, epic, limits};
#[test]
fn valid_item() {
let g = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap();
assert_eq!(g.id.as_str(), "epic:exampleracer_main-01");
assert_eq!(g.source, Source::Epic);
assert_eq!(g.title, "Example Racer");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\Program Files\Epic Games\ExampleRacer"));
assert_eq!(g.launch, Launch::Epic { app_name: "ExampleRacer_Main-01".into() });
assert_eq!(
g.launch.uri().as_deref(),
Some("com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true")
);
assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'E', .. })), "{:?}", g.cover);
}
#[test]
fn bom_is_accepted() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(include_bytes!("fixtures/epic/valid.item"));
assert!(epic::item(&bytes).is_ok());
}
#[test]
fn addon_is_not_a_game() {
let r = epic::item(include_bytes!("fixtures/epic/addon.item"));
assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}");
}
#[test]
fn wrong_type_app_name() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/wrongtype.item")), Err(ParseError::WrongType("AppName")));
}
#[test]
fn wrong_type_for_each_field() {
let cases = [
(r#"{"AppName":"A","DisplayName":["x"],"InstallLocation":"C:\\G"}"#, "DisplayName"),
(r#"{"AppName":"A","DisplayName":"x","InstallLocation":{"a":1}}"#, "InstallLocation"),
(r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","MainGameAppName":7}"#, "MainGameAppName"),
(r#"{"AppName":null,"DisplayName":"x","InstallLocation":"C:\\G"}"#, "AppName"),
];
for (json, field) in cases {
assert_eq!(epic::item(json.as_bytes()), Err(ParseError::WrongType(field)), "{json}");
}
assert_eq!(epic::item(b"[]"), Err(ParseError::WrongType("item")));
assert_eq!(epic::item(b"\"text\""), Err(ParseError::WrongType("item")));
}
#[test]
fn duplicate_key() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName")));
}
#[test]
fn traversal_in_install_location() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/traversal.item")), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn unc_install_location() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/unc.item")), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn injected_app_name() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/badappname.item")), Err(ParseError::BadId));
}
#[test]
fn app_name_rules() {
let long = "a".repeat(limits::MAX_EPIC_APP + 1);
for bad in ["", " A", "A B", "a.b", "a/b", "a%20", "a?b", "ä", long.as_str()] {
let json = format!(r#"{{"AppName":"{bad}","DisplayName":"x","InstallLocation":"C:\\G"}}"#);
assert_eq!(epic::item(json.as_bytes()), Err(ParseError::BadId), "{bad:?}");
}
let ok = "A".repeat(limits::MAX_EPIC_APP);
let json = format!(r#"{{"AppName":"{ok}","DisplayName":"x","InstallLocation":"C:\\G"}}"#);
assert!(epic::item(json.as_bytes()).is_ok());
}
#[test]
fn missing_fields() {
assert_eq!(epic::item(include_bytes!("fixtures/epic/missing.item")), Err(ParseError::Missing("AppName")));
assert_eq!(epic::item(br#"{"AppName":"A","InstallLocation":"C:\\G"}"#), Err(ParseError::Missing("DisplayName")));
assert_eq!(epic::item(br#"{"AppName":"A","DisplayName":"x"}"#), Err(ParseError::Missing("InstallLocation")));
}
#[test]
fn trailing_garbage() {
assert!(matches!(epic::item(include_bytes!("fixtures/epic/trailing.item")), Err(ParseError::Syntax { .. })));
}
#[test]
fn absurd_number() {
let r = epic::item(include_bytes!("fixtures/epic/absurd.item"));
assert!(matches!(r, Err(ParseError::Syntax { .. }) | Err(ParseError::WrongType("AppName"))), "{r:?}");
}
#[test]
fn syntax_error_offset_points_into_the_input() {
let json = b"{\n \"AppName\": \"A\",\n oops\n}";
match epic::item(json) {
Err(ParseError::Syntax { at }) => assert!(at < json.len(), "{at}"),
other => panic!("{other:?}"),
}
}
#[test]
fn main_game_equal_to_app_name_is_a_game() {
let json = br#"{"AppName":"A","MainGameAppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#;
assert!(epic::item(json).is_ok());
}
+6
View File
@@ -0,0 +1,6 @@
{
"FormatVersion": 0,
"DisplayName": "Absurd Number",
"InstallLocation": "C:\\Games\\Absurd",
"AppName": 1e999999
}
+7
View File
@@ -0,0 +1,7 @@
{
"FormatVersion": 0,
"DisplayName": "Example Racer - Bonus Cars",
"InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer",
"AppName": "ExampleRacerBonusCars",
"MainGameAppName": "ExampleRacer_Main-01"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Injected",
"InstallLocation": "C:\\Games\\Injected",
"AppName": "x?action=uninstall&a=../../"
}
+6
View File
@@ -0,0 +1,6 @@
{
"DisplayName": "Twice",
"InstallLocation": "C:\\Games\\Twice",
"AppName": "TwiceA",
"AppName": "TwiceB"
}
+4
View File
@@ -0,0 +1,4 @@
{
"DisplayName": "No App Name",
"InstallLocation": "C:\\Games\\NoAppName"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Trailing",
"InstallLocation": "C:\\Games\\Trailing",
"AppName": "Trailing"
} {"AppName": "Second"}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Escape Artist",
"InstallLocation": "C:\\Games\\..\\Windows\\System32",
"AppName": "EscapeArtist"
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Remote",
"InstallLocation": "\\\\evil-server\\share\\Game",
"AppName": "Remote"
}
+26
View File
@@ -0,0 +1,26 @@
{
"FormatVersion": 0,
"bIsIncompleteInstall": false,
"LaunchCommand": "",
"LaunchExecutable": "ExampleRacer/Binaries/Win64/ExampleRacer.exe",
"ManifestLocation": "C:\\ProgramData\\Epic\\EpicGamesLauncher\\Data\\Manifests",
"bIsApplication": true,
"bIsExecutable": true,
"bIsManaged": false,
"bNeedsValidation": false,
"bRequiresAuth": true,
"bCanRunOffline": true,
"DisplayName": "Example Racer",
"InstallationGuid": "00000000000000000000000000000001",
"InstallLocation": "C:\\Program Files\\Epic Games\\ExampleRacer",
"CatalogNamespace": "example",
"CatalogItemId": "00000000000000000000000000000002",
"AppName": "ExampleRacer_Main-01",
"AppVersionString": "1.0.0",
"MainGameCatalogNamespace": "example",
"MainGameCatalogItemId": "00000000000000000000000000000002",
"MainGameAppName": "ExampleRacer_Main-01",
"AppCategories": ["public", "games", "applications"],
"ExpectingDLCInstalled": {},
"InstallTags": []
}
+5
View File
@@ -0,0 +1,5 @@
{
"DisplayName": "Wrong Type",
"InstallLocation": "C:\\Games\\WrongType",
"AppName": 12345
}
@@ -0,0 +1,33 @@
"AppState"
{
"appid" "1234560"
"universe" "1"
"LauncherPath" "C:\\Program Files (x86)\\Steam\\steam.exe"
"name" "Example Quest: The \"Quoted\" Edition"
"StateFlags" "4"
"installdir" "Example Quest"
"LastUpdated" "0"
"SizeOnDisk" "1000"
"StagingSize" "0"
"buildid" "1"
"LastOwner" "0"
"AutoUpdateBehavior" "0"
"AllowOtherDownloadsWhileRunning" "0"
"ScheduledAutoUpdate" "0"
"InstalledDepots"
{
"1234561"
{
"manifest" "1"
"size" "1000"
}
}
"UserConfig"
{
"language" "english"
}
"MountedConfig"
{
"language" "english"
}
}
@@ -0,0 +1,8 @@
"AppState"
{
"appid" "228980"
"universe" "1"
"name" "Steamworks Common Redistributables"
"StateFlags" "4"
"installdir" "Steamworks Shared"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "1234571"
"name" "Somewhere Else"
"installdir" "C:\\Windows"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "99999999999999999999999999"
"name" "Absurd"
"installdir" "Absurd"
}
@@ -0,0 +1,7 @@
"AppState"
{
"appid" "1234573"
"name" "First Name"
"installdir" "Twice"
"Name" "Second Name"
}
@@ -0,0 +1,6 @@
"AppState"
{
"appid" "1234570"
"name" "Escape Artist"
"installdir" "..\\..\\..\\Windows\\System32"
}
@@ -0,0 +1,5 @@
"AppState"
{
"appid" "1234574"
"name" "Never Ends
}
@@ -0,0 +1,9 @@
"AppState"
{
"appid"
{
"value" "1234572"
}
"name" "Wrong Type"
"installdir" "Wrong Type"
}
@@ -0,0 +1,30 @@
"libraryfolders"
{
"0"
{
"path" "C:\\Program Files (x86)\\Steam"
"label" ""
"contentid" "1111111111111111111"
"totalsize" "0"
"update_clean_bytes_tally" "0"
"time_last_update_verified" "0"
"apps"
{
"228980" "0"
"1234560" "1000"
}
}
"1"
{
"path" "D:\\SteamLibrary"
"label" "Games"
"contentid" "2222222222222222222"
"totalsize" "1000000000000"
"update_clean_bytes_tally" "0"
"time_last_update_verified" "0"
"apps"
{
"7654320" "2000"
}
}
}
@@ -0,0 +1,11 @@
"libraryfolders"
{
"0"
{
"path" "D:\\SteamLibrary"
}
"1"
{
"path" "d:\\steamlibrary\\"
}
}
@@ -0,0 +1,8 @@
// An older Steam layout: numbered keys hold the path directly.
"LibraryFolders"
{
"TimeNextStatsReport" "0"
"ContentStatsID" "-1"
"1" "D:\\SteamLibrary"
"2" "E:/Games/Steam"
}
@@ -0,0 +1,7 @@
"libraryfolders"
{
"0"
{
"path" "\\\\evil-server\\share\\Steam"
}
}
@@ -0,0 +1,10 @@
"libraryfolders"
{
"0"
{
"path"
{
"drive" "C:"
}
}
}
+147
View File
@@ -0,0 +1,147 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! GOG entries built from registry values the app passes in.
use arena_core::gog::{GogEntry, game};
use arena_core::{Launch, ParseError, Source, WinPath, limits};
fn entry() -> GogEntry {
GogEntry {
game_id: "1207658924".into(),
name: "Example Saga".into(),
path: r"C:\GOG Games\Example Saga".into(),
exe: r"C:\GOG Games\Example Saga\bin\x64\saga.exe".into(),
working_dir: Some(r"C:\GOG Games\Example Saga\bin\x64".into()),
launch_params: Some(r#"-skipintro "-profile=Slot One""#.into()),
}
}
fn exe_parts(l: &Launch) -> (&str, &str, Vec<&str>) {
match l {
Launch::Exe { exe, working_dir, args } => {
(exe.as_str(), working_dir.as_str(), args.iter().map(String::as_str).collect())
}
other => panic!("{other:?}"),
}
}
#[test]
fn valid_entry() {
let g = game(&entry()).unwrap();
assert_eq!(g.id.as_str(), "gog:1207658924");
assert_eq!(g.source, Source::Gog);
assert_eq!(g.title, "Example Saga");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"C:\GOG Games\Example Saga"));
let (exe, wd, args) = exe_parts(&g.launch);
assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe");
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert_eq!(args, ["-skipintro", "-profile=Slot One"]);
assert_eq!(g.launch.uri(), None, "an exe launch has no URI");
}
#[test]
fn relative_exe_and_defaults() {
let mut e = entry();
e.exe = r"bin\x64\saga.exe".into();
e.working_dir = Some(String::new());
e.launch_params = Some(" ".into());
let g = game(&e).unwrap();
let (exe, wd, args) = exe_parts(&g.launch);
assert_eq!(exe, r"C:\GOG Games\Example Saga\bin\x64\saga.exe");
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert!(args.is_empty());
e.working_dir = None;
e.launch_params = None;
let g = game(&e).unwrap();
let (_, wd, args) = exe_parts(&g.launch);
assert_eq!(wd, r"C:\GOG Games\Example Saga\bin\x64");
assert!(args.is_empty());
e.working_dir = Some("data".into());
let g = game(&e).unwrap();
let (_, wd, _) = exe_parts(&g.launch);
assert_eq!(wd, r"C:\GOG Games\Example Saga\data");
}
#[test]
fn bad_ids() {
for bad in ["", "abc", "12a", "-1", " 1", "123456789012345678901", "1.5"] {
let mut e = entry();
e.game_id = bad.into();
assert_eq!(game(&e), Err(ParseError::BadId), "{bad:?}");
}
let mut e = entry();
e.game_id = "1".repeat(limits::MAX_GOG_ID);
assert!(game(&e).is_ok());
}
#[test]
fn bad_paths() {
let cases: [(&str, &str, &str); 9] = [
(r"\\server\share\Game", r"\\server\share\Game\g.exe", "path"),
(r"C:\GOG Games\..\Windows", r"C:\Windows\g.exe", "path"),
(r"relative\Game", r"relative\Game\g.exe", "path"),
(r"C:\GOG Games\Example Saga", r"C:\Windows\System32\cmd.exe", "exe"),
(r"C:\GOG Games\Example Saga", r"..\..\Windows\System32\cmd.exe", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.bat", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\run.cmd", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga\game.exe.lnk", "exe"),
(r"C:\GOG Games\Example Saga", r"C:\GOG Games\Example Saga Evil\g.exe", "exe"),
];
for (path, exe, field) in cases {
let mut e = entry();
e.path = path.into();
e.exe = exe.into();
e.working_dir = None;
assert_eq!(game(&e), Err(ParseError::BadPath(field)), "{path} {exe}");
}
let mut e = entry();
e.working_dir = Some(r"\\?\C:\x".into());
assert_eq!(game(&e), Err(ParseError::BadPath("working_dir")));
}
#[test]
fn exe_extension_ignores_case() {
let mut e = entry();
e.exe = r"C:\GOG Games\Example Saga\SAGA.EXE".into();
assert!(game(&e).is_ok());
}
#[test]
fn bad_args() {
for bad in ["a\u{0}b", "a\nb", "a\rb", "\"unclosed", "a\u{7}"] {
let mut e = entry();
e.launch_params = Some(bad.into());
assert_eq!(game(&e), Err(ParseError::BadValue("launch_params")), "{bad:?}");
}
let mut e = entry();
e.launch_params = Some(vec!["-a"; limits::MAX_ARGS + 1].join(" "));
assert_eq!(game(&e), Err(ParseError::TooMany("args")));
e.launch_params = Some("x".repeat(limits::MAX_ARG + 1));
assert_eq!(game(&e), Err(ParseError::TooLong("arg")));
e.launch_params = Some("x ".repeat(limits::MAX_ARGS_LINE));
assert_eq!(game(&e), Err(ParseError::TooLong("launch_params")));
}
#[test]
fn shell_metacharacters_stay_inside_one_argument() {
let mut e = entry();
e.launch_params = Some(r#""a & calc" |b ^c %PATH%"#.into());
let g = game(&e).unwrap();
let (_, _, args) = exe_parts(&g.launch);
assert_eq!(args, ["a & calc", "|b", "^c", "%PATH%"]);
}
#[test]
fn bad_title() {
let mut e = entry();
e.name = " ".into();
assert_eq!(game(&e), Err(ParseError::Missing("name")));
e.name = "x".repeat(limits::MAX_TITLE + 1);
assert_eq!(game(&e), Err(ParseError::TooLong("name")));
e.name = "a\u{1b}[31mred".into();
assert_eq!(game(&e), Err(ParseError::BadValue("name")));
}
+323
View File
@@ -0,0 +1,323 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Hostile input across every parser: refused with a typed error, never a panic.
use arena_core::gog::GogEntry;
use arena_core::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE};
use arena_core::{ParseError, WinPath, epic, gog, manual, steam, vdf};
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
const FIXTURES: [&[u8]; 23] = [
include_bytes!("fixtures/steam/libraryfolders.vdf"),
include_bytes!("fixtures/steam/libraryfolders_old.vdf"),
include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf"),
include_bytes!("fixtures/steam/libraryfolders_unc.vdf"),
include_bytes!("fixtures/steam/libraryfolders_dup.vdf"),
include_bytes!("fixtures/steam/appmanifest_1234560.acf"),
include_bytes!("fixtures/steam/appmanifest_228980.acf"),
include_bytes!("fixtures/steam/appmanifest_traversal.acf"),
include_bytes!("fixtures/steam/appmanifest_absolute.acf"),
include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"),
include_bytes!("fixtures/steam/appmanifest_dupkey.acf"),
include_bytes!("fixtures/steam/appmanifest_absurd.acf"),
include_bytes!("fixtures/steam/appmanifest_unterminated.acf"),
include_bytes!("fixtures/epic/valid.item"),
include_bytes!("fixtures/epic/addon.item"),
include_bytes!("fixtures/epic/wrongtype.item"),
include_bytes!("fixtures/epic/dupkey.item"),
include_bytes!("fixtures/epic/traversal.item"),
include_bytes!("fixtures/epic/unc.item"),
include_bytes!("fixtures/epic/badappname.item"),
include_bytes!("fixtures/epic/missing.item"),
include_bytes!("fixtures/epic/trailing.item"),
include_bytes!("fixtures/epic/absurd.item"),
];
/// Runs every byte parser over `input`; any panic fails the test.
fn all_parsers(input: &[u8]) {
let _ = vdf::tokenize(input);
let _ = vdf::parse(input);
let _ = steam::library_folders(input);
let _ = steam::app_manifest(input, &lib());
let _ = epic::item(input);
}
// ---- huge files -------------------------------------------------------------------------------------------
#[test]
fn huge_file_is_refused_before_parsing() {
let mut big = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec();
big.resize(MAX_FILE + 1, b' ');
assert_eq!(vdf::tokenize(&big), Err(ParseError::TooLarge));
assert_eq!(vdf::parse(&big), Err(ParseError::TooLarge));
assert_eq!(steam::library_folders(&big), Err(ParseError::TooLarge));
assert_eq!(steam::app_manifest(&big, &lib()), Err(ParseError::TooLarge));
let mut json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G"}"#.to_vec();
json.resize(MAX_FILE + 1, b' ');
assert_eq!(epic::item(&json), Err(ParseError::TooLarge));
}
#[test]
fn exactly_max_file_is_still_read() {
let mut ok = b"\"AppState\" { \"appid\" \"10\" \"name\" \"N\" \"installdir\" \"N\" }".to_vec();
ok.resize(MAX_FILE, b' ');
assert!(steam::app_manifest(&ok, &lib()).is_ok());
}
// ---- deep nesting -----------------------------------------------------------------------------------------
fn nested_vdf(depth: usize) -> Vec<u8> {
let mut s = Vec::new();
for _ in 0..depth {
s.extend_from_slice(b"\"k\" { ");
}
for _ in 0..depth {
s.extend_from_slice(b"} ");
}
s
}
#[test]
fn deep_vdf_is_refused() {
assert!(vdf::parse(&nested_vdf(MAX_DEPTH)).is_ok());
assert_eq!(vdf::parse(&nested_vdf(MAX_DEPTH + 1)), Err(ParseError::TooDeep));
// Far deeper than any stack would survive with naive recursion.
assert_eq!(vdf::parse(&nested_vdf(100_000)), Err(ParseError::TooDeep));
assert_eq!(steam::library_folders(&nested_vdf(5_000)), Err(ParseError::TooDeep));
}
#[test]
fn deep_json_is_refused() {
let deep = |n: usize| {
let mut s = String::from(r#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G","Deep":"#);
s.push_str(&"[".repeat(n));
s.push_str(&"]".repeat(n));
s.push('}');
s
};
assert!(epic::item(deep(MAX_DEPTH - 1).as_bytes()).is_ok());
assert_eq!(epic::item(deep(MAX_DEPTH).as_bytes()), Err(ParseError::TooDeep));
assert_eq!(epic::item(deep(200_000).as_bytes()), Err(ParseError::TooDeep));
// Brackets inside strings do not count.
let in_string = format!(r#"{{"AppName":"A","DisplayName":"{}","InstallLocation":"C:\\G"}}"#, "[".repeat(200));
assert!(epic::item(in_string.as_bytes()).is_ok());
}
// ---- wrong types ------------------------------------------------------------------------------------------
#[test]
fn wrong_types_everywhere() {
let acf = |body: &str| format!("\"AppState\" {{ {body} }}");
let cases = [
(acf("\"appid\" { } \"name\" \"N\" \"installdir\" \"N\""), "appid"),
(acf("\"appid\" \"10\" \"name\" { } \"installdir\" \"N\""), "name"),
(acf("\"appid\" \"10\" \"name\" \"N\" \"installdir\" { }"), "installdir"),
("\"AppState\" \"text\"".to_string(), "AppState"),
];
for (text, field) in cases {
assert_eq!(steam::app_manifest(text.as_bytes(), &lib()), Err(ParseError::WrongType(field)), "{text}");
}
assert_eq!(
steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" { } } }"),
Err(ParseError::WrongType("path"))
);
}
// ---- bad paths --------------------------------------------------------------------------------------------
#[test]
fn bad_library_paths() {
for bad in [r"..\\Steam", r"C:\\Steam\\..\\..\\Windows", r"\\\\?\\C:\\Steam", r"Steam", "C:\\\\CON", "C:"] {
let text = format!("\"libraryfolders\" {{ \"0\" {{ \"path\" \"{bad}\" }} }}");
assert_eq!(steam::library_folders(text.as_bytes()), Err(ParseError::BadPath("path")), "{bad}");
}
}
#[test]
fn bad_paths_in_every_source() {
let r = epic::item(include_bytes!("fixtures/epic/traversal.item"));
assert_eq!(r, Err(ParseError::BadPath("InstallLocation")));
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
let e = GogEntry {
game_id: "1".into(),
name: "G".into(),
path: r"C:\G\..\..".into(),
exe: r"C:\g.exe".into(),
working_dir: None,
launch_params: None,
};
assert_eq!(gog::game(&e), Err(ParseError::BadPath("path")));
assert_eq!(manual::game(r"C:\G\..\g.exe", None), Err(ParseError::BadPath("exe")));
}
// ---- non-UTF-8 --------------------------------------------------------------------------------------------
#[test]
fn non_utf8_names_are_refused() {
let mut acf = b"\"AppState\" { \"appid\" \"10\" \"name\" \"Bad ".to_vec();
acf.extend_from_slice(&[0xC3, 0x28, 0xFF]);
acf.extend_from_slice(b"\" \"installdir\" \"N\" }");
assert_eq!(vdf::tokenize(&acf), Err(ParseError::NotUtf8));
assert_eq!(steam::app_manifest(&acf, &lib()), Err(ParseError::NotUtf8));
let mut key = b"\"AppState\" { \"".to_vec();
key.extend_from_slice(&[0xED, 0xA0, 0x80]); // an encoded surrogate
key.extend_from_slice(b"\" \"x\" }");
assert_eq!(steam::app_manifest(&key, &lib()), Err(ParseError::NotUtf8));
let mut json = br#"{"AppName":"A","DisplayName":""#.to_vec();
json.extend_from_slice(&[0x80, 0x80]);
json.extend_from_slice(br#"","InstallLocation":"C:\\G"}"#);
assert_eq!(epic::item(&json), Err(ParseError::NotUtf8));
// Outside a string too.
assert_eq!(epic::item(&[b'{', 0xFF, b'}']), Err(ParseError::NotUtf8));
}
#[test]
fn bytes_outside_strings_are_refused_too() {
assert_eq!(vdf::tokenize(&[0xFF]), Err(ParseError::NotUtf8));
assert_eq!(vdf::tokenize(&[&b"\"a\" \"b\" // comment "[..], &[0xFF]].concat()), Err(ParseError::NotUtf8));
}
// ---- NUL and control bytes --------------------------------------------------------------------------------
#[test]
fn nul_bytes_are_refused() {
assert_eq!(vdf::tokenize(b"\"a\0b\" \"c\""), Err(ParseError::Syntax { at: 2 }));
assert_eq!(vdf::tokenize(b"\"a\" \0 \"c\""), Err(ParseError::Syntax { at: 4 }));
assert!(matches!(epic::item(b"{\"AppName\":\"A\0\"}"), Err(ParseError::Syntax { .. })));
let json = br#"{"AppName":"A","DisplayName":"x\u0000y","InstallLocation":"C:\\G"}"#;
assert_eq!(epic::item(json), Err(ParseError::BadValue("DisplayName")));
let json = br#"{"AppName":"A","DisplayName":"x","InstallLocation":"C:\\G\u0000"}"#;
assert_eq!(epic::item(json), Err(ParseError::BadPath("InstallLocation")));
}
#[test]
fn raw_control_characters_in_vdf_strings_are_refused() {
for b in [0x01u8, 0x07, 0x0A, 0x0D, 0x1B, 0x7F] {
let input = [b'"', b'a', b, b'"'];
assert_eq!(vdf::tokenize(&input), Err(ParseError::Syntax { at: 2 }), "{b:#x}");
}
assert!(vdf::tokenize(b"\"a\tb\"").is_ok(), "a raw tab is allowed");
}
// ---- unterminated -----------------------------------------------------------------------------------------
#[test]
fn unterminated_strings_and_objects() {
assert_eq!(vdf::tokenize(b"\"abc"), Err(ParseError::Syntax { at: 0 }));
assert_eq!(vdf::tokenize(b"\"a\" \"b"), Err(ParseError::Syntax { at: 4 }));
assert!(matches!(vdf::parse(b"\"a\" { \"b\" \"c\""), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(br#"{"AppName":"A"#), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(b"{"), Err(ParseError::Syntax { .. })));
assert!(matches!(epic::item(b""), Err(ParseError::Syntax { .. })));
}
// ---- duplicates -------------------------------------------------------------------------------------------
#[test]
fn duplicate_keys_and_ids() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib());
assert_eq!(r, Err(ParseError::Duplicate("key")));
let r =
steam::library_folders(b"\"libraryfolders\" { \"0\" { \"path\" \"C:\\\\A\" } \"0\" { \"path\" \"C:\\\\B\" } }");
assert_eq!(r, Err(ParseError::Duplicate("key")));
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf"));
assert_eq!(r, Err(ParseError::Duplicate("path")));
assert_eq!(epic::item(include_bytes!("fixtures/epic/dupkey.item")), Err(ParseError::Duplicate("AppName")));
let json = br#"{"AppName":"A","DisplayName":"x","DisplayName":"y","InstallLocation":"C:\\G"}"#;
assert_eq!(epic::item(json), Err(ParseError::Duplicate("DisplayName")));
}
// ---- caps on lengths, counts, escapes ---------------------------------------------------------------------
#[test]
fn long_keys_and_values() {
let key = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY + 1));
assert_eq!(vdf::parse(key.as_bytes()), Err(ParseError::TooLong("key")));
let key_ok = format!("\"{}\" \"v\"", "k".repeat(MAX_KEY));
assert!(vdf::parse(key_ok.as_bytes()).is_ok());
let value = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE + 1));
assert_eq!(vdf::parse(value.as_bytes()), Err(ParseError::TooLong("value")));
assert_eq!(vdf::tokenize(value.as_bytes()), Err(ParseError::TooLong("value")));
let value_ok = format!("\"k\" \"{}\"", "v".repeat(MAX_VALUE));
assert!(vdf::parse(value_ok.as_bytes()).is_ok());
}
#[test]
fn too_many_escapes() {
let s = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES + 1));
assert_eq!(vdf::tokenize(s.as_bytes()), Err(ParseError::TooMany("escapes")));
let ok = format!("\"k\" \"{}\"", "\\\\".repeat(MAX_ESCAPES));
assert!(vdf::tokenize(ok.as_bytes()).is_ok());
}
#[test]
fn too_many_entries() {
let mut s = String::from("\"root\" {\n");
for i in 0..MAX_ENTRIES {
s.push_str(&format!("\"{i}\" \"\"\n"));
}
s.push_str("}\n");
assert!(s.len() <= MAX_FILE, "the test document must fit the file cap");
assert_eq!(vdf::parse(s.as_bytes()), Err(ParseError::TooMany("entries")));
}
#[test]
fn absurd_numbers() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib());
assert_eq!(r, Err(ParseError::BadId));
let r = epic::item(include_bytes!("fixtures/epic/absurd.item"));
assert!(r.is_err());
let e = GogEntry {
game_id: "9".repeat(10_000),
name: "G".into(),
path: r"C:\G".into(),
exe: r"C:\G\g.exe".into(),
working_dir: None,
launch_params: None,
};
assert_eq!(gog::game(&e), Err(ParseError::BadId));
}
#[test]
fn huge_strings_into_value_builders() {
let huge = "a".repeat(10 * MAX_FILE);
assert!(manual::game(&huge, None).is_err());
assert!(manual::game(r"C:\G\g.exe", Some(&huge)).is_err());
assert!(WinPath::parse(&huge).is_err());
assert!(huge.parse::<arena_core::GameId>().is_err());
}
// ---- never panics -----------------------------------------------------------------------------------------
#[test]
fn every_truncation_of_every_fixture() {
for f in FIXTURES {
for end in 0..=f.len() {
all_parsers(&f[..end]);
}
}
}
#[test]
fn every_single_byte_corruption_of_every_fixture() {
let replacements = [0x00u8, b'"', b'\\', b'{', b'}', b'[', b']', b':', b',', 0xFF, 0xC3, b'\n'];
for f in FIXTURES {
for i in 0..f.len() {
for &r in &replacements {
let mut m = f.to_vec();
m[i] = r;
all_parsers(&m);
}
}
}
}
+222
View File
@@ -0,0 +1,222 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Launch strings contain only parsed, validated fields: nothing raw from a file reaches a URI or an argument.
use arena_core::gog::GogEntry;
use arena_core::{Launch, ParseError, WinPath, epic, gog, limits, steam};
use proptest::prelude::*;
fn is_epic_app(s: &str) -> bool {
!s.is_empty()
&& s.len() <= limits::MAX_EPIC_APP
&& s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
fn is_domi_id(s: &str) -> bool {
!s.is_empty()
&& s.len() <= limits::MAX_DOMI_ID
&& !s.starts_with('-')
&& !s.ends_with('-')
&& s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
/// The URI is exactly the template filled with the field, and the field passes its rule.
fn check_uri(l: &Launch) {
let uri = l.uri();
match l {
Launch::SteamRunGameId(id) => {
assert_eq!(uri, (*id != 0).then(|| format!("steam://rungameid/{id}")));
}
Launch::Epic { app_name } => {
let want = is_epic_app(app_name)
.then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true"));
assert_eq!(uri, want, "{app_name:?}");
}
Launch::DomiLink { app } => {
assert_eq!(uri, is_domi_id(app).then(|| format!("domi-{app}://open")), "{app:?}");
}
Launch::Exe { .. } => assert_eq!(uri, None),
Launch::Url(u) => {
if let Some(got) = &uri {
assert_eq!(got, u);
assert!(got.starts_with("https://"));
assert!(got.bytes().all(|b| b.is_ascii_graphic() && b != b'\\' && b != b'"'), "{got:?}");
}
}
}
}
#[test]
fn fixture_uris_are_templates_of_parsed_fields() {
let lib = WinPath::parse(r"D:\SteamLibrary").unwrap();
let s = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib).unwrap();
check_uri(&s.launch);
assert_eq!(s.launch.uri().unwrap(), "steam://rungameid/1234560");
let e = epic::item(include_bytes!("fixtures/epic/valid.item")).unwrap();
check_uri(&e.launch);
assert_eq!(e.launch.uri().unwrap(), "com.epicgames.launcher://apps/ExampleRacer_Main-01?action=launch&silent=true");
}
#[test]
fn hand_built_bad_values_give_no_uri() {
let bad = [
Launch::SteamRunGameId(0),
Launch::Epic { app_name: String::new() },
Launch::Epic { app_name: "Fortnite?action=uninstall".into() },
Launch::Epic { app_name: "a/../../b".into() },
Launch::Epic { app_name: "a b".into() },
Launch::Epic { app_name: "a".repeat(65) },
Launch::DomiLink { app: "Lapilli".into() },
Launch::DomiLink { app: "x://evil".into() },
Launch::DomiLink { app: "-x".into() },
Launch::Url("javascript:alert(1)".into()),
Launch::Url("http://example.org/".into()),
Launch::Url("https://example.org/a b".into()),
Launch::Url("https://user@example.org/".into()),
Launch::Url("file:///C:/Windows/System32/calc.exe".into()),
];
for l in &bad {
assert_eq!(l.uri(), None, "{l:?}");
assert_eq!(l.uri_checked(&["example.org"]), None, "{l:?}");
check_uri(l);
}
let exe = Launch::Exe {
exe: WinPath::parse(r"C:\G\g.exe").unwrap(),
working_dir: WinPath::parse(r"C:\G").unwrap(),
args: vec![],
};
assert_eq!(exe.uri(), None);
}
#[test]
fn url_needs_allowed_host_when_checked() {
let l = Launch::web("https://games.example.org/x", &["games.example.org"]).unwrap();
assert_eq!(l.uri_checked(&["GAMES.example.org"]).as_deref(), Some("https://games.example.org/x"));
assert_eq!(l.uri_checked(&[]), None);
assert_eq!(Launch::web("https://games.example.org/x", &[]), Err(ParseError::BadValue("url")));
}
#[test]
fn builders_validate() {
assert_eq!(Launch::steam(0), Err(ParseError::BadId));
assert_eq!(Launch::steam(10).unwrap(), Launch::SteamRunGameId(10));
assert_eq!(Launch::epic("a?b"), Err(ParseError::BadId));
assert_eq!(Launch::domi_link("A"), Err(ParseError::BadId));
let exe = WinPath::parse(r"C:\G\g.exe").unwrap();
let dir = WinPath::parse(r"C:\G").unwrap();
assert_eq!(
Launch::exe(WinPath::parse(r"C:\G\g.bat").unwrap(), dir.clone(), vec![]),
Err(ParseError::BadPath("exe"))
);
assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\u{0}".into()]), Err(ParseError::BadValue("args")));
assert_eq!(Launch::exe(exe.clone(), dir.clone(), vec!["a\nb".into()]), Err(ParseError::BadValue("args")));
assert_eq!(
Launch::exe(exe.clone(), dir.clone(), vec!["x".repeat(limits::MAX_ARG + 1)]),
Err(ParseError::TooLong("arg"))
);
assert_eq!(
Launch::exe(exe.clone(), dir.clone(), vec![String::new(); limits::MAX_ARGS + 1]),
Err(ParseError::TooMany("args"))
);
assert!(Launch::exe(exe, dir, vec!["--fine".into(), "with space".into()]).is_ok());
}
#[test]
fn gog_args_are_exactly_the_split_params() {
let e = GogEntry {
game_id: "1".into(),
name: "G".into(),
path: r"C:\G".into(),
exe: r"C:\G\g.exe".into(),
working_dir: None,
launch_params: Some(r#" -a "b c" d"#.into()),
};
let g = gog::game(&e).unwrap();
match g.launch {
Launch::Exe { args, .. } => assert_eq!(args, ["-a", "b c", "d"]),
other => panic!("{other:?}"),
}
}
#[test]
fn deserialising_validates_every_field() {
let good = r#"{"epic":{"app_name":"Fortnite"}}"#;
assert_eq!(serde_json::from_str::<Launch>(good).unwrap(), Launch::Epic { app_name: "Fortnite".into() });
for bad in [
r#"{"epic":{"app_name":"a?b"}}"#,
r#"{"steam_run_game_id":0}"#,
r#"{"steam_run_game_id":4294967296}"#,
r#"{"domi_link":{"app":"X"}}"#,
r#"{"url":"http://example.org/"}"#,
r#"{"exe":{"exe":"C:\\G\\g.bat","working_dir":"C:\\G","args":[]}}"#,
r#"{"exe":{"exe":"C:\\G\\..\\g.exe","working_dir":"C:\\G","args":[]}}"#,
r#"{"exe":{"exe":"C:\\G\\g.exe","working_dir":"C:\\G","args":["a\u0000"]}}"#,
] {
assert!(serde_json::from_str::<Launch>(bad).is_err(), "{bad}");
}
}
#[test]
fn serde_round_trip() {
let all = [
Launch::steam(10).unwrap(),
Launch::epic("A_b-1").unwrap(),
Launch::domi_link("lapilli").unwrap(),
Launch::web("https://games.example.org/p?q=1", &["games.example.org"]).unwrap(),
Launch::exe(WinPath::parse(r"C:\G\g.exe").unwrap(), WinPath::parse(r"C:\G").unwrap(), vec!["-x".into()])
.unwrap(),
];
for l in all {
let json = serde_json::to_string(&l).unwrap();
assert_eq!(serde_json::from_str::<Launch>(&json).unwrap(), l, "{json}");
}
}
proptest! {
#[test]
fn epic_uri_only_from_valid_names(name in ".{0,80}") {
let l = Launch::Epic { app_name: name.clone() };
check_uri(&l);
prop_assert_eq!(Launch::epic(&name).is_ok(), is_epic_app(&name));
}
#[test]
fn epic_uri_from_generated_valid_names(name in "[A-Za-z0-9_-]{1,64}") {
let l = Launch::epic(&name).unwrap();
prop_assert_eq!(l.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true"));
}
#[test]
fn domi_uri_only_from_valid_ids(app in ".{0,40}") {
check_uri(&Launch::DomiLink { app });
}
#[test]
fn steam_uri_any_id(id in any::<u32>()) {
check_uri(&Launch::SteamRunGameId(id));
}
#[test]
fn url_uri_never_escapes_the_rules(url in "(https?://)?[a-zA-Z0-9.:@/?#%&=_ \\\\\"-]{0,60}") {
let l = Launch::Url(url);
check_uri(&l);
}
#[test]
fn epic_manifest_app_name_reaches_uri_only_when_valid(name in "[ -~]{0,70}") {
let json = serde_json::json!({"AppName": name, "DisplayName": "x", "InstallLocation": "C:\\G"}).to_string();
match epic::item(json.as_bytes()) {
Ok(g) => {
prop_assert!(is_epic_app(&name));
prop_assert_eq!(g.launch.uri().unwrap(), format!("com.epicgames.launcher://apps/{name}?action=launch&silent=true"));
}
Err(e) => {
prop_assert!(!is_epic_app(&name));
prop_assert_eq!(e, ParseError::BadId);
}
}
}
}
+136
View File
@@ -0,0 +1,136 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Manual games (an `.exe` the user picked) and Domi games (Atrium registry entries).
use arena_core::{CoverHint, DomiLaunch, Launch, ParseError, Source, WinPath, domi, limits, manual};
#[test]
fn manual_game() {
let g = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap();
assert_eq!(g.source, Source::Manual);
assert_eq!(g.title, "OldThing");
assert!(g.id.as_str().starts_with("manual:"));
assert_eq!(g.id.native().len(), 16);
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\Games\Old Thing"));
match &g.launch {
Launch::Exe { exe, working_dir, args } => {
assert_eq!(exe.as_str(), r"D:\Games\Old Thing\OldThing.exe");
assert_eq!(working_dir.as_str(), r"D:\Games\Old Thing");
assert!(args.is_empty());
}
other => panic!("{other:?}"),
}
assert!(matches!(g.cover, Some(CoverHint::Lettered { letter: 'O', hue }) if hue < 360));
}
#[test]
fn manual_id_is_stable_and_ignores_case_and_slashes() {
let a = manual::game(r"D:\Games\Old Thing\OldThing.exe", None).unwrap();
let b = manual::game("d:/games/old thing/OLDTHING.EXE", Some("Renamed")).unwrap();
assert_eq!(a.id, b.id);
assert_eq!(b.title, "Renamed");
let c = manual::game(r"D:\Games\Other\OldThing.exe", None).unwrap();
assert_ne!(a.id, c.id);
}
#[test]
fn manual_refuses_bad_exe() {
for bad in [
r"OldThing.exe",
r"\\server\share\x.exe",
r"\\?\C:\x.exe",
r"\\.\C:\x.exe",
r"C:\Games\..\Windows\x.exe",
r"C:\Games\run.bat",
r"C:\Games\run.cmd",
r"C:\",
r"C:\Games\CON.exe",
"C:\\Games\\x\u{0}.exe",
"",
] {
assert_eq!(manual::game(bad, None), Err(ParseError::BadPath("exe")), "{bad:?}");
}
}
#[test]
fn manual_refuses_bad_title() {
assert_eq!(manual::game(r"C:\G\x.exe", Some(" ")), Err(ParseError::Missing("title")));
assert_eq!(manual::game(r"C:\G\x.exe", Some("a\u{0}b")), Err(ParseError::BadValue("title")));
}
#[test]
fn domi_link_game() {
let g = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap();
assert_eq!(g.id.as_str(), "domi:lapilli");
assert_eq!(g.source, Source::Domi);
assert_eq!(g.title, "Lapilli");
assert_eq!(g.install_dir, None);
assert_eq!(g.launch, Launch::DomiLink { app: "lapilli".into() });
assert_eq!(g.launch.uri().as_deref(), Some("domi-lapilli://open"));
}
#[test]
fn domi_web_game() {
let hosts = ["rosea.example.org", "moin.example.org"];
let g = domi::game(
"rosea",
"Rosea",
DomiLaunch::Web { url: "HTTPS://Rosea.Example.org/play?x=1#top", allowed_hosts: &hosts },
)
.unwrap();
assert_eq!(g.launch, Launch::Url("https://rosea.example.org/play?x=1#top".into()));
assert_eq!(g.launch.uri().as_deref(), Some("https://rosea.example.org/play?x=1#top"));
assert_eq!(g.launch.uri_checked(&hosts).as_deref(), Some("https://rosea.example.org/play?x=1#top"));
assert_eq!(g.launch.uri_checked(&["other.example.org"]), None);
}
#[test]
fn domi_refuses_bad_ids() {
let long = "a".repeat(limits::MAX_DOMI_ID + 1);
for bad in ["", "-x", "x-", "X", "a_b", "a.b", "a b", "ä", long.as_str()] {
assert_eq!(domi::game(bad, "N", DomiLaunch::Link { app: "ok" }), Err(ParseError::BadId), "{bad:?}");
assert_eq!(domi::game("ok", "N", DomiLaunch::Link { app: bad }), Err(ParseError::BadId), "{bad:?}");
}
assert!(domi::game(&"a".repeat(limits::MAX_DOMI_ID), "N", DomiLaunch::Link { app: "a-1" }).is_ok());
}
#[test]
fn domi_refuses_bad_urls() {
let hosts = ["rosea.example.org"];
let long = format!("https://rosea.example.org/{}", "a".repeat(limits::MAX_URL));
for bad in [
"http://rosea.example.org/",
"javascript:alert(1)",
"file:///C:/Windows/System32/calc.exe",
"https://evil.example.org/",
"https://rosea.example.org.evil.example/",
"https://sub.rosea.example.org/",
"https://user@rosea.example.org/",
"https://rosea.example.org:8443/",
"https://rosea.example.org/a b",
"https://rosea.example.org/a\\b",
"https://rosea.example.org/\u{0}",
"https://rosea.example.org/%zz",
"https://rosea.example.org/\"quote",
"https:///path",
"https://",
" https://rosea.example.org/",
"https://[::1]/",
"https://rosea..example.org/",
"https://-rosea.example.org/",
long.as_str(),
] {
let r = domi::game("rosea", "Rosea", DomiLaunch::Web { url: bad, allowed_hosts: &hosts });
assert!(matches!(r, Err(ParseError::BadValue("url")) | Err(ParseError::TooLong("url"))), "{bad:?}: {r:?}");
}
}
#[test]
fn domi_web_host_without_path() {
let hosts = ["moin.example.org"];
let g =
domi::game("moin", "Moin", DomiLaunch::Web { url: "https://moin.example.org", allowed_hosts: &hosts }).unwrap();
assert_eq!(g.launch.uri().as_deref(), Some("https://moin.example.org"));
}
+153
View File
@@ -0,0 +1,153 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Dedupe and ordering in `merge`.
use arena_core::{CoverHint, DomiLaunch, Game, GameId, Launch, Library, Source, WinPath, domi, gog, manual, merge};
fn game(source: Source, native: &str, title: &str, dir: Option<&str>) -> Game {
let id = GameId::new(source, native).unwrap();
let launch = match source {
Source::Steam => Launch::steam(native.parse().unwrap()).unwrap(),
Source::Epic => Launch::epic(native).unwrap(),
Source::Domi => Launch::domi_link(native).unwrap(),
_ => {
let d = WinPath::parse(dir.unwrap()).unwrap();
Launch::exe(d.join("g.exe").unwrap(), d, vec![]).unwrap()
}
};
Game {
cover: Some(CoverHint::lettered(title, &id)),
id,
source,
title: title.into(),
install_dir: dir.map(|d| WinPath::parse(d).unwrap()),
launch,
}
}
fn ids(lib: &Library) -> Vec<&str> {
lib.games.iter().map(|g| g.id.as_str()).collect()
}
#[test]
fn same_id_kept_once_first_wins() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let mut a2 = a.clone();
a2.title = "Alpha (again)".into();
let lib = merge(vec![vec![a.clone(), a2.clone()], vec![a2]]);
assert_eq!(lib.len(), 1);
assert_eq!(lib.games[0].title, "Alpha");
}
#[test]
fn same_install_dir_keeps_the_best_source() {
let dir = r"C:\Games\Shared";
let steam = game(Source::Steam, "10", "Shared S", Some(dir));
let epic = game(Source::Epic, "shared", "Shared E", Some(r"c:\games\SHARED"));
let gog = game(Source::Gog, "20", "Shared G", Some(dir));
let man = game(Source::Manual, "0123456789abcdef", "Shared M", Some(dir));
let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()], vec![steam.clone()]]);
assert_eq!(ids(&lib), ["steam:10"]);
let lib = merge(vec![vec![man.clone()], vec![gog.clone()], vec![epic.clone()]]);
assert_eq!(ids(&lib), ["epic:shared"]);
let lib = merge(vec![vec![man.clone(), gog.clone()]]);
assert_eq!(ids(&lib), ["gog:20"]);
}
#[test]
fn domi_beats_manual_on_the_same_folder() {
let dir = r"C:\Domi\Lapilli";
let mut d = domi::game("lapilli", "Lapilli", DomiLaunch::Link { app: "lapilli" }).unwrap();
d.install_dir = Some(WinPath::parse(dir).unwrap());
let m = manual::game(r"C:\Domi\Lapilli\lapilli.exe", None).unwrap();
let lib = merge(vec![vec![m], vec![d]]);
assert_eq!(ids(&lib), ["domi:lapilli"]);
}
#[test]
fn same_source_same_folder_keeps_both() {
let a = game(Source::Steam, "10", "A", Some(r"D:\S\common\X"));
let b = game(Source::Steam, "11", "B", Some(r"D:\S\common\X"));
let lib = merge(vec![vec![a, b]]);
assert_eq!(ids(&lib), ["steam:10", "steam:11"]);
}
#[test]
fn no_install_dir_never_dedupes_by_folder() {
let a = domi::game("rosea", "Rosea", DomiLaunch::Link { app: "rosea" }).unwrap();
let b = domi::game("moin", "Moin", DomiLaunch::Link { app: "moin" }).unwrap();
let lib = merge(vec![vec![a], vec![b]]);
assert_eq!(ids(&lib), ["domi:moin", "domi:rosea"]);
}
#[test]
fn different_folders_are_different_games() {
let a = game(Source::Steam, "10", "Same Title", Some(r"D:\S\common\X"));
let b = game(Source::Gog, "20", "Same Title", Some(r"C:\GOG Games\X"));
let lib = merge(vec![vec![a], vec![b]]);
assert_eq!(lib.len(), 2);
}
#[test]
fn ordered_by_title_ignoring_case_then_id_and_independent_of_scan_order() {
let games = vec![
game(Source::Steam, "30", "zeta", Some(r"D:\z")),
game(Source::Epic, "b", "Beta", Some(r"D:\b")),
game(Source::Gog, "1", "alpha", Some(r"D:\a1")),
game(Source::Steam, "2", "Alpha", Some(r"D:\a2")),
game(Source::Manual, "0123456789abcdef", "Ärger", Some(r"D:\ae")),
];
let forward = merge(vec![games.clone()]);
let mut rev = games.clone();
rev.reverse();
let backward = merge(vec![rev.into_iter().map(|g| vec![g]).collect::<Vec<_>>().concat()]);
assert_eq!(forward, backward);
assert_eq!(ids(&forward), ["gog:1", "steam:2", "epic:b", "steam:30", "manual:0123456789abcdef"]);
}
#[test]
fn library_lookup() {
let g = gog::game(&gog::GogEntry {
game_id: "5".into(),
name: "Five".into(),
path: r"C:\G5".into(),
exe: r"C:\G5\five.exe".into(),
working_dir: None,
launch_params: None,
})
.unwrap();
let lib = merge(vec![vec![g.clone()]]);
assert_eq!(lib.get(&"gog:5".parse().unwrap()), Some(&g));
assert_eq!(lib.get(&"gog:6".parse().unwrap()), None);
assert!(merge(vec![]).is_empty());
}
#[test]
fn library_json_round_trip() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let b = domi::game(
"rosea",
"Rosea",
DomiLaunch::Web { url: "https://rosea.example.org/", allowed_hosts: &["rosea.example.org"] },
)
.unwrap();
let lib = merge(vec![vec![a, b]]);
let json = serde_json::to_string(&lib).unwrap();
let back: Library = serde_json::from_str(&json).unwrap();
assert_eq!(back, lib);
}
#[test]
fn library_json_refuses_mismatched_or_bad_games() {
let a = game(Source::Steam, "10", "Alpha", Some(r"D:\S\common\Alpha"));
let json = serde_json::to_string(&Library { games: vec![a] }).unwrap();
let wrong_source = json.replace(r#""source":"steam""#, r#""source":"epic""#);
assert!(serde_json::from_str::<Library>(&wrong_source).is_err());
let bad_title = json.replace(r#""title":"Alpha""#, r#""title":"\u0000""#);
assert!(serde_json::from_str::<Library>(&bad_title).is_err());
let bad_path = json.replace(r#"D:\\S\\common\\Alpha"#, r#"D:\\S\\..\\Alpha"#);
assert!(serde_json::from_str::<Library>(&bad_path).is_err());
}
+250
View File
@@ -0,0 +1,250 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! `WinPath` and `GameId`: the two validated value types everything else is built from.
use arena_core::{GameId, ParseError, Source, WinPath, limits};
use proptest::prelude::*;
proptest! {
#[test]
fn winpath_never_panics_and_normal_form_is_stable(s in r"([A-Za-z]:)?[\\/a-zA-Z0-9 .:<>|?*\x00-\x1f¹~$-]{0,40}") {
if let Ok(p) = WinPath::parse(&s) {
let again = WinPath::parse(p.as_str()).unwrap();
prop_assert_eq!(&again, &p);
prop_assert!(p.components().all(|c| c != ".." && c != "." && !c.contains('\0')));
prop_assert!(!p.as_str().contains('/'));
prop_assert!(p.as_str().get(1..3) == Some(":\\"));
if let Some(parent) = p.parent() {
prop_assert!(p.starts_with(&parent));
}
}
}
#[test]
fn winpath_join_never_climbs_out(rel in r"[a-zA-Z.\\/]{0,20}") {
let base = WinPath::parse(r"C:\Games\X").unwrap();
if let Ok(j) = base.join(&rel) {
prop_assert!(j.starts_with(&base));
}
}
#[test]
fn game_id_round_trips_or_refuses(s in r"[a-z]{0,7}:?[a-zA-Z0-9:._ -]{0,20}") {
if let Ok(id) = s.parse::<GameId>() {
prop_assert_eq!(id.to_string(), s.clone());
prop_assert!(s.len() <= limits::MAX_GAME_ID);
prop_assert!(s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b":._-".contains(&b)));
}
}
}
#[test]
fn errors_display_without_input_text() {
let all = [
ParseError::TooLarge,
ParseError::TooDeep,
ParseError::NotUtf8,
ParseError::Syntax { at: 7 },
ParseError::Missing("name"),
ParseError::WrongType("appid"),
ParseError::BadPath("installdir"),
ParseError::BadId,
ParseError::Duplicate("key"),
ParseError::TooLong("value"),
ParseError::TooMany("entries"),
ParseError::BadValue("url"),
ParseError::NotAGame("Epic add-on"),
];
for e in all {
let text = e.to_string();
assert!(!text.is_empty());
let as_error: &dyn std::error::Error = &e;
assert_eq!(as_error.to_string(), text);
}
assert_eq!(ParseError::Syntax { at: 7 }.to_string(), "syntax error at byte 7");
}
fn p(s: &str) -> WinPath {
WinPath::parse(s).unwrap()
}
#[test]
fn winpath_accepts_and_normalises() {
assert_eq!(p(r"C:\Games\X").as_str(), r"C:\Games\X");
assert_eq!(p(r"c:\Games\X\").as_str(), r"C:\Games\X");
assert_eq!(p("d:/Games//X/").as_str(), r"D:\Games\X");
assert_eq!(p(r"C:\").as_str(), r"C:\");
assert_eq!(p("C:/").as_str(), r"C:\");
assert_eq!(p(r"C:\Program Files (x86)\Steam").as_str(), r"C:\Program Files (x86)\Steam");
assert_eq!(p(r"C:\Hry\Příliš žluťoučký kůň").as_str(), r"C:\Hry\Příliš žluťoučký kůň");
assert_eq!(p(r"C:\a.b\.hidden\x..y").as_str(), r"C:\a.b\.hidden\x..y");
assert_eq!(p(r"C:\CONSOLE\NULL\COM10\LPT").as_str(), r"C:\CONSOLE\NULL\COM10\LPT");
}
#[test]
fn winpath_refuses() {
let long = format!(r"C:\{}", "a".repeat(limits::MAX_PATH));
for bad in [
"",
"C:",
"C:Games",
r"\Games",
"Games",
r"1:\x",
r"\\server\share",
r"\\?\C:\x",
r"\\.\C:\x",
r"\??\C:\x",
"//server/share",
r"C:\..",
r"C:\Games\..\Windows",
r"C:\Games\.\x",
"C:\\Games\\x\u{0}",
"C:\\Games\\x\ny",
"C:\\Games\\x\u{1f}",
r"C:\Games\x:stream",
r"C:\Games\a*b",
r"C:\Games\a?b",
r#"C:\Games\a"b"#,
r"C:\Games\a<b",
r"C:\Games\a>b",
r"C:\Games\a|b",
r"C:\CON",
r"C:\con.txt",
r"C:\Games\nul",
r"C:\Games\Aux.log",
r"C:\Games\prn",
r"C:\Games\COM1",
r"C:\Games\lpt9.dat",
r"C:\Games\COM¹",
r"C:\Games\CONIN$",
r"C:\Games\conout$",
r"C:\Games\NUL .txt",
r"C:\Games\trailing.",
r"C:\Games\trailing ",
long.as_str(),
] {
assert!(matches!(WinPath::parse(bad), Err(ParseError::BadPath(_))), "{bad:?}");
}
}
#[test]
fn winpath_length_counts_utf16_units() {
let ok = format!(r"C:\{}", "a".repeat(limits::MAX_PATH - 3));
assert!(WinPath::parse(&ok).is_ok());
// One astral character is two UTF-16 units.
let astral = format!(r"C:\{}😀", "a".repeat(limits::MAX_PATH - 4));
assert!(WinPath::parse(&astral).is_err());
}
#[test]
fn winpath_join_parent_file_name() {
let base = p(r"C:\Games");
assert_eq!(base.join(r"A\b.exe").unwrap().as_str(), r"C:\Games\A\b.exe");
assert_eq!(base.join("A/b.exe").unwrap().as_str(), r"C:\Games\A\b.exe");
for bad in ["", r"..\x", r"A\..\..\x", r"\x", r"D:\x", "D:x", r"\\s\x", "a\u{0}"] {
assert!(base.join(bad).is_err(), "{bad:?}");
}
assert_eq!(p(r"C:\Games\A").parent(), Some(p(r"C:\Games")));
assert_eq!(p(r"C:\Games").parent(), Some(p(r"C:\")));
assert_eq!(p(r"C:\").parent(), None);
assert_eq!(p(r"C:\Games\b.exe").file_name(), Some("b.exe"));
assert_eq!(p(r"C:\").file_name(), None);
assert_eq!(p(r"C:\a\b").components().collect::<Vec<_>>(), ["a", "b"]);
}
#[test]
fn winpath_join_respects_length() {
let base = p(r"C:\Games");
assert!(base.join(&"a".repeat(limits::MAX_PATH)).is_err());
}
#[test]
fn winpath_compare_ignoring_case() {
assert!(p(r"C:\Games\X").eq_ignore_case(&p(r"c:\GAMES\x")));
assert!(p(r"C:\Games\X\bin\x.exe").starts_with(&p(r"c:\games\x")));
assert!(p(r"C:\Games\X").starts_with(&p(r"C:\Games\X")));
assert!(p(r"C:\Games\X").starts_with(&p(r"C:\")));
assert!(!p(r"C:\Games\XY").starts_with(&p(r"C:\Games\X")));
assert!(!p(r"D:\Games\X").starts_with(&p(r"C:\Games")));
assert!(!p(r"C:\Games").starts_with(&p(r"C:\Games\X")));
}
#[test]
fn winpath_serde_validates() {
let ok: WinPath = serde_json::from_str(r#""C:\\Games""#).unwrap();
assert_eq!(ok.as_str(), r"C:\Games");
assert!(serde_json::from_str::<WinPath>(r#""C:\\Games\\..\\x""#).is_err());
assert_eq!(serde_json::to_string(&ok).unwrap(), r#""C:\\Games""#);
}
#[test]
fn game_id_round_trip() {
for s in ["steam:1234560", "epic:exampleracer_main-01", "gog:1207658924", "manual:0123456789abcdef", "domi:lapilli"]
{
let id: GameId = s.parse().unwrap();
assert_eq!(id.to_string(), s);
assert_eq!(id.source().as_str(), s.split(':').next().unwrap());
assert_eq!(id.native(), s.split_once(':').unwrap().1);
}
assert_eq!(GameId::new(Source::Steam, "10").unwrap().as_str(), "steam:10");
assert_eq!("epic:a".parse::<GameId>().unwrap().source(), Source::Epic);
}
#[test]
fn game_id_refuses() {
let long = format!("epic:{}", "a".repeat(limits::MAX_GAME_ID));
for bad in [
"",
"steam",
"steam:",
":10",
"Steam:10",
"steam:0",
"steam:01",
"steam:4294967296",
"steam:-1",
"steam:1a",
"xbox:10",
"epic:A",
"epic:a.b",
"epic:a:b",
"gog:abc",
"gog:123456789012345678901",
"manual:0123",
"manual:0123456789ABCDEF",
"manual:0123456789abcdeg",
"domi:-x",
"domi:a_b",
"domi:../x",
"steam:10 ",
" steam:10",
"steam:10\u{0}",
long.as_str(),
] {
assert_eq!(bad.parse::<GameId>(), Err(ParseError::BadId), "{bad:?}");
}
assert_eq!(GameId::new(Source::Gog, "x"), Err(ParseError::BadId));
}
#[test]
fn game_id_serde_validates() {
let id: GameId = serde_json::from_str(r#""steam:10""#).unwrap();
assert_eq!(serde_json::to_string(&id).unwrap(), r#""steam:10""#);
assert!(serde_json::from_str::<GameId>(r#""steam:../x""#).is_err());
}
#[test]
fn source_names() {
for s in Source::ALL {
assert_eq!(s.as_str().parse::<Source>().unwrap(), s);
assert_eq!(s.to_string(), s.as_str());
}
assert!("Steam".parse::<Source>().is_err());
assert!(Source::Steam.priority() > Source::Epic.priority());
assert!(Source::Epic.priority() > Source::Gog.priority());
assert!(Source::Gog.priority() > Source::Domi.priority());
assert!(Source::Domi.priority() > Source::Manual.priority());
}
+181
View File
@@ -0,0 +1,181 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Steam: valid fixtures and the hostile ones that are Steam-specific.
use arena_core::{CoverHint, Launch, ParseError, Source, WinPath, steam};
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
#[test]
fn library_folders_current_layout() {
let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap();
let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect();
assert_eq!(dirs, [r"C:\Program Files (x86)\Steam", r"D:\SteamLibrary"]);
}
#[test]
fn library_folders_old_layout() {
let dirs = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_old.vdf")).unwrap();
let dirs: Vec<&str> = dirs.iter().map(WinPath::as_str).collect();
assert_eq!(dirs, [r"D:\SteamLibrary", r"E:\Games\Steam"]);
}
#[test]
fn library_folders_empty_root_is_empty_list() {
assert_eq!(steam::library_folders(b"\"libraryfolders\"\n{\n}\n").unwrap(), Vec::<WinPath>::new());
}
#[test]
fn library_folders_needs_the_root_key() {
assert_eq!(steam::library_folders(b"\"other\" { }"), Err(ParseError::Missing("libraryfolders")));
assert_eq!(steam::library_folders(b"\"libraryfolders\" \"x\""), Err(ParseError::WrongType("libraryfolders")));
}
#[test]
fn library_folders_refuses_path_object() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_wrongtype.vdf"));
assert_eq!(r, Err(ParseError::WrongType("path")));
}
#[test]
fn library_folders_refuses_missing_path() {
let r = steam::library_folders(b"\"libraryfolders\" { \"0\" { \"label\" \"\" } }");
assert_eq!(r, Err(ParseError::Missing("path")));
}
#[test]
fn library_folders_refuses_unc() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_unc.vdf"));
assert_eq!(r, Err(ParseError::BadPath("path")));
}
#[test]
fn library_folders_refuses_the_same_folder_twice() {
let r = steam::library_folders(include_bytes!("fixtures/steam/libraryfolders_dup.vdf"));
assert_eq!(r, Err(ParseError::Duplicate("path")));
}
#[test]
fn library_folders_caps_the_count() {
let mut s = String::from("\"libraryfolders\"\n{\n");
for i in 0..=arena_core::limits::MAX_LIBRARIES {
s.push_str(&format!("\"{i}\" {{ \"path\" \"D:\\\\Lib{i}\" }}\n"));
}
s.push_str("}\n");
assert_eq!(steam::library_folders(s.as_bytes()), Err(ParseError::TooMany("libraries")));
}
#[test]
fn app_manifest_valid() {
let g = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_1234560.acf"), &lib()).unwrap();
assert_eq!(g.id.as_str(), "steam:1234560");
assert_eq!(g.source, Source::Steam);
assert_eq!(g.title, "Example Quest: The \"Quoted\" Edition");
assert_eq!(g.install_dir.as_ref().map(WinPath::as_str), Some(r"D:\SteamLibrary\steamapps\common\Example Quest"));
assert_eq!(g.launch, Launch::SteamRunGameId(1_234_560));
assert_eq!(g.launch.uri().as_deref(), Some("steam://rungameid/1234560"));
assert_eq!(g.cover, Some(CoverHint::SteamLibraryCache { app_id: 1_234_560 }));
}
#[test]
fn app_manifest_redistributable_is_not_a_game() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_228980.acf"), &lib());
assert!(matches!(r, Err(ParseError::NotAGame(_))), "{r:?}");
assert!(steam::is_tool(228_980));
assert!(!steam::is_tool(1_234_560));
}
#[test]
fn app_manifest_refuses_traversal_in_installdir() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_traversal.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
}
#[test]
fn app_manifest_refuses_absolute_installdir() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absolute.acf"), &lib());
assert_eq!(r, Err(ParseError::BadPath("installdir")));
}
#[test]
fn app_manifest_refuses_appid_object() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_wrongtype.acf"), &lib());
assert_eq!(r, Err(ParseError::WrongType("appid")));
}
#[test]
fn app_manifest_refuses_duplicate_keys_ignoring_case() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_dupkey.acf"), &lib());
assert_eq!(r, Err(ParseError::Duplicate("key")));
}
#[test]
fn app_manifest_refuses_absurd_appid() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_absurd.acf"), &lib());
assert_eq!(r, Err(ParseError::BadId));
}
#[test]
fn app_manifest_refuses_line_break_in_string() {
let r = steam::app_manifest(include_bytes!("fixtures/steam/appmanifest_unterminated.acf"), &lib());
assert!(matches!(r, Err(ParseError::Syntax { .. })), "{r:?}");
}
#[test]
fn app_manifest_appid_rules() {
for bad in ["0", "-1", "+5", "01", " 5", "5 ", "4294967296", "1e3", "0x10", ""] {
let acf = format!("\"AppState\" {{ \"appid\" \"{bad}\" \"name\" \"N\" \"installdir\" \"N\" }}");
assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()), Err(ParseError::BadId), "appid {bad:?}");
}
let acf = "\"AppState\" { \"appid\" \"4294967295\" \"name\" \"N\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(acf.as_bytes(), &lib()).unwrap().launch, Launch::SteamRunGameId(u32::MAX));
}
#[test]
fn app_manifest_missing_fields() {
let no_name = "\"AppState\" { \"appid\" \"10\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(no_name.as_bytes(), &lib()), Err(ParseError::Missing("name")));
let no_dir = "\"AppState\" { \"appid\" \"10\" \"name\" \"N\" }";
assert_eq!(steam::app_manifest(no_dir.as_bytes(), &lib()), Err(ParseError::Missing("installdir")));
let no_id = "\"AppState\" { \"name\" \"N\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(no_id.as_bytes(), &lib()), Err(ParseError::Missing("appid")));
assert_eq!(steam::app_manifest(b"\"Other\" { }", &lib()), Err(ParseError::Missing("AppState")));
}
#[test]
fn app_manifest_refuses_blank_or_control_title() {
let blank = "\"AppState\" { \"appid\" \"10\" \"name\" \" \" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(blank.as_bytes(), &lib()), Err(ParseError::Missing("name")));
let ctl = "\"AppState\" { \"appid\" \"10\" \"name\" \"a\\tb\" \"installdir\" \"N\" }";
assert_eq!(steam::app_manifest(ctl.as_bytes(), &lib()), Err(ParseError::BadValue("name")));
}
#[test]
fn app_manifest_refuses_device_name_installdir() {
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:?}");
}
}
#[test]
fn manifest_names() {
assert_eq!(steam::app_id_from_manifest_name("appmanifest_1234560.acf"), Some(1_234_560));
for bad in [
"appmanifest_0.acf",
"appmanifest_01.acf",
"appmanifest_.acf",
"appmanifest_12.acf.bak",
"APPMANIFEST_12.ACF",
"appmanifest_99999999999.acf",
"appmanifest_-1.acf",
"libraryfolders.vdf",
"appmanifest_1 2.acf",
] {
assert_eq!(steam::app_id_from_manifest_name(bad), None, "{bad}");
}
}
+114
View File
@@ -0,0 +1,114 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! The VDF tokenizer, parser and writer on hand-written input.
use arena_core::ParseError;
use arena_core::vdf::{self, Obj, TokenKind, Value};
#[test]
fn tokens_and_offsets() {
let t = vdf::tokenize(b"\"a\" {\n\t\"b\\\\c\" \"d\\\"e\"\n}").unwrap();
let kinds: Vec<&TokenKind> = t.iter().map(|t| &t.kind).collect();
assert_eq!(
kinds,
[
&TokenKind::Str("a".into()),
&TokenKind::Open,
&TokenKind::Str("b\\c".into()),
&TokenKind::Str("d\"e".into()),
&TokenKind::Close
]
);
let at: Vec<usize> = t.iter().map(|t| t.at).collect();
assert_eq!(at, [0, 4, 7, 14, 21]);
}
#[test]
fn escapes() {
let t = vdf::tokenize(br#""\n\t\r\\\"""#).unwrap();
assert_eq!(t[0].kind, TokenKind::Str("\n\t\r\\\"".into()));
for bad in [&br#""\x""#[..], br#""\0""#, br#""\'""#, br#""\""#, b"\"\\"] {
assert!(matches!(vdf::tokenize(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn comments_and_whitespace() {
let doc = vdf::parse(b"// top\r\n\"a\" // after key\r\n{ \"b\" \"c\" } // end").unwrap();
let Some(Value::Obj(a)) = doc.get("A") else { panic!("{doc:?}") };
assert_eq!(a.get("b"), Some(&Value::Str("c".into())));
}
#[test]
fn refuses_unquoted_and_directives() {
for bad in [
&b"a { }"[..],
b"\"a\" b",
b"#include \"x.vdf\"",
b"#base \"x\"",
b"\"a\" \"b\" [$WIN32]",
b"/ x",
b"\"a\" { \"b\" \"c\" }}",
] {
assert!(matches!(vdf::parse(bad), Err(ParseError::Syntax { .. })), "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn structure_errors() {
assert!(matches!(vdf::parse(b"\"a\""), Err(ParseError::Syntax { .. })));
assert!(matches!(vdf::parse(b"\"a\" {"), Err(ParseError::Syntax { .. })));
assert!(matches!(vdf::parse(b"{ }"), Err(ParseError::Syntax { at: 0 })));
assert!(matches!(vdf::parse(b"\"a\" { { } }"), Err(ParseError::Syntax { .. })));
assert_eq!(vdf::parse(b"\"\" \"v\""), Err(ParseError::Missing("key")));
assert_eq!(vdf::parse(b"\"a\" \"1\" \"A\" \"2\""), Err(ParseError::Duplicate("key")));
assert!(vdf::parse(b"\"a\" { \"k\" \"1\" } \"b\" { \"k\" \"2\" }").is_ok(), "same key on different objects");
assert_eq!(vdf::parse(b"").unwrap(), Obj::new());
assert_eq!(vdf::parse(b" \n// only a comment").unwrap(), Obj::new());
}
#[test]
fn syntax_offset_is_where_the_problem_is() {
assert_eq!(vdf::parse(b"\"a\" \"b\"\n\"c\" x"), Err(ParseError::Syntax { at: 12 }));
assert_eq!(vdf::tokenize(b"\"ab\0\""), Err(ParseError::Syntax { at: 3 }));
}
#[test]
fn bom_only_at_the_start() {
assert!(vdf::parse(b"\xEF\xBB\xBF\"a\" \"b\"").is_ok());
assert!(vdf::parse(b"\"a\" \xEF\xBB\xBF\"b\"").is_err());
}
#[test]
fn obj_insert_rules() {
let mut o = Obj::new();
o.insert("Key".into(), Value::Str("v".into())).unwrap();
assert_eq!(o.insert("KEY".into(), Value::Str("w".into())), Err(ParseError::Duplicate("key")));
assert_eq!(o.insert(String::new(), Value::Str("w".into())), Err(ParseError::Missing("key")));
assert_eq!(o.insert("k".repeat(257), Value::Str("w".into())), Err(ParseError::TooLong("key")));
assert_eq!(o.insert("k2".into(), Value::Str("v".repeat(4097))), Err(ParseError::TooLong("value")));
assert_eq!(o.len(), 1);
assert_eq!(o.iter().next(), Some(("Key", &Value::Str("v".into()))));
}
#[test]
fn write_then_parse() {
let mut inner = Obj::new();
inner.insert("path".into(), Value::Str("C:\\Program Files (x86)\\Steam".into())).unwrap();
inner.insert("quote".into(), Value::Str("say \"hi\"\n\tbye".into())).unwrap();
let mut root = Obj::new();
root.insert("0".into(), Value::Obj(inner)).unwrap();
let mut doc = Obj::new();
doc.insert("libraryfolders".into(), Value::Obj(root)).unwrap();
let text = vdf::write(&doc);
assert!(text.contains(r#""path" "C:\\Program Files (x86)\\Steam""#), "{text}");
assert_eq!(vdf::parse(text.as_bytes()).unwrap(), doc);
}
#[test]
fn fixture_round_trips_through_the_writer() {
let doc = vdf::parse(include_bytes!("fixtures/steam/libraryfolders.vdf")).unwrap();
assert_eq!(vdf::parse(vdf::write(&doc).as_bytes()).unwrap(), doc);
}
+140
View File
@@ -0,0 +1,140 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Property tests on the VDF tokenizer and parser: no panics on arbitrary bytes, and generated documents survive
//! a write/parse round trip.
use arena_core::vdf::{self, Obj, TokenKind, Value};
use arena_core::{WinPath, epic, steam};
use proptest::prelude::*;
/// Strings the format can carry: anything printable plus the characters the writer must escape.
fn vdf_string(max: usize) -> impl Strategy<Value = String> {
proptest::collection::vec(
prop_oneof![
8 => proptest::char::range(' ', '~'),
2 => Just('"'),
2 => Just('\\'),
1 => Just('\n'),
1 => Just('\t'),
1 => Just('\r'),
1 => proptest::char::range('\u{a0}', '\u{2fff}'),
1 => proptest::char::range('\u{1f300}', '\u{1f64f}'),
],
0..max,
)
.prop_map(|cs| cs.into_iter().collect())
}
fn key() -> impl Strategy<Value = String> {
vdf_string(12).prop_filter("keys are not empty", |k| !k.is_empty())
}
#[derive(Debug, Clone)]
enum Gen {
Str(String),
Obj(Vec<(String, Gen)>),
}
fn gen_value() -> impl Strategy<Value = Gen> {
let leaf = vdf_string(24).prop_map(Gen::Str);
leaf.prop_recursive(6, 64, 6, |inner| proptest::collection::vec((key(), inner), 0..6).prop_map(Gen::Obj))
}
/// Builds an `Obj`, dropping keys that repeat (ignoring ASCII case) as the format requires.
fn build(pairs: Vec<(String, Gen)>) -> Obj {
let mut o = Obj::new();
for (k, v) in pairs {
let v = match v {
Gen::Str(s) => Value::Str(s),
Gen::Obj(p) => Value::Obj(build(p)),
};
let _ = o.insert(k, v);
}
o
}
fn gen_doc() -> impl Strategy<Value = Obj> {
proptest::collection::vec((key(), gen_value()), 0..6).prop_map(build)
}
fn lib() -> WinPath {
WinPath::parse(r"D:\SteamLibrary").unwrap()
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn tokenizer_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..2048)) {
let _ = vdf::tokenize(&bytes);
let _ = vdf::parse(&bytes);
let _ = steam::library_folders(&bytes);
let _ = steam::app_manifest(&bytes, &lib());
let _ = epic::item(&bytes);
}
#[test]
fn tokenizer_never_panics_on_vdf_like_bytes(
parts in proptest::collection::vec(
prop_oneof![
Just(&b"\""[..]), Just(&b"{"[..]), Just(&b"}"[..]), Just(&b"\\"[..]), Just(&b"//"[..]),
Just(&b"\n"[..]), Just(&b" "[..]), Just(&b"\\\""[..]), Just(&b"\\n"[..]), Just(&b"\0"[..]),
Just(&b"\xff"[..]), Just(&b"\xc3"[..]), Just(&b"key"[..]), Just(&b"\xEF\xBB\xBF"[..]),
Just(&b"\"AppState\""[..]), Just(&b"\"appid\""[..]), Just(&b"\"10\""[..]),
Just(&b"\"libraryfolders\""[..]), Just(&b"\"path\""[..]), Just(&b"\"C:\\\\G\""[..]),
],
0..200,
)
) {
let bytes: Vec<u8> = parts.concat();
let _ = vdf::tokenize(&bytes);
let _ = vdf::parse(&bytes);
let _ = steam::library_folders(&bytes);
let _ = steam::app_manifest(&bytes, &lib());
}
#[test]
fn tokens_carry_valid_offsets(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
if let Ok(tokens) = vdf::tokenize(&bytes) {
let mut last = None;
for t in &tokens {
prop_assert!(t.at < bytes.len());
prop_assert!(last.is_none_or(|l| l < t.at), "offsets increase");
last = Some(t.at);
let first = bytes[t.at];
match t.kind {
TokenKind::Open => prop_assert_eq!(first, b'{'),
TokenKind::Close => prop_assert_eq!(first, b'}'),
TokenKind::Str(_) => prop_assert_eq!(first, b'"'),
}
}
}
}
#[test]
fn syntax_errors_point_inside_the_input(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
if let Err(arena_core::ParseError::Syntax { at }) = vdf::parse(&bytes) {
prop_assert!(at <= bytes.len());
}
}
#[test]
fn generated_documents_round_trip(doc in gen_doc()) {
let text = vdf::write(&doc);
let back = vdf::parse(text.as_bytes());
prop_assert_eq!(back.as_ref(), Ok(&doc), "{}", text);
// Writing again is byte-identical.
prop_assert_eq!(vdf::write(&back.unwrap()), text);
}
#[test]
fn generated_strings_round_trip_through_tokens(s in vdf_string(200)) {
let mut o = Obj::new();
o.insert("k".into(), Value::Str(s.clone())).unwrap();
let tokens = vdf::tokenize(vdf::write(&o).as_bytes()).unwrap();
let kinds: Vec<TokenKind> = tokens.into_iter().map(|t| t.kind).collect();
prop_assert_eq!(kinds, vec![TokenKind::Str("k".into()), TokenKind::Str(s)]);
}
}
+203
View File
@@ -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`**: `<source>:<native>` 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-<app>://` 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_<id>.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
`<library>\steamapps\common\<installdir>` 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:<id>`, launch `steam://rungameid/<id>`, cover `SteamLibraryCache { app_id }`.
`steam::app_id_from_manifest_name` accepts exactly `appmanifest_<canonical id>.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:<appname lowercased>`, launch `com.epicgames.launcher://apps/<AppName>?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\
<gameID>` 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:<gameID>`, `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:<FNV-1a 64 of the case-folded path, 16 hex>`, 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>` | `id != 0` |
| `Epic { app_name }` | `com.epicgames.launcher://apps/<app_name>?action=launch&silent=true` | `[A-Za-z0-9_-]{1,64}` |
| `DomiLink { app }` | `domi-<app>://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.
+37
View File
@@ -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.
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"