#![deny(unsafe_code)]
use std::io::ErrorKind;
use std::process::{Command, Stdio};
use std::sync::Mutex;
use crate::url::{scheme_allowed, scheme_of};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Desktop {
Xdg,
Macos,
Windows,
}
impl Desktop {
#[cfg(test)]
pub const ALL: [Desktop; 3] = [Desktop::Xdg, Desktop::Macos, Desktop::Windows];
}
pub const HOST: Desktop = if cfg!(windows) {
Desktop::Windows
} else if cfg!(target_os = "macos") {
Desktop::Macos
} else {
Desktop::Xdg
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Argv {
pub program: &'static str,
pub args: Vec<String>,
}
pub fn argv(desktop: Desktop, url: &str) -> Argv {
match desktop {
Desktop::Xdg => Argv {
program: "xdg-open",
args: vec![url.to_string()],
},
Desktop::Macos => Argv {
program: "open",
args: vec![url.to_string()],
},
Desktop::Windows => Argv {
program: "rundll32",
args: vec![
"url.dll,FileProtocolHandler".to_string(),
url.to_string(),
],
},
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum OpenError {
Missing(&'static str),
Failed { program: &'static str, why: String },
}
impl OpenError {
pub fn message(&self) -> String {
match self {
OpenError::Missing(p) => format!("no system opener: {p} is not installed"),
OpenError::Failed { program, why } => format!("could not run {program}: {why}"),
}
}
}
static SPAWNED: Mutex<Vec<std::process::Child>> = Mutex::new(Vec::new());
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Vetted<'a> {
url: &'a str,
}
impl<'a> Vetted<'a> {
pub fn new(url: &'a str, allowed: &[&str]) -> Option<Vetted<'a>> {
let scheme = scheme_of(url)?;
scheme_allowed(scheme, allowed).then_some(Vetted { url })
}
pub fn url(&self) -> &'a str {
self.url
}
}
pub fn open(url: Vetted<'_>) -> Result<&'static str, OpenError> {
let Argv { program, args } = argv(HOST, url.url());
reap();
let child = Command::new(program)
.args(&args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
match child {
Ok(c) => {
if let Ok(mut held) = SPAWNED.lock() {
held.push(c);
}
Ok(program)
}
Err(e) if e.kind() == ErrorKind::NotFound => Err(OpenError::Missing(program)),
Err(e) => Err(OpenError::Failed {
program,
why: e.to_string(),
}),
}
}
fn reap() {
if let Ok(mut held) = SPAWNED.lock() {
held.retain_mut(|c| !matches!(c.try_wait(), Ok(Some(_)) | Err(_)));
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_platform_gets_its_documented_argv() {
let url = "https://example.com/a?b=c";
assert_eq!(
argv(Desktop::Xdg, url),
Argv {
program: "xdg-open",
args: vec![url.to_string()]
}
);
assert_eq!(
argv(Desktop::Macos, url),
Argv {
program: "open",
args: vec![url.to_string()]
}
);
assert_eq!(
argv(Desktop::Windows, url),
Argv {
program: "rundll32",
args: vec![
"url.dll,FileProtocolHandler".to_string(),
url.to_string()
]
}
);
}
#[test]
fn no_platform_runs_a_shell() {
for d in Desktop::ALL {
let a = argv(d, "https://x");
for forbidden in ["cmd", "cmd.exe", "sh", "bash", "start", "powershell"] {
assert_ne!(a.program, forbidden, "{d:?} must not run a shell");
assert!(
!a.args.iter().any(|s| s == forbidden),
"{d:?} must not pass {forbidden}"
);
}
assert!(!a.program.contains(' '), "{d:?}: program is one word");
}
}
#[test]
fn a_hostile_url_stays_one_untouched_argument() {
let nasty = "https://x/?a=1&b=2|c;rm -rf /`whoami`$(id)\"'\n\\%windir%^&";
for d in Desktop::ALL {
let a = argv(d, nasty);
assert_eq!(
a.args.iter().filter(|s| s.contains(nasty)).count(),
1,
"{d:?}: the url appears once"
);
assert!(a.args.contains(&nasty.to_string()), "{d:?}: verbatim");
assert_eq!(a.args.last().map(String::as_str), Some(nasty));
}
}
#[test]
fn mailto_is_passed_like_any_other_url() {
for d in Desktop::ALL {
let a = argv(d, "mailto:someone@example.com?subject=hi there");
assert_eq!(
a.args.last().map(String::as_str),
Some("mailto:someone@example.com?subject=hi there")
);
}
}
#[test]
fn only_a_scheme_on_the_list_can_be_vetted() {
let list = ["http", "https", "mailto"];
for url in ["http://x", "https://x/a?b#c", "mailto:a@b", "HTTPS://x"] {
assert_eq!(Vetted::new(url, &list).map(|v| v.url()), Some(url), "{url}");
}
for url in [
"file:///etc/passwd",
"javascript:alert(1)",
"vbscript:msgbox(1)",
"data:text/html,x",
"models/A.md",
"#anchor",
"",
] {
assert!(Vetted::new(url, &list).is_none(), "{url} must not vet");
}
}
#[test]
fn an_empty_allowlist_vets_nothing() {
assert!(Vetted::new("https://example.com", &[]).is_none());
}
#[test]
fn vetting_does_not_touch_the_url() {
let url = "https://x/?a=1&b=2|c;\"'`$( )";
let v = Vetted::new(url, &["https"]).expect("https is on the list");
assert_eq!(v.url(), url);
assert_eq!(argv(HOST, v.url()).args.last().map(String::as_str), Some(url));
}
#[test]
fn host_matches_the_compilation_target() {
assert_eq!(HOST == Desktop::Windows, cfg!(windows));
assert_eq!(
HOST == Desktop::Macos,
cfg!(all(target_os = "macos", not(windows)))
);
assert!(Desktop::ALL.contains(&HOST));
}
#[test]
fn failures_name_the_program() {
let missing = OpenError::Missing("xdg-open").message();
assert!(missing.contains("xdg-open"), "{missing}");
assert!(missing.contains("not installed"), "{missing}");
let failed = OpenError::Failed {
program: "open",
why: "permission denied".to_string(),
}
.message();
assert!(failed.contains("open") && failed.contains("permission denied"), "{failed}");
}
}