use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};
pub const ENV: &str = "ICEDWRIGHT_REMOTE";
#[derive(Debug, Clone, Copy)]
pub struct Startup<'a> {
pub debug_assertions: bool,
pub allow_in_release: bool,
pub remote_env: Option<&'a OsStr>,
pub runtime_dir: Option<&'a Path>,
pub app: &'a str,
pub pid: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SocketPlan {
pub dir: PathBuf,
pub create_dir: bool,
pub path: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Off,
Listen(SocketPlan),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refusal {
Release,
NoRuntimeDir,
NoParent(PathBuf),
NotOwned {
dir: PathBuf,
owner: u32,
},
Writable {
dir: PathBuf,
mode: u32,
},
Io(String),
}
impl fmt::Display for Refusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Refusal::Release => f.write_str(
"this is a release build; the remote endpoint opens in release only with the \
probe's `remote-in-release` feature",
),
Refusal::NoRuntimeDir => f.write_str(
"XDG_RUNTIME_DIR is not set, and the endpoint never falls back to /tmp; set it \
or give ICEDWRIGHT_REMOTE a socket path",
),
Refusal::NoParent(path) => {
write!(f, "the socket path {} has no directory", path.display())
}
Refusal::NotOwned { dir, owner } => write!(
f,
"{} belongs to uid {owner}, not to this user",
dir.display()
),
Refusal::Writable { dir, mode } => write!(
f,
"{} is writable by its group or others (mode {mode:o}); it must be private",
dir.display()
),
Refusal::Io(error) => write!(f, "the socket could not be set up: {error}"),
}
}
}
impl std::error::Error for Refusal {}
pub fn decide(startup: &Startup<'_>) -> Result<Decision, Refusal> {
let Some(value) = startup.remote_env.filter(|v| !v.is_empty()) else {
return Ok(Decision::Off);
};
if !startup.debug_assertions && !startup.allow_in_release {
return Err(Refusal::Release);
}
if value == "1" {
let runtime = startup.runtime_dir.ok_or(Refusal::NoRuntimeDir)?;
let dir = runtime.join("icedwright");
let path = dir.join(format!("{}-{}.sock", file_safe(startup.app), startup.pid));
return Ok(Decision::Listen(SocketPlan {
dir,
create_dir: true,
path,
}));
}
let path = PathBuf::from(value);
let dir = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.ok_or_else(|| Refusal::NoParent(path.clone()))?
.to_path_buf();
Ok(Decision::Listen(SocketPlan {
dir,
create_dir: false,
path,
}))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DirFacts {
pub owner: u32,
pub mode: u32,
}
pub fn check_dir(dir: &Path, facts: DirFacts, uid: u32) -> Result<(), Refusal> {
if facts.owner != uid {
return Err(Refusal::NotOwned {
dir: dir.to_path_buf(),
owner: facts.owner,
});
}
if facts.mode & 0o022 != 0 {
return Err(Refusal::Writable {
dir: dir.to_path_buf(),
mode: facts.mode & 0o7777,
});
}
Ok(())
}
fn file_safe(name: &str) -> String {
let cleaned: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c
} else {
'_'
}
})
.collect();
if cleaned.is_empty() {
"app".to_owned()
} else {
cleaned
}
}
#[cfg(test)]
mod tests {
use super::*;
fn startup<'a>(env: Option<&'a str>, runtime: Option<&'a Path>) -> Startup<'a> {
Startup {
debug_assertions: true,
allow_in_release: false,
remote_env: env.map(OsStr::new),
runtime_dir: runtime,
app: "remote demo",
pid: 42,
}
}
#[test]
fn unset_or_empty_means_off() {
assert_eq!(decide(&startup(None, None)), Ok(Decision::Off));
assert_eq!(decide(&startup(Some(""), None)), Ok(Decision::Off));
}
#[test]
fn release_profile_refuses_unless_allowed() {
let mut s = startup(Some("1"), Some(Path::new("/run/user/1000")));
s.debug_assertions = false;
assert_eq!(decide(&s), Err(Refusal::Release));
s.allow_in_release = true;
assert!(matches!(decide(&s), Ok(Decision::Listen(_))));
}
#[test]
fn release_profile_without_the_variable_stays_off() {
let mut s = startup(None, None);
s.debug_assertions = false;
assert_eq!(decide(&s), Ok(Decision::Off));
}
#[test]
fn default_path_lives_in_the_runtime_dir() {
let decision = decide(&startup(Some("1"), Some(Path::new("/run/user/1000"))));
assert_eq!(
decision,
Ok(Decision::Listen(SocketPlan {
dir: PathBuf::from("/run/user/1000/icedwright"),
create_dir: true,
path: PathBuf::from("/run/user/1000/icedwright/remote_demo-42.sock"),
}))
);
}
#[test]
fn missing_runtime_dir_is_refused_without_a_fallback() {
assert_eq!(
decide(&startup(Some("1"), None)),
Err(Refusal::NoRuntimeDir)
);
}
#[test]
fn explicit_paths_use_their_parent() {
let decision = decide(&startup(Some("/home/me/sockets/app.sock"), None));
assert_eq!(
decision,
Ok(Decision::Listen(SocketPlan {
dir: PathBuf::from("/home/me/sockets"),
create_dir: false,
path: PathBuf::from("/home/me/sockets/app.sock"),
}))
);
assert!(matches!(
decide(&startup(Some("app.sock"), None)),
Err(Refusal::NoParent(_))
));
}
#[test]
fn directories_must_be_private_and_ours() {
let dir = Path::new("/d");
let ok = DirFacts {
owner: 1000,
mode: 0o40700,
};
assert_eq!(check_dir(dir, ok, 1000), Ok(()));
assert!(matches!(
check_dir(
dir,
DirFacts {
mode: 0o40770,
..ok
},
1000
),
Err(Refusal::Writable { mode: 0o770, .. })
));
assert!(matches!(
check_dir(
dir,
DirFacts {
mode: 0o40702,
..ok
},
1000
),
Err(Refusal::Writable { .. })
));
assert!(matches!(
check_dir(dir, DirFacts { owner: 0, ..ok }, 1000),
Err(Refusal::NotOwned { owner: 0, .. })
));
assert_eq!(
check_dir(
dir,
DirFacts {
mode: 0o40755,
..ok
},
1000
),
Ok(())
);
}
}