use crate::model::Provider;
use serde::{Deserialize, Serialize};
use std::{
io::Read,
os::unix::process::CommandExt,
path::{Component, Path, PathBuf},
process::{Command, Stdio},
thread,
time::{Duration, Instant},
};
mod catalog;
mod npm_discovery;
const LIMIT: usize = 4 * 1024 * 1024;
const TIMEOUT: Duration = Duration::from_secs(10);
pub const WARNING: &str = "Runs a local package-manager program. It can run configuration and plugin code, and change caches or logs. No packages are installed. Results are what the package manager reports; Dort does not verify ownership or command identity.";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Query {
BrewFormulae,
NpmGlobals,
}
impl Query {
pub fn provider(self) -> Provider {
match self {
Self::BrewFormulae => Provider::Brew,
Self::NpmGlobals => Provider::Npm,
}
}
fn arguments(self) -> Vec<String> {
let args: &[&str] = match self {
Self::BrewFormulae => &["info", "--json=v2", "--installed", "--formula"],
Self::NpmGlobals => &[
"ls",
"--global",
"--json",
"--depth=0",
"--offline",
"--ignore-scripts",
"--logs-max=0",
"--update-notifier=false",
"--audit=false",
"--fund=false",
],
};
args.iter().map(|s| (*s).to_owned()).collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, thiserror::Error)]
#[serde(rename_all = "snake_case")]
pub enum Failure {
#[error("inspection requires absolute UTF-8 paths without dot components")]
InvalidPath,
#[error("inspection requires an explicit nonempty trusted executable search path")]
InvalidSearchPath,
#[error(
"npm inspection requires an explicit declared runtime, Node, npm CLI and prefix binding"
)]
InvalidNpmBinding,
#[error("provider executable unavailable or could not start")]
Unavailable,
#[error("provider pipe setup/read failed")]
Pipe,
#[error("provider wait failed")]
Wait,
#[error("provider query exceeded time limit")]
Timeout,
#[error("provider query exceeded output limit")]
OutputLimit,
#[error("provider query failed; raw output withheld")]
QueryFailed,
#[error("provider returned malformed or unsupported metadata; raw output withheld")]
Malformed,
#[error("package database contains incomplete or repair-required packages")]
IncompletePackages,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Installation {
pub package: String,
pub version: String,
}
#[derive(Debug, Serialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum Observation {
Complete { installations: Vec<Installation> },
Unavailable { reason: Failure },
}
#[derive(Debug, Serialize)]
pub struct Report {
pub description: Description,
pub observation: Observation,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NpmBinding {
pub runtime_tool: String,
pub node: PathBuf,
pub npm_cli: PathBuf,
pub prefix: PathBuf,
}
#[derive(Debug, Clone, Serialize)]
pub struct Description {
pub query: Query,
pub executable: PathBuf,
pub arguments: Vec<String>,
pub working_directory: &'static str,
pub home: PathBuf,
pub trusted_search_path: Vec<PathBuf>,
pub npm_binding: Option<NpmBinding>,
#[serde(skip_serializing_if = "Option::is_none")]
pub npm_global_prefix: Option<PathBuf>,
pub warning: &'static str,
pub output_limit_bytes: usize,
pub timeout_seconds: u64,
}
pub struct Preview {
description: Description,
prefix_probe: Option<Description>,
}
pub struct Approval(Preview);
pub(super) fn absolute(path: &Path) -> bool {
path.is_absolute()
&& path.to_str().is_some()
&& path.components().all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
&& !path.as_os_str().as_encoded_bytes().contains(&0)
&& !path.to_str().unwrap_or("").split('/').any(|c| c == "." || c == "..")
}
impl Preview {
pub fn new(
query: Query,
executable: PathBuf,
home: PathBuf,
trusted_search_path: Vec<PathBuf>,
) -> Result<Self, Failure> {
if query == Query::NpmGlobals {
return Err(Failure::InvalidNpmBinding);
}
Self::with_binding(query, executable, home, trusted_search_path, None)
}
pub fn npm_inventory(
executable: PathBuf,
home: PathBuf,
trusted_search_path: Vec<PathBuf>,
) -> Result<Self, Failure> {
let mut preview = Self::with_binding(
Query::NpmGlobals,
executable,
home,
trusted_search_path,
None,
)?;
preview.description.warning = npm_discovery::WARNING;
let mut probe = preview.description.clone();
probe.arguments = npm_discovery::prefix_arguments();
probe.output_limit_bytes = npm_discovery::PREFIX_LIMIT;
preview.prefix_probe = Some(probe);
Ok(preview)
}
pub fn npm(
manifest: &crate::Manifest,
binding: NpmBinding,
home: PathBuf,
trusted_search_path: Vec<PathBuf>,
) -> Result<Self, Failure> {
if !manifest.tools.iter().any(|t| t.id == binding.runtime_tool) {
return Err(Failure::InvalidNpmBinding);
}
Self::npm_probe(binding, home, trusted_search_path)
}
pub(crate) fn npm_probe(
binding: NpmBinding,
home: PathBuf,
trusted_search_path: Vec<PathBuf>,
) -> Result<Self, Failure> {
if binding.runtime_tool.is_empty()
|| binding.runtime_tool.len() > 256
|| !binding
.runtime_tool
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
{
return Err(Failure::InvalidNpmBinding);
}
if !absolute(&binding.node) || !absolute(&binding.npm_cli) || !absolute(&binding.prefix) {
return Err(Failure::InvalidPath);
}
Self::with_binding(
Query::NpmGlobals,
binding.node.clone(),
home,
trusted_search_path,
Some(binding),
)
}
fn with_binding(
query: Query,
executable: PathBuf,
home: PathBuf,
trusted_search_path: Vec<PathBuf>,
npm_binding: Option<NpmBinding>,
) -> Result<Self, Failure> {
if !absolute(&executable) || !absolute(&home) {
return Err(Failure::InvalidPath);
}
if trusted_search_path.is_empty()
|| trusted_search_path.iter().any(|p| !absolute(p))
|| std::env::join_paths(&trusted_search_path).is_err()
{
return Err(Failure::InvalidSearchPath);
}
let mut arguments = query.arguments();
if let Some(binding) = &npm_binding {
arguments.insert(
0,
binding
.npm_cli
.to_str()
.ok_or(Failure::InvalidPath)?
.to_owned(),
);
arguments.push("--prefix".into());
arguments.push(
binding
.prefix
.to_str()
.ok_or(Failure::InvalidPath)?
.to_owned(),
);
}
Ok(Self {
prefix_probe: None,
description: Description {
query,
executable,
arguments,
working_directory: "/",
home,
trusted_search_path,
npm_binding,
npm_global_prefix: None,
warning: WARNING,
output_limit_bytes: LIMIT,
timeout_seconds: TIMEOUT.as_secs(),
},
})
}
pub fn description(&self) -> &Description {
&self.description
}
pub fn prefix_probe(&self) -> Option<&Description> {
self.prefix_probe.as_ref()
}
pub fn approve(self) -> Approval {
Approval(self)
}
}
impl Approval {
pub fn inspect(self) -> Report {
let Preview {
mut description,
prefix_probe,
} = self.0;
let result = if let Some(probe) = prefix_probe {
npm_discovery::inspect(&probe, &mut description)
} else {
run_bounded(command(&description), LIMIT, TIMEOUT)
.and_then(|bytes| catalog::parse(description.query, &bytes))
};
Report {
description,
observation: match result {
Ok(installations) => Observation::Complete { installations },
Err(reason) => Observation::Unavailable { reason },
},
}
}
}
fn command(d: &Description) -> Command {
let mut command = Command::new(&d.executable);
command
.env_clear()
.env("HOME", &d.home)
.env("XDG_CONFIG_HOME", d.home.join(".config"))
.env("XDG_CACHE_HOME", d.home.join(".cache"))
.env("XDG_DATA_HOME", d.home.join(".local/share"))
.env("XDG_STATE_HOME", d.home.join(".local/state"))
.env(
"PATH",
std::env::join_paths(&d.trusted_search_path).expect("validated search path"),
)
.env("LC_ALL", "C")
.env("LANG", "C")
.env("NO_COLOR", "1")
.current_dir(d.working_directory)
.args(&d.arguments);
match d.query {
Query::BrewFormulae => {
command
.env("HOMEBREW_NO_AUTO_UPDATE", "1")
.env("HOMEBREW_NO_ANALYTICS", "1")
.env("HOMEBREW_NO_ENV_HINTS", "1")
.env("HOMEBREW_NO_INSTALL_FROM_API", "1");
}
Query::NpmGlobals => {}
}
command
}
pub(crate) fn run_bounded(
mut command: Command,
limit: usize,
timeout: Duration,
) -> Result<Vec<u8>, Failure> {
command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0);
let mut child = command.spawn().map_err(|_| Failure::Unavailable)?;
let result = (|| {
let mut stdout = child.stdout.take().ok_or(Failure::Pipe)?;
let mut stderr = child.stderr.take().ok_or(Failure::Pipe)?;
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
for pipe in [&stdout as &dyn std::os::fd::AsFd, &stderr] {
let flags = fcntl_getfl(pipe).map_err(|_| Failure::Pipe)?;
fcntl_setfl(pipe, flags | OFlags::NONBLOCK).map_err(|_| Failure::Pipe)?;
}
let start = Instant::now();
let mut bytes = Vec::new();
let mut total = 0usize;
let (mut out_done, mut err_done) = (false, false);
loop {
if start.elapsed() >= timeout {
return Err(Failure::Timeout);
}
for (pipe, done, keep) in [
(&mut stdout as &mut dyn Read, &mut out_done, true),
(&mut stderr as &mut dyn Read, &mut err_done, false),
] {
if *done {
continue;
}
let mut buffer = [0; 8192];
match pipe.read(&mut buffer) {
Ok(0) => *done = true,
Ok(count) => {
total += count;
if total > limit {
return Err(Failure::OutputLimit);
}
if keep {
bytes.extend_from_slice(&buffer[..count]);
}
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
) => {}
Err(_) => return Err(Failure::Pipe),
}
}
if let Some(status) = child.try_wait().map_err(|_| Failure::Wait)?
&& out_done
&& err_done
{
return if status.success() {
Ok(bytes)
} else {
Err(Failure::QueryFailed)
};
}
thread::sleep(Duration::from_millis(1));
}
})();
if let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32) {
let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
}
let _ = child.wait();
result
}
#[cfg(test)]
mod tests;