1use std::{
31 collections::BTreeMap,
32 ffi::OsStr,
33 fs,
34 os::unix::{ffi::OsStrExt as _, fs::PermissionsExt as _},
35};
36
37use kizz_trace::{AbsolutePath, AccessKind, Accesses, Observations, Outcome};
38
39pub const PATH_VARIABLE: &str = "PATH";
41
42const EXECUTE_BITS: u32 = 0o111;
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum ProgramLookup {
48 Found {
50 program: AbsolutePath,
52 checked: Accesses,
54 },
55 NotFound {
57 checked: Accesses,
59 },
60 NotExecutable {
63 candidate: AbsolutePath,
65 checked: Accesses,
67 },
68}
69
70impl ProgramLookup {
71 #[must_use]
73 pub const fn checked(&self) -> &Accesses {
74 match self {
75 Self::Found { checked, .. }
76 | Self::NotFound { checked }
77 | Self::NotExecutable { checked, .. } => checked,
78 }
79 }
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum ProgramSearch {
86 Found {
88 program: AbsolutePath,
90 checked: Observations,
92 },
93 NotFound {
95 checked: Observations,
97 },
98 NotExecutable {
101 candidate: AbsolutePath,
103 checked: Observations,
105 },
106}
107
108impl ProgramSearch {
109 #[must_use]
111 pub const fn checked(&self) -> &Observations {
112 match self {
113 Self::Found { checked, .. }
114 | Self::NotFound { checked }
115 | Self::NotExecutable { checked, .. } => checked,
116 }
117 }
118
119 #[must_use]
122 pub fn into_lookup(self) -> ProgramLookup {
123 match self {
124 Self::Found { program, checked } => {
125 ProgramLookup::Found {
126 program,
127 checked: checked.accesses(),
128 }
129 },
130 Self::NotFound { checked } => {
131 ProgramLookup::NotFound {
132 checked: checked.accesses(),
133 }
134 },
135 Self::NotExecutable { candidate, checked } => {
136 ProgramLookup::NotExecutable {
137 candidate,
138 checked: checked.accesses(),
139 }
140 },
141 }
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
147#[error(
148 "cannot run `{program}`: a program name without `/` is looked up in the task \
149 environment's PATH, but the task environment has no PATH; set it with \
150 env.set(\"PATH\", ...) or inherit it with env.inherit(\"PATH\")"
151)]
152pub struct NoPathError {
153 pub program: String,
155}
156
157pub fn check_path(
166 name: &str,
167 env: &BTreeMap<String, String>,
168) -> Result<(), NoPathError> {
169 if name.contains('/') || env.contains_key(PATH_VARIABLE) {
170 Ok(())
171 } else {
172 Err(NoPathError {
173 program: name.to_owned(),
174 })
175 }
176}
177
178pub fn find_program(
185 name: &str,
186 env: &BTreeMap<String, String>,
187 cwd: &AbsolutePath,
188) -> Result<ProgramLookup, NoPathError> {
189 search_step_program(name, env, cwd, kizz_trace::unnamed_error).map(ProgramSearch::into_lookup)
190}
191
192pub fn search_step_program(
201 name: &str,
202 env: &BTreeMap<String, String>,
203 cwd: &AbsolutePath,
204 error_name: impl Fn(i32) -> String,
205) -> Result<ProgramSearch, NoPathError> {
206 let search = env.get(PATH_VARIABLE).map(OsStr::new);
207 search_program(OsStr::new(name), search, cwd, error_name).ok_or_else(|| {
208 NoPathError {
209 program: name.to_owned(),
210 }
211 })
212}
213
214pub fn search_program(
226 name: &OsStr,
227 search: Option<&OsStr>,
228 cwd: &AbsolutePath,
229 error_name: impl Fn(i32) -> String,
230) -> Option<ProgramSearch> {
231 if name.as_bytes().contains(&b'/') {
232 return Some(ProgramSearch::Found {
233 program: cwd.join(name),
234 checked: Observations::new(),
235 });
236 }
237 let search = search?;
238 let mut checked = Observations::new();
239 if name.is_empty() {
240 return Some(ProgramSearch::NotFound { checked });
241 }
242 let mut not_executable = None;
243 for entry in search.as_bytes().split(|byte| *byte == b':') {
244 let candidate = cwd.join(OsStr::from_bytes(entry)).join(name);
245 let metadata = match fs::metadata(candidate.as_path()) {
246 Ok(metadata) => metadata,
247 Err(error) => {
248 let outcome = error
249 .raw_os_error()
250 .map_or(Outcome::Unknown, |errno| Outcome::Error(error_name(errno)));
251 checked.record(candidate, AccessKind::Probe, outcome);
252 continue;
253 },
254 };
255 checked.record(candidate.clone(), AccessKind::Probe, Outcome::Ok);
256 if metadata.is_file() && metadata.permissions().mode() & EXECUTE_BITS != 0 {
257 return Some(ProgramSearch::Found {
258 program: candidate,
259 checked,
260 });
261 }
262 not_executable.get_or_insert(candidate);
263 }
264 Some(match not_executable {
265 Some(candidate) => ProgramSearch::NotExecutable { candidate, checked },
266 None => ProgramSearch::NotFound { checked },
267 })
268}
269
270#[cfg(test)]
272#[allow(clippy::disallowed_macros, reason = "test code: the tests assert")]
273mod tests {
274 use std::{
275 collections::BTreeMap, ffi::OsStr, fs, os::unix::fs::PermissionsExt as _, path::Path,
276 };
277
278 use kizz_trace::{AbsolutePath, AccessKind, Observations, Outcome};
279
280 use super::{
281 NoPathError, ProgramLookup, ProgramSearch, check_path, find_program, search_program,
282 search_step_program,
283 };
284
285 fn named(errno: i32) -> String {
287 format!("E{errno}")
288 }
289
290 fn fixture() -> Result<(tempfile::TempDir, AbsolutePath), Box<dyn std::error::Error>> {
293 let dir = tempfile::tempdir()?;
294 let root = AbsolutePath::new(dir.path().canonicalize()?)?;
295 for (sub, mode) in [("bin", 0o755), ("text", 0o644)] {
296 fs::create_dir(root.as_path().join(sub))?;
297 let tool = root.as_path().join(sub).join("tool");
298 fs::write(&tool, "#!/bin/sh\n")?;
299 fs::set_permissions(&tool, fs::Permissions::from_mode(mode))?;
300 }
301 Ok((dir, root))
302 }
303
304 fn probe(
306 observations: &mut Observations,
307 path: &Path,
308 outcome: Outcome,
309 ) {
310 observations.record(AbsolutePath::new(path).unwrap(), AccessKind::Probe, outcome);
311 }
312
313 #[test]
318 fn each_checked_location_has_its_outcome() -> Result<(), Box<dyn std::error::Error>> {
319 let (_dir, root) = fixture()?;
320 let missing = root.as_path().join("missing");
321 let bin = root.as_path().join("bin");
322 let search = format!("{}:{}", missing.display(), bin.display());
323 let found = search_program(OsStr::new("tool"), Some(OsStr::new(&search)), &root, named);
324 let mut checked = Observations::new();
325 probe(
326 &mut checked,
327 &missing.join("tool"),
328 Outcome::Error(named(2)),
329 );
330 probe(&mut checked, &bin.join("tool"), Outcome::Ok);
331 let program = AbsolutePath::new(bin.join("tool"))?;
332 assert_eq!(
333 found,
334 Some(ProgramSearch::Found {
335 program: program.clone(),
336 checked: checked.clone(),
337 })
338 );
339 let env = BTreeMap::from([("PATH".to_owned(), search)]);
340 assert_eq!(find_program("tool", &env, &root)?, ProgramLookup::Found {
341 program,
342 checked: checked.accesses(),
343 });
344 Ok(())
345 }
346
347 #[test]
352 fn other_results_of_the_search() -> Result<(), Box<dyn std::error::Error>> {
353 let (_dir, root) = fixture()?;
354 let text = root.as_path().join("text");
355 let search = text.display().to_string();
356 let mut checked = Observations::new();
357 probe(&mut checked, &text.join("tool"), Outcome::Ok);
358 assert_eq!(
359 search_program(OsStr::new("tool"), Some(OsStr::new(&search)), &root, named),
360 Some(ProgramSearch::NotExecutable {
361 candidate: AbsolutePath::new(text.join("tool"))?,
362 checked,
363 })
364 );
365 let mut absent = Observations::new();
366 probe(&mut absent, &text.join("other"), Outcome::Error(named(2)));
367 assert_eq!(
368 search_program(OsStr::new("other"), Some(OsStr::new(&search)), &root, named),
369 Some(ProgramSearch::NotFound { checked: absent })
370 );
371 assert_eq!(
372 search_program(OsStr::new(""), Some(OsStr::new(&search)), &root, named),
373 Some(ProgramSearch::NotFound {
374 checked: Observations::new(),
375 })
376 );
377 assert_eq!(
378 search_program(OsStr::new("./tool"), None, &root, named),
379 Some(ProgramSearch::Found {
380 program: root.join("tool"),
381 checked: Observations::new(),
382 })
383 );
384 assert_eq!(search_program(OsStr::new("tool"), None, &root, named), None);
385 Ok(())
386 }
387
388 #[test]
392 fn the_check_for_path_agrees_with_the_lookup() -> Result<(), Box<dyn std::error::Error>> {
393 let (_dir, root) = fixture()?;
394 let none = BTreeMap::new();
395 let missing = NoPathError {
396 program: "tool".to_owned(),
397 };
398 assert_eq!(check_path("tool", &none), Err(missing.clone()));
399 assert_eq!(
400 search_step_program("tool", &none, &root, named),
401 Err(missing)
402 );
403 assert_eq!(
404 check_path("", &none),
405 Err(NoPathError {
406 program: String::new(),
407 })
408 );
409 assert_eq!(check_path("./tool", &none), Ok(()));
410 assert_eq!(check_path("bin/tool", &none), Ok(()));
411 let empty = BTreeMap::from([("PATH".to_owned(), String::new())]);
412 assert_eq!(check_path("tool", &empty), Ok(()));
413 assert!(search_step_program("tool", &empty, &root, named).is_ok());
414 Ok(())
415 }
416}