Files

249 lines
9.7 KiB
Rust

// 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)),
}
}
}