1use crate::model::Provider;
4use serde::{Deserialize, Serialize};
5use std::{
6 io::Read,
7 os::unix::process::CommandExt,
8 path::{Component, Path, PathBuf},
9 process::{Command, Stdio},
10 thread,
11 time::{Duration, Instant},
12};
13
14mod catalog;
15mod npm_discovery;
16
17const LIMIT: usize = 4 * 1024 * 1024;
18const TIMEOUT: Duration = Duration::from_secs(10);
19pub 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.";
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum Query {
27 BrewFormulae,
28 NpmGlobals,
29}
30impl Query {
31 pub fn provider(self) -> Provider {
32 match self {
33 Self::BrewFormulae => Provider::Brew,
34 Self::NpmGlobals => Provider::Npm,
35 }
36 }
37 fn arguments(self) -> Vec<String> {
38 let args: &[&str] = match self {
39 Self::BrewFormulae => &["info", "--json=v2", "--installed", "--formula"],
40 Self::NpmGlobals => &[
41 "ls",
42 "--global",
43 "--json",
44 "--depth=0",
45 "--offline",
46 "--ignore-scripts",
47 "--logs-max=0",
48 "--update-notifier=false",
49 "--audit=false",
50 "--fund=false",
51 ],
52 };
53 args.iter().map(|s| (*s).to_owned()).collect()
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, thiserror::Error)]
58#[serde(rename_all = "snake_case")]
59pub enum Failure {
60 #[error("inspection requires absolute UTF-8 paths without dot components")]
61 InvalidPath,
62 #[error("inspection requires an explicit nonempty trusted executable search path")]
63 InvalidSearchPath,
64 #[error(
65 "npm inspection requires an explicit declared runtime, Node, npm CLI and prefix binding"
66 )]
67 InvalidNpmBinding,
68 #[error("provider executable unavailable or could not start")]
69 Unavailable,
70 #[error("provider pipe setup/read failed")]
71 Pipe,
72 #[error("provider wait failed")]
73 Wait,
74 #[error("provider query exceeded time limit")]
75 Timeout,
76 #[error("provider query exceeded output limit")]
77 OutputLimit,
78 #[error("provider query failed; raw output withheld")]
79 QueryFailed,
80 #[error("provider returned malformed or unsupported metadata; raw output withheld")]
81 Malformed,
82 #[error("package database contains incomplete or repair-required packages")]
83 IncompletePackages,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
88pub struct Installation {
89 pub package: String,
91 pub version: String,
92}
93
94#[derive(Debug, Serialize)]
96#[serde(tag = "state", rename_all = "snake_case")]
97pub enum Observation {
98 Complete { installations: Vec<Installation> },
99 Unavailable { reason: Failure },
100}
101#[derive(Debug, Serialize)]
102pub struct Report {
103 pub description: Description,
104 pub observation: Observation,
105}
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct NpmBinding {
111 pub runtime_tool: String,
112 pub node: PathBuf,
113 pub npm_cli: PathBuf,
114 pub prefix: PathBuf,
115}
116
117#[derive(Debug, Clone, Serialize)]
119pub struct Description {
120 pub query: Query,
121 pub executable: PathBuf,
122 pub arguments: Vec<String>,
123 pub working_directory: &'static str,
124 pub home: PathBuf,
125 pub trusted_search_path: Vec<PathBuf>,
126 pub npm_binding: Option<NpmBinding>,
127 #[serde(skip_serializing_if = "Option::is_none")]
129 pub npm_global_prefix: Option<PathBuf>,
130 pub warning: &'static str,
131 pub output_limit_bytes: usize,
132 pub timeout_seconds: u64,
133}
134pub struct Preview {
137 description: Description,
138 prefix_probe: Option<Description>,
139}
140pub struct Approval(Preview);
142
143pub(super) fn absolute(path: &Path) -> bool {
144 path.is_absolute()
145 && path.to_str().is_some()
146 && path.components().all(|c| matches!(c, Component::RootDir | Component::Normal(_)))
147 && !path.as_os_str().as_encoded_bytes().contains(&0)
148 && !path.to_str().unwrap_or("").split('/').any(|c| c == "." || c == "..")
150}
151impl Preview {
152 pub fn new(
156 query: Query,
157 executable: PathBuf,
158 home: PathBuf,
159 trusted_search_path: Vec<PathBuf>,
160 ) -> Result<Self, Failure> {
161 if query == Query::NpmGlobals {
162 return Err(Failure::InvalidNpmBinding);
163 }
164 Self::with_binding(query, executable, home, trusted_search_path, None)
165 }
166 pub fn npm_inventory(
170 executable: PathBuf,
171 home: PathBuf,
172 trusted_search_path: Vec<PathBuf>,
173 ) -> Result<Self, Failure> {
174 let mut preview = Self::with_binding(
175 Query::NpmGlobals,
176 executable,
177 home,
178 trusted_search_path,
179 None,
180 )?;
181 preview.description.warning = npm_discovery::WARNING;
182 let mut probe = preview.description.clone();
183 probe.arguments = npm_discovery::prefix_arguments();
184 probe.output_limit_bytes = npm_discovery::PREFIX_LIMIT;
185 preview.prefix_probe = Some(probe);
186 Ok(preview)
187 }
188 pub fn npm(
191 manifest: &crate::Manifest,
192 binding: NpmBinding,
193 home: PathBuf,
194 trusted_search_path: Vec<PathBuf>,
195 ) -> Result<Self, Failure> {
196 if !manifest.tools.iter().any(|t| t.id == binding.runtime_tool) {
197 return Err(Failure::InvalidNpmBinding);
198 }
199 Self::npm_probe(binding, home, trusted_search_path)
200 }
201 pub(crate) fn npm_probe(
204 binding: NpmBinding,
205 home: PathBuf,
206 trusted_search_path: Vec<PathBuf>,
207 ) -> Result<Self, Failure> {
208 if binding.runtime_tool.is_empty()
209 || binding.runtime_tool.len() > 256
210 || !binding
211 .runtime_tool
212 .bytes()
213 .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
214 {
215 return Err(Failure::InvalidNpmBinding);
216 }
217 if !absolute(&binding.node) || !absolute(&binding.npm_cli) || !absolute(&binding.prefix) {
218 return Err(Failure::InvalidPath);
219 }
220 Self::with_binding(
221 Query::NpmGlobals,
222 binding.node.clone(),
223 home,
224 trusted_search_path,
225 Some(binding),
226 )
227 }
228 fn with_binding(
229 query: Query,
230 executable: PathBuf,
231 home: PathBuf,
232 trusted_search_path: Vec<PathBuf>,
233 npm_binding: Option<NpmBinding>,
234 ) -> Result<Self, Failure> {
235 if !absolute(&executable) || !absolute(&home) {
236 return Err(Failure::InvalidPath);
237 }
238 if trusted_search_path.is_empty()
239 || trusted_search_path.iter().any(|p| !absolute(p))
240 || std::env::join_paths(&trusted_search_path).is_err()
241 {
242 return Err(Failure::InvalidSearchPath);
243 }
244 let mut arguments = query.arguments();
245 if let Some(binding) = &npm_binding {
246 arguments.insert(
247 0,
248 binding
249 .npm_cli
250 .to_str()
251 .ok_or(Failure::InvalidPath)?
252 .to_owned(),
253 );
254 arguments.push("--prefix".into());
255 arguments.push(
256 binding
257 .prefix
258 .to_str()
259 .ok_or(Failure::InvalidPath)?
260 .to_owned(),
261 );
262 }
263 Ok(Self {
264 prefix_probe: None,
265 description: Description {
266 query,
267 executable,
268 arguments,
269 working_directory: "/",
270 home,
271 trusted_search_path,
272 npm_binding,
273 npm_global_prefix: None,
274 warning: WARNING,
275 output_limit_bytes: LIMIT,
276 timeout_seconds: TIMEOUT.as_secs(),
277 },
278 })
279 }
280 pub fn description(&self) -> &Description {
281 &self.description
282 }
283 pub fn prefix_probe(&self) -> Option<&Description> {
284 self.prefix_probe.as_ref()
285 }
286 pub fn approve(self) -> Approval {
289 Approval(self)
290 }
291}
292impl Approval {
293 pub fn inspect(self) -> Report {
294 let Preview {
295 mut description,
296 prefix_probe,
297 } = self.0;
298 let result = if let Some(probe) = prefix_probe {
299 npm_discovery::inspect(&probe, &mut description)
300 } else {
301 run_bounded(command(&description), LIMIT, TIMEOUT)
302 .and_then(|bytes| catalog::parse(description.query, &bytes))
303 };
304 Report {
305 description,
306 observation: match result {
307 Ok(installations) => Observation::Complete { installations },
308 Err(reason) => Observation::Unavailable { reason },
309 },
310 }
311 }
312}
313fn command(d: &Description) -> Command {
314 let mut command = Command::new(&d.executable);
315 command
316 .env_clear()
317 .env("HOME", &d.home)
318 .env("XDG_CONFIG_HOME", d.home.join(".config"))
319 .env("XDG_CACHE_HOME", d.home.join(".cache"))
320 .env("XDG_DATA_HOME", d.home.join(".local/share"))
321 .env("XDG_STATE_HOME", d.home.join(".local/state"))
322 .env(
323 "PATH",
324 std::env::join_paths(&d.trusted_search_path).expect("validated search path"),
325 )
326 .env("LC_ALL", "C")
327 .env("LANG", "C")
328 .env("NO_COLOR", "1")
329 .current_dir(d.working_directory)
330 .args(&d.arguments);
331 match d.query {
332 Query::BrewFormulae => {
333 command
334 .env("HOMEBREW_NO_AUTO_UPDATE", "1")
335 .env("HOMEBREW_NO_ANALYTICS", "1")
336 .env("HOMEBREW_NO_ENV_HINTS", "1")
337 .env("HOMEBREW_NO_INSTALL_FROM_API", "1");
338 }
339 Query::NpmGlobals => {}
340 }
341 command
342}
343
344pub(crate) fn run_bounded(
347 mut command: Command,
348 limit: usize,
349 timeout: Duration,
350) -> Result<Vec<u8>, Failure> {
351 command
352 .stdin(Stdio::null())
353 .stdout(Stdio::piped())
354 .stderr(Stdio::piped())
355 .process_group(0);
356 let mut child = command.spawn().map_err(|_| Failure::Unavailable)?;
357 let result = (|| {
358 let mut stdout = child.stdout.take().ok_or(Failure::Pipe)?;
359 let mut stderr = child.stderr.take().ok_or(Failure::Pipe)?;
360 use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
361 for pipe in [&stdout as &dyn std::os::fd::AsFd, &stderr] {
362 let flags = fcntl_getfl(pipe).map_err(|_| Failure::Pipe)?;
363 fcntl_setfl(pipe, flags | OFlags::NONBLOCK).map_err(|_| Failure::Pipe)?;
364 }
365 let start = Instant::now();
366 let mut bytes = Vec::new();
367 let mut total = 0usize;
368 let (mut out_done, mut err_done) = (false, false);
369 loop {
370 if start.elapsed() >= timeout {
371 return Err(Failure::Timeout);
372 }
373 for (pipe, done, keep) in [
374 (&mut stdout as &mut dyn Read, &mut out_done, true),
375 (&mut stderr as &mut dyn Read, &mut err_done, false),
376 ] {
377 if *done {
378 continue;
379 }
380 let mut buffer = [0; 8192];
381 match pipe.read(&mut buffer) {
382 Ok(0) => *done = true,
383 Ok(count) => {
384 total += count;
385 if total > limit {
386 return Err(Failure::OutputLimit);
387 }
388 if keep {
389 bytes.extend_from_slice(&buffer[..count]);
390 }
391 }
392 Err(e)
393 if matches!(
394 e.kind(),
395 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted
396 ) => {}
397 Err(_) => return Err(Failure::Pipe),
398 }
399 }
400 if let Some(status) = child.try_wait().map_err(|_| Failure::Wait)?
401 && out_done
402 && err_done
403 {
404 return if status.success() {
405 Ok(bytes)
406 } else {
407 Err(Failure::QueryFailed)
408 };
409 }
410 thread::sleep(Duration::from_millis(1));
411 }
412 })();
413 if let Some(pid) = rustix::process::Pid::from_raw(child.id() as i32) {
415 let _ = rustix::process::kill_process_group(pid, rustix::process::Signal::KILL);
416 }
417 let _ = child.wait();
418 result
419}
420
421#[cfg(test)]
422mod tests;