[core] Parsers: strict VDF, Steam, Epic, GOG, manual and Domi sources, WinPath, GameId, Launch URIs, merge
This commit is contained in:
@@ -6,7 +6,10 @@
|
||||
//! web games (Rosea, Moin) opened by URL.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::model::Game;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::Launch;
|
||||
use crate::model::{CoverHint, Game};
|
||||
use crate::text;
|
||||
|
||||
/// How a Domi game starts.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -20,6 +23,21 @@ pub enum DomiLaunch<'a> {
|
||||
/// The game for one Domi entry. `id` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end) and
|
||||
/// becomes `domi:<id>`; `name` is the title. No install folder.
|
||||
pub fn game(id: &str, name: &str, launch: DomiLaunch<'_>) -> Result<Game, ParseError> {
|
||||
let _ = (id, name, launch);
|
||||
Err(ParseError::BadId)
|
||||
if !text::is_atrium_id(id) {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
let title = text::title(name, "name")?;
|
||||
let launch = match launch {
|
||||
DomiLaunch::Link { app } => Launch::domi_link(app)?,
|
||||
DomiLaunch::Web { url, allowed_hosts } => Launch::web(url, allowed_hosts)?,
|
||||
};
|
||||
let id = GameId::new(Source::Domi, id)?;
|
||||
Ok(Game {
|
||||
cover: Some(CoverHint::lettered(&title, &id)),
|
||||
id,
|
||||
source: Source::Domi,
|
||||
title,
|
||||
install_dir: None,
|
||||
launch,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,12 +7,138 @@
|
||||
//! `com.epicgames.launcher://apps/<AppName>?action=launch&silent=true`.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::model::Game;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::Launch;
|
||||
use crate::limits::{MAX_DEPTH, MAX_FILE};
|
||||
use crate::model::{CoverHint, Game};
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
use serde::de::IgnoredAny;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use serde_json::Value;
|
||||
|
||||
/// The fields read from a manifest. Present-but-`null` is kept apart from absent, so `null` is a wrong type.
|
||||
#[derive(Deserialize)]
|
||||
struct Raw {
|
||||
#[serde(rename = "AppName", default, deserialize_with = "present")]
|
||||
app_name: Option<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> {
|
||||
let _ = json;
|
||||
Err(ParseError::Syntax { at: 0 })
|
||||
if json.len() > MAX_FILE {
|
||||
return Err(ParseError::TooLarge);
|
||||
}
|
||||
let whole = std::str::from_utf8(json).map_err(|_| ParseError::NotUtf8)?;
|
||||
let (bom, text) = match whole.strip_prefix('\u{feff}') {
|
||||
Some(rest) => (3, rest),
|
||||
None => (0, whole),
|
||||
};
|
||||
check_depth(text)?;
|
||||
// serde would read a struct from an array too; only an object is a manifest.
|
||||
if !text.trim_start().starts_with('{') {
|
||||
return Err(match serde_json::from_str::<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))
|
||||
}
|
||||
|
||||
@@ -7,7 +7,12 @@
|
||||
//! `workingDir`, `launchParam`) and passes the values in. Launch is the `.exe` directly.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::model::Game;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::{Launch, split_args};
|
||||
use crate::limits::MAX_GOG_ID;
|
||||
use crate::model::{CoverHint, Game};
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
|
||||
/// The registry values of one GOG game, as the app read them.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
@@ -28,6 +33,36 @@ pub struct GogEntry {
|
||||
|
||||
/// The game for one GOG entry.
|
||||
pub fn game(e: &GogEntry) -> Result<Game, ParseError> {
|
||||
let _ = e;
|
||||
Err(ParseError::BadId)
|
||||
if !(1..=MAX_GOG_ID).contains(&e.game_id.len()) || !e.game_id.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
let title = text::title(&e.name, "name")?;
|
||||
let path = WinPath::parse(&e.path).map_err(|_| ParseError::BadPath("path"))?;
|
||||
let exe = resolve(&path, &e.exe).map_err(|_| ParseError::BadPath("exe"))?;
|
||||
if !exe.starts_with(&path) || exe == path || !text::is_exe(&exe) {
|
||||
return Err(ParseError::BadPath("exe"));
|
||||
}
|
||||
let working_dir = match e.working_dir.as_deref().map(str::trim) {
|
||||
None | Some("") => exe.parent().ok_or(ParseError::BadPath("exe"))?,
|
||||
Some(w) => resolve(&path, w).map_err(|_| ParseError::BadPath("working_dir"))?,
|
||||
};
|
||||
let args = match e.launch_params.as_deref() {
|
||||
None => Vec::new(),
|
||||
Some(line) => split_args(line)?,
|
||||
};
|
||||
let id = GameId::new(Source::Gog, &e.game_id)?;
|
||||
Ok(Game {
|
||||
cover: Some(CoverHint::lettered(&title, &id)),
|
||||
id,
|
||||
source: Source::Gog,
|
||||
title,
|
||||
install_dir: Some(path),
|
||||
launch: Launch::exe(exe, working_dir, args)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// An absolute path as it is, a relative one inside `base`.
|
||||
fn resolve(base: &WinPath, s: &str) -> Result<WinPath, ParseError> {
|
||||
let absolute = s.get(1..2) == Some(":") || s.starts_with(['\\', '/']);
|
||||
if absolute { WinPath::parse(s) } else { base.join(s) }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::limits::{MAX_GAME_ID, MAX_GOG_ID};
|
||||
use crate::text;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
@@ -72,8 +74,14 @@ pub struct GameId(String);
|
||||
impl GameId {
|
||||
/// Builds and checks `<source>:<native>`.
|
||||
pub fn new(source: Source, native: &str) -> Result<GameId, ParseError> {
|
||||
let _ = (source, native);
|
||||
Err(ParseError::BadId)
|
||||
if !native_ok(source, native) {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
let id = format!("{source}:{native}");
|
||||
if id.len() > MAX_GAME_ID {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
Ok(GameId(id))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
@@ -82,12 +90,13 @@ impl GameId {
|
||||
|
||||
/// The source named by the prefix.
|
||||
pub fn source(&self) -> Source {
|
||||
Source::Manual
|
||||
// Every GameId was built by `new`, so the prefix is a known source.
|
||||
self.0.split_once(':').and_then(|(s, _)| s.parse().ok()).unwrap_or(Source::Manual)
|
||||
}
|
||||
|
||||
/// The part after `<source>:`.
|
||||
pub fn native(&self) -> &str {
|
||||
""
|
||||
self.0.split_once(':').map_or("", |(_, n)| n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,8 +110,22 @@ impl FromStr for GameId {
|
||||
type Err = ParseError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let _ = s;
|
||||
Err(ParseError::BadId)
|
||||
if s.len() > MAX_GAME_ID {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
let (source, native) = s.split_once(':').ok_or(ParseError::BadId)?;
|
||||
GameId::new(source.parse()?, native)
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-source rule for the part after `<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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+164
-19
@@ -3,7 +3,9 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::limits::{MAX_ARG, MAX_ARGS, MAX_ARGS_LINE, MAX_HOST, MAX_URL};
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How to start a game. The protocol variants become a URI through [`Launch::uri`]; [`Launch::Exe`] is started
|
||||
@@ -30,50 +32,194 @@ pub enum Launch {
|
||||
impl Launch {
|
||||
/// A Steam launch; the app id may not be 0.
|
||||
pub fn steam(app_id: u32) -> Result<Launch, ParseError> {
|
||||
let _ = app_id;
|
||||
Err(ParseError::BadId)
|
||||
if app_id == 0 {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
Ok(Launch::SteamRunGameId(app_id))
|
||||
}
|
||||
|
||||
/// An Epic launch; `app_name` must match `[A-Za-z0-9_-]{1,64}`.
|
||||
pub fn epic(app_name: &str) -> Result<Launch, ParseError> {
|
||||
let _ = app_name;
|
||||
Err(ParseError::BadId)
|
||||
if !text::is_epic_app(app_name) {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
Ok(Launch::Epic { app_name: app_name.to_owned() })
|
||||
}
|
||||
|
||||
/// A direct launch. `exe` must end in `.exe` (so never a `.bat`, `.cmd` or `.lnk`, which Windows would hand to
|
||||
/// a shell); each argument is checked (no control characters, caps on count and length).
|
||||
pub fn exe(exe: WinPath, working_dir: WinPath, args: Vec<String>) -> Result<Launch, ParseError> {
|
||||
let _ = (exe, working_dir, args);
|
||||
Err(ParseError::BadPath("exe"))
|
||||
if !text::is_exe(&exe) {
|
||||
return Err(ParseError::BadPath("exe"));
|
||||
}
|
||||
check_args(&args)?;
|
||||
Ok(Launch::Exe { exe, working_dir, args })
|
||||
}
|
||||
|
||||
/// A Domi app link; `app` follows the Atrium id rules (`[a-z0-9-]{1,32}`, no `-` at either end).
|
||||
pub fn domi_link(app: &str) -> Result<Launch, ParseError> {
|
||||
let _ = app;
|
||||
Err(ParseError::BadId)
|
||||
if !text::is_atrium_id(app) {
|
||||
return Err(ParseError::BadId);
|
||||
}
|
||||
Ok(Launch::DomiLink { app: app.to_owned() })
|
||||
}
|
||||
|
||||
/// A web game. The URL must be `https://<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 _ = (url, allowed_hosts);
|
||||
Err(ParseError::BadValue("url"))
|
||||
let (normal, host_len) = check_url(url)?;
|
||||
if !host_allowed(&normal, host_len, allowed_hosts) {
|
||||
return Err(ParseError::BadValue("url"));
|
||||
}
|
||||
Ok(Launch::Url(normal))
|
||||
}
|
||||
|
||||
/// The exact URI for the protocol variants, rebuilt from the validated fields; `None` for [`Launch::Exe`] and
|
||||
/// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only; use
|
||||
/// [`Launch::uri_checked`] to apply the host allow-list again.
|
||||
/// for any field that fails validation. For [`Launch::Url`] this checks the URL's form only (and that it is
|
||||
/// already normalised); use [`Launch::uri_checked`] to apply the host allow-list again.
|
||||
pub fn uri(&self) -> Option<String> {
|
||||
None
|
||||
match self {
|
||||
Launch::SteamRunGameId(id) => (*id != 0).then(|| format!("steam://rungameid/{id}")),
|
||||
Launch::Epic { app_name } => text::is_epic_app(app_name)
|
||||
.then(|| format!("com.epicgames.launcher://apps/{app_name}?action=launch&silent=true")),
|
||||
Launch::DomiLink { app } => text::is_atrium_id(app).then(|| format!("domi-{app}://open")),
|
||||
Launch::Url(url) => match check_url(url) {
|
||||
Ok((normal, _)) if &normal == url => Some(normal),
|
||||
_ => None,
|
||||
},
|
||||
Launch::Exe { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// As [`Launch::uri`], and a [`Launch::Url`] must also have its host in `allowed_hosts`.
|
||||
pub fn uri_checked(&self, allowed_hosts: &[&str]) -> Option<String> {
|
||||
let _ = allowed_hosts;
|
||||
None
|
||||
match self {
|
||||
Launch::Url(url) => match check_url(url) {
|
||||
Ok((normal, host_len)) if &normal == url && host_allowed(&normal, host_len, allowed_hosts) => {
|
||||
Some(normal)
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
other => other.uri(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments of an exe launch: at most `MAX_ARGS`, each at most `MAX_ARG` bytes, no control characters.
|
||||
fn check_args(args: &[String]) -> Result<(), ParseError> {
|
||||
if args.len() > MAX_ARGS {
|
||||
return Err(ParseError::TooMany("args"));
|
||||
}
|
||||
for a in args {
|
||||
if a.len() > MAX_ARG {
|
||||
return Err(ParseError::TooLong("arg"));
|
||||
}
|
||||
if a.chars().any(char::is_control) {
|
||||
return Err(ParseError::BadValue("args"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Splits a launch-parameter line into arguments: spaces separate, `"` groups (and is removed), nothing else is
|
||||
/// special. Refuses control characters (tabs included) and an unclosed quote.
|
||||
pub(crate) fn split_args(line: &str) -> Result<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")]
|
||||
@@ -88,16 +234,15 @@ enum LaunchRepr {
|
||||
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) => {
|
||||
let _ = url;
|
||||
Err(ParseError::BadValue("url"))
|
||||
}
|
||||
LaunchRepr::Url(url) => check_url(&url).map(|(normal, _)| Launch::Url(normal)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,36 @@
|
||||
//! A game the user added by picking its `.exe`.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::model::Game;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::Launch;
|
||||
use crate::model::{CoverHint, Game};
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
|
||||
/// The game for an `.exe` the user picked. The id is `manual:<16 hex>`, a stable hash of the path ignoring case,
|
||||
/// so adding the same file twice gives the same id. The title defaults to the file name without `.exe`; the
|
||||
/// install and working folder are the exe's folder; no arguments.
|
||||
pub fn game(exe: &str, title: Option<&str>) -> Result<Game, ParseError> {
|
||||
let _ = (exe, title);
|
||||
Err(ParseError::BadPath("exe"))
|
||||
const BAD: ParseError = ParseError::BadPath("exe");
|
||||
let exe = WinPath::parse(exe).map_err(|_| BAD)?;
|
||||
if !text::is_exe(&exe) {
|
||||
return Err(BAD);
|
||||
}
|
||||
let dir = exe.parent().ok_or(BAD)?;
|
||||
let title = match title {
|
||||
Some(t) => text::title(t, "title")?,
|
||||
None => {
|
||||
let name = exe.file_name().ok_or(BAD)?;
|
||||
text::title(name.get(..name.len() - 4).ok_or(BAD)?, "title")?
|
||||
}
|
||||
};
|
||||
let id = GameId::new(Source::Manual, &format!("{:016x}", text::fnv1a64(exe.key().as_bytes())))?;
|
||||
Ok(Game {
|
||||
cover: Some(CoverHint::lettered(&title, &id)),
|
||||
id,
|
||||
source: Source::Manual,
|
||||
title,
|
||||
install_dir: Some(dir.clone()),
|
||||
launch: Launch::exe(exe, dir, Vec::new())?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,13 +2,18 @@
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::Launch;
|
||||
use crate::limits::MAX_GAMES;
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// One game in the library.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "GameRepr")]
|
||||
pub struct Game {
|
||||
pub id: GameId,
|
||||
pub source: Source,
|
||||
@@ -19,6 +24,35 @@ pub struct Game {
|
||||
pub cover: Option<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")]
|
||||
@@ -69,6 +103,24 @@ impl Library {
|
||||
/// - The result is sorted by title (ignoring case), then by id, so the order does not depend on scan order.
|
||||
/// - At most [`crate::limits::MAX_GAMES`] games are considered; the rest are dropped.
|
||||
pub fn merge(scans: Vec<Vec<Game>>) -> Library {
|
||||
let _ = scans;
|
||||
Library::default()
|
||||
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 }
|
||||
}
|
||||
|
||||
@@ -3,10 +3,22 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::limits::MAX_PATH;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
const BAD: ParseError = ParseError::BadPath("path");
|
||||
const SEPARATORS: [char; 2] = ['\\', '/'];
|
||||
/// `X:\`
|
||||
const ROOT_LEN: usize = 3;
|
||||
/// Device names Windows opens instead of a file, whatever the folder or extension.
|
||||
const DEVICES: [&str; 32] = [
|
||||
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM0", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7",
|
||||
"COM8", "COM9", "COM¹", "COM²", "COM³", "LPT0", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8",
|
||||
"LPT9", "LPT¹", "LPT²", "LPT³",
|
||||
];
|
||||
|
||||
/// An absolute Windows path with a drive letter, checked and normalised.
|
||||
///
|
||||
/// Refused: anything not starting with `X:\` (so UNC `\\server\share`, `\\?\` and `\\.\` too), `.` and `..`
|
||||
@@ -23,8 +35,35 @@ pub struct WinPath(String);
|
||||
impl WinPath {
|
||||
/// Checks and normalises `s`.
|
||||
pub fn parse(s: &str) -> Result<WinPath, ParseError> {
|
||||
let _ = s;
|
||||
Err(ParseError::BadPath("path"))
|
||||
// Cheap bound first: no valid path has more than 4 bytes per UTF-16 unit.
|
||||
if s.len() > 4 * MAX_PATH {
|
||||
return Err(BAD);
|
||||
}
|
||||
let mut chars = s.chars();
|
||||
let drive = chars.next().filter(char::is_ascii_alphabetic).ok_or(BAD)?;
|
||||
if chars.next() != Some(':') {
|
||||
return Err(BAD);
|
||||
}
|
||||
let rest = chars.as_str();
|
||||
if !rest.starts_with(SEPARATORS) {
|
||||
return Err(BAD);
|
||||
}
|
||||
let mut out = String::with_capacity(s.len());
|
||||
out.push(drive.to_ascii_uppercase());
|
||||
out.push_str(":\\");
|
||||
let mut first = true;
|
||||
for comp in rest.split(SEPARATORS).filter(|c| !c.is_empty()) {
|
||||
check_component(comp)?;
|
||||
if !first {
|
||||
out.push('\\');
|
||||
}
|
||||
first = false;
|
||||
out.push_str(comp);
|
||||
}
|
||||
if out.encode_utf16().count() > MAX_PATH {
|
||||
return Err(BAD);
|
||||
}
|
||||
Ok(WinPath(out))
|
||||
}
|
||||
|
||||
pub fn as_str(&self) -> &str {
|
||||
@@ -33,23 +72,34 @@ impl WinPath {
|
||||
|
||||
/// Appends a relative path (`a\b` or `a/b`); the same component rules apply and it may not climb out.
|
||||
pub fn join(&self, relative: &str) -> Result<WinPath, ParseError> {
|
||||
let _ = relative;
|
||||
Err(ParseError::BadPath("path"))
|
||||
if relative.is_empty() || relative.starts_with(SEPARATORS) {
|
||||
return Err(BAD);
|
||||
}
|
||||
let mut joined = String::with_capacity(self.0.len() + 1 + relative.len());
|
||||
joined.push_str(&self.0);
|
||||
if !joined.ends_with('\\') {
|
||||
joined.push('\\');
|
||||
}
|
||||
joined.push_str(relative);
|
||||
WinPath::parse(&joined)
|
||||
}
|
||||
|
||||
/// The containing folder, or `None` for a drive root.
|
||||
pub fn parent(&self) -> Option<WinPath> {
|
||||
None
|
||||
self.file_name()?;
|
||||
let cut = self.0.rfind('\\')?;
|
||||
let head = if cut < ROOT_LEN { self.0.get(..ROOT_LEN)? } else { self.0.get(..cut)? };
|
||||
Some(WinPath(head.to_owned()))
|
||||
}
|
||||
|
||||
/// The last component, or `None` for a drive root.
|
||||
pub fn file_name(&self) -> Option<&str> {
|
||||
None
|
||||
self.components().last()
|
||||
}
|
||||
|
||||
/// The components after the drive root.
|
||||
pub fn components(&self) -> impl Iterator<Item = &str> {
|
||||
std::iter::empty()
|
||||
self.0.get(ROOT_LEN..).unwrap_or_default().split('\\').filter(|c| !c.is_empty())
|
||||
}
|
||||
|
||||
/// The case-folded form Windows treats as the same place, for comparing and deduping.
|
||||
@@ -64,11 +114,30 @@ impl WinPath {
|
||||
|
||||
/// True when `self` is `base` or lies inside it (component-wise, ignoring case).
|
||||
pub fn starts_with(&self, base: &WinPath) -> bool {
|
||||
let _ = base;
|
||||
false
|
||||
let same_drive = self.0.get(..1).zip(base.0.get(..1)).is_some_and(|(a, b)| a.eq_ignore_ascii_case(b));
|
||||
if !same_drive {
|
||||
return false;
|
||||
}
|
||||
let mut mine = self.components();
|
||||
base.components().all(|b| mine.next().is_some_and(|m| m.to_lowercase() == b.to_lowercase()))
|
||||
}
|
||||
}
|
||||
|
||||
/// One path component, between separators.
|
||||
fn check_component(c: &str) -> Result<(), ParseError> {
|
||||
if c == "." || c == ".." || c.ends_with('.') || c.ends_with(' ') {
|
||||
return Err(BAD);
|
||||
}
|
||||
if c.chars().any(|ch| ch.is_control() || matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*')) {
|
||||
return Err(BAD);
|
||||
}
|
||||
let stem = c.split('.').next().unwrap_or(c).trim_end_matches(' ');
|
||||
if DEVICES.iter().any(|d| d.eq_ignore_ascii_case(stem)) {
|
||||
return Err(BAD);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl fmt::Display for WinPath {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.0)
|
||||
|
||||
@@ -6,33 +6,107 @@
|
||||
//! `<library>/steamapps/appmanifest_<id>.acf`. Launch is `steam://rungameid/<id>`.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::model::Game;
|
||||
use crate::id::{GameId, Source};
|
||||
use crate::launch::Launch;
|
||||
use crate::limits::MAX_LIBRARIES;
|
||||
use crate::model::{CoverHint, Game};
|
||||
use crate::path::WinPath;
|
||||
use crate::text;
|
||||
use crate::vdf::{self, Obj, Value};
|
||||
|
||||
/// Steam's own redistributables and runtimes: installed like games, never played.
|
||||
const TOOLS: [u32; 7] = [
|
||||
228_980, // Steamworks Common Redistributables
|
||||
1_070_560, // Steam Linux Runtime 1.0 (scout)
|
||||
1_391_110, // Steam Linux Runtime 2.0 (soldier)
|
||||
1_628_350, // Steam Linux Runtime 3.0 (sniper)
|
||||
1_493_710, // Proton Experimental
|
||||
1_826_330, // Proton EasyAntiCheat Runtime
|
||||
1_161_040, // Proton BattlEye Runtime
|
||||
];
|
||||
|
||||
/// The library folders listed in `libraryfolders.vdf` (both the current layout, `"0" { "path" "..." }`, and the
|
||||
/// old one, `"1" "D:\\SteamLibrary"`). At most [`crate::limits::MAX_LIBRARIES`]; a path listed twice is refused.
|
||||
/// Keys under the root that are not plain numbers (`contentstatsid`, ...) are skipped.
|
||||
pub fn library_folders(vdf: &[u8]) -> Result<Vec<WinPath>, ParseError> {
|
||||
let _ = vdf;
|
||||
Err(ParseError::Syntax { at: 0 })
|
||||
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 _ = (acf, library);
|
||||
Err(ParseError::Syntax { at: 0 })
|
||||
let doc = vdf::parse(acf)?;
|
||||
let state = obj(&doc, "AppState")?;
|
||||
let app_id = text::canonical_u32(string(state, "appid")?).ok_or(ParseError::BadId)?;
|
||||
let title = text::title(string(state, "name")?, "name")?;
|
||||
let installdir = string(state, "installdir")?;
|
||||
if is_tool(app_id) {
|
||||
return Err(ParseError::NotAGame("Steam redistributable or runtime"));
|
||||
}
|
||||
if installdir.is_empty() || installdir.contains(['\\', '/']) {
|
||||
return Err(ParseError::BadPath("installdir"));
|
||||
}
|
||||
let install_dir = library
|
||||
.join("steamapps")
|
||||
.and_then(|p| p.join("common"))
|
||||
.and_then(|p| p.join(installdir))
|
||||
.map_err(|_| ParseError::BadPath("installdir"))?;
|
||||
Ok(Game {
|
||||
id: GameId::new(Source::Steam, &app_id.to_string())?,
|
||||
source: Source::Steam,
|
||||
title,
|
||||
install_dir: Some(install_dir),
|
||||
launch: Launch::steam(app_id)?,
|
||||
cover: Some(CoverHint::SteamLibraryCache { app_id }),
|
||||
})
|
||||
}
|
||||
|
||||
/// The app id in a file name `appmanifest_<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> {
|
||||
let _ = name;
|
||||
None
|
||||
text::canonical_u32(name.strip_prefix("appmanifest_")?.strip_suffix(".acf")?)
|
||||
}
|
||||
|
||||
/// Steam apps that are not games: the common redistributables and the Linux runtimes.
|
||||
pub fn is_tool(app_id: u32) -> bool {
|
||||
let _ = app_id;
|
||||
false
|
||||
TOOLS.contains(&app_id)
|
||||
}
|
||||
|
||||
/// The object under `key`.
|
||||
fn obj<'a>(o: &'a Obj, key: &'static str) -> Result<&'a Obj, ParseError> {
|
||||
match o.get(key) {
|
||||
Some(Value::Obj(inner)) => Ok(inner),
|
||||
Some(Value::Str(_)) => Err(ParseError::WrongType(key)),
|
||||
None => Err(ParseError::Missing(key)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The string under `key`.
|
||||
fn string<'a>(o: &'a Obj, key: &'static str) -> Result<&'a str, ParseError> {
|
||||
match o.get(key) {
|
||||
Some(Value::Str(s)) => Ok(s),
|
||||
Some(Value::Obj(_)) => Err(ParseError::WrongType(key)),
|
||||
None => Err(ParseError::Missing(key)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,60 @@
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! Small shared helpers: title checks, a stable hash, the lettered cover.
|
||||
//! Small shared checks: titles, ids, numbers, a stable hash, the lettered cover.
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::id::GameId;
|
||||
use crate::limits::{MAX_DOMI_ID, MAX_EPIC_APP, MAX_TITLE};
|
||||
use crate::model::CoverHint;
|
||||
use crate::path::WinPath;
|
||||
|
||||
/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control characters.
|
||||
/// Bidirectional-override characters, which could make a title display as something else.
|
||||
fn is_bidi_control(c: char) -> bool {
|
||||
matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{200e}' | '\u{200f}' | '\u{061c}')
|
||||
}
|
||||
|
||||
/// Checks a display title: trimmed, 1 to `MAX_TITLE` characters, no control or bidi-override characters.
|
||||
pub(crate) fn title(s: &str, field: &'static str) -> Result<String, ParseError> {
|
||||
let _ = s;
|
||||
Err(ParseError::Missing(field))
|
||||
let t = s.trim();
|
||||
if t.is_empty() {
|
||||
return Err(ParseError::Missing(field));
|
||||
}
|
||||
if t.chars().nth(MAX_TITLE).is_some() {
|
||||
return Err(ParseError::TooLong(field));
|
||||
}
|
||||
if t.chars().any(|c| c.is_control() || is_bidi_control(c)) {
|
||||
return Err(ParseError::BadValue(field));
|
||||
}
|
||||
Ok(t.to_owned())
|
||||
}
|
||||
|
||||
/// A canonical decimal `u32` other than 0: digits only, no sign, no leading zero, no whitespace.
|
||||
pub(crate) fn canonical_u32(s: &str) -> Option<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).
|
||||
@@ -25,6 +69,17 @@ pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 {
|
||||
}
|
||||
|
||||
pub(crate) fn lettered(title: &str, id: &GameId) -> CoverHint {
|
||||
let _ = (title, id);
|
||||
CoverHint::Lettered { letter: '#', hue: 0 }
|
||||
let letter = title
|
||||
.chars()
|
||||
.find(|c| c.is_alphanumeric())
|
||||
.map(|c| {
|
||||
let mut up = c.to_uppercase();
|
||||
match (up.next(), up.next()) {
|
||||
(Some(u), None) => u,
|
||||
_ => c,
|
||||
}
|
||||
})
|
||||
.unwrap_or('#');
|
||||
let hue = u16::try_from(fnv1a64(id.as_str().as_bytes()) % 360).unwrap_or(0);
|
||||
CoverHint::Lettered { letter, hue }
|
||||
}
|
||||
|
||||
+265
-16
@@ -6,12 +6,14 @@
|
||||
//! `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: unquoted
|
||||
//! tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control characters or line breaks inside
|
||||
//! a string, NUL anywhere, empty keys, a key repeated on the same level (ignoring ASCII case), and anything over the
|
||||
//! caps in [`crate::limits`].
|
||||
//! CR, LF); `//` comments to the end of the line; one UTF-8 byte-order mark at the start. Refused: input that is not
|
||||
//! UTF-8 as a whole, unquoted tokens, `#include` / `#base`, `[$CONDITION]` tags, any other escape, raw control
|
||||
//! characters (other than tab) or line breaks inside a string, NUL anywhere, empty keys, a key repeated in the same
|
||||
//! object (ignoring ASCII case), and anything over the caps in [`crate::limits`].
|
||||
|
||||
use crate::error::ParseError;
|
||||
use crate::limits::{MAX_DEPTH, MAX_ENTRIES, MAX_ESCAPES, MAX_FILE, MAX_KEY, MAX_VALUE};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// One token and the byte offset where it starts.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -37,26 +39,73 @@ pub enum Value {
|
||||
Obj(Obj),
|
||||
}
|
||||
|
||||
/// An ordered list of key/value pairs with unique keys (ignoring ASCII case).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
/// An ordered list of key/value pairs with unique keys (ignoring ASCII case). It carries its own caps: at most
|
||||
/// [`MAX_DEPTH`] levels of objects below it and [`MAX_ENTRIES`] pairs in total, so every `Obj` can be written and
|
||||
/// read back.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Obj {
|
||||
entries: Vec<(String, Value)>,
|
||||
/// ASCII-lowercased key -> position in `entries`.
|
||||
index: BTreeMap<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, and a key already present.
|
||||
/// Appends a pair. Refuses an empty key, a key or value over its cap, a key already present, an object value
|
||||
/// that would nest deeper than [`MAX_DEPTH`], and more than [`MAX_ENTRIES`] pairs in total.
|
||||
pub fn insert(&mut self, key: String, value: Value) -> Result<(), ParseError> {
|
||||
let _ = (key, value);
|
||||
Err(ParseError::Missing("key"))
|
||||
if key.is_empty() {
|
||||
return Err(ParseError::Missing("key"));
|
||||
}
|
||||
if key.len() > MAX_KEY {
|
||||
return Err(ParseError::TooLong("key"));
|
||||
}
|
||||
writable(&key, "key")?;
|
||||
let (depth, added) = match &value {
|
||||
Value::Str(s) if s.len() > MAX_VALUE => return Err(ParseError::TooLong("value")),
|
||||
Value::Str(s) => {
|
||||
writable(s, "value")?;
|
||||
(0, 1)
|
||||
}
|
||||
Value::Obj(o) => (o.depth + 1, o.total + 1),
|
||||
};
|
||||
if depth > MAX_DEPTH {
|
||||
return Err(ParseError::TooDeep);
|
||||
}
|
||||
let total = self.total + added;
|
||||
if total > MAX_ENTRIES {
|
||||
return Err(ParseError::TooMany("entries"));
|
||||
}
|
||||
let folded = key.to_ascii_lowercase();
|
||||
if self.index.contains_key(&folded) {
|
||||
return Err(ParseError::Duplicate("key"));
|
||||
}
|
||||
self.index.insert(folded, self.entries.len());
|
||||
self.entries.push((key, value));
|
||||
self.depth = self.depth.max(depth);
|
||||
self.total = total;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The value under `key`, ignoring ASCII case.
|
||||
pub fn get(&self, key: &str) -> Option<&Value> {
|
||||
self.entries.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v)
|
||||
let i = *self.index.get(&key.to_ascii_lowercase())?;
|
||||
self.entries.get(i).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// The pairs in file order.
|
||||
@@ -73,20 +122,220 @@ impl Obj {
|
||||
}
|
||||
}
|
||||
|
||||
/// A string [`write`] can carry and [`parse`] reads back: no control characters other than tab, CR and LF, and at
|
||||
/// most [`MAX_ESCAPES`] characters that need an escape.
|
||||
fn writable(s: &str, what: &'static str) -> Result<(), ParseError> {
|
||||
let mut escapes = 0usize;
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' | '"' | '\n' | '\r' => escapes += 1,
|
||||
'\t' => {}
|
||||
c if c.is_ascii_control() => return Err(ParseError::BadValue(what)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if escapes > MAX_ESCAPES {
|
||||
return Err(ParseError::TooMany("escapes"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads tokens one at a time.
|
||||
struct Lexer<'a> {
|
||||
input: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
fn new(input: &'a [u8]) -> Result<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 _ = input;
|
||||
Err(ParseError::Syntax { at: 0 })
|
||||
let mut lx = Lexer::new(input)?;
|
||||
let mut out = Vec::new();
|
||||
while let Some(t) = lx.next_token()? {
|
||||
out.push(t);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Parses a whole document: a sequence of top-level pairs.
|
||||
pub fn parse(input: &[u8]) -> Result<Obj, ParseError> {
|
||||
let _ = input;
|
||||
Err(ParseError::Syntax { at: 0 })
|
||||
let mut lx = Lexer::new(input)?;
|
||||
parse_obj(&mut lx, 0)
|
||||
}
|
||||
|
||||
/// Reads pairs until `}` (inside an object, `depth > 0`) or the end of input (at the top, `depth == 0`).
|
||||
/// Recursion is bounded by `MAX_DEPTH`.
|
||||
fn parse_obj(lx: &mut Lexer<'_>, depth: usize) -> Result<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 _ = doc;
|
||||
String::new()
|
||||
let mut out = String::new();
|
||||
write_obj(doc, 0, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn write_obj(o: &Obj, indent: usize, out: &mut String) {
|
||||
for (k, v) in &o.entries {
|
||||
push_tabs(out, indent);
|
||||
push_quoted(out, k);
|
||||
match v {
|
||||
Value::Str(s) => {
|
||||
out.push_str("\t\t");
|
||||
push_quoted(out, s);
|
||||
out.push('\n');
|
||||
}
|
||||
Value::Obj(inner) => {
|
||||
out.push('\n');
|
||||
push_tabs(out, indent);
|
||||
out.push_str("{\n");
|
||||
write_obj(inner, indent + 1, out);
|
||||
push_tabs(out, indent);
|
||||
out.push_str("}\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn push_tabs(out: &mut String, n: usize) {
|
||||
out.extend(std::iter::repeat_n('\t', n));
|
||||
}
|
||||
|
||||
fn push_quoted(out: &mut String, s: &str) {
|
||||
out.push('"');
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'"' => out.push_str("\\\""),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user