kernel_abi_tools/
container.rs1use crate::{seccomp_profile, Target};
4use std::env;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct Engine {
13 pub program: String,
15 pub engine_args: Vec<String>,
17 pub run_args: Vec<String>,
19}
20
21impl Engine {
22 pub fn from_env() -> Self {
25 Engine {
26 program: env::var("CONTAINER_ENGINE").unwrap_or_else(|_| "podman".to_string()),
27 engine_args: env_words("KERNEL_ABI_ENGINE_ARGS"),
28 run_args: env_words("KERNEL_ABI_RUN_ARGS"),
29 }
30 }
31}
32
33pub fn run(
43 engine: &Engine,
44 target: &Target,
45 image: &str,
46 program: &str,
47 args: &[String],
48) -> Result<i32, String> {
49 if image.is_empty() {
50 return Err("no container image selected".to_string());
51 }
52 let cwd = env::current_dir().map_err(|e| format!("current directory: {e}"))?;
53 let host_program = program
54 .contains('/')
55 .then(|| absolute(&cwd, Path::new(program)));
56 if let Some(p) = &host_program {
57 if !p.is_file() {
58 return Err(format!("{} is not a file on this host", p.display()));
59 }
60 }
61
62 let profile = TempFile::new("kernel-seccomp", ".json")?;
63 fs::write(&profile.0, seccomp_profile(target))
64 .map_err(|e| format!("{}: {e}", profile.0.display()))?;
65
66 let mut cmd = Command::new(&engine.program);
67 cmd.args(&engine.engine_args);
68 cmd.args(["run", "--rm", "--security-opt"]);
69 cmd.arg(format!("seccomp={}", profile.0.display()));
70 cmd.arg("-v").arg(format!("{0}:{0}:z", cwd.display()));
71 match &host_program {
72 Some(p) if !p.starts_with(&cwd) => {
73 cmd.arg("-v").arg(format!("{0}:{0}:ro,z", p.display()));
74 }
75 _ => {}
76 }
77 cmd.arg("-w").arg(&cwd);
78 cmd.args(["-e", "CARGO*", "-e", "RUST*"]);
79 cmd.args(&engine.run_args);
80 cmd.arg(image);
81 match &host_program {
82 Some(p) => cmd.arg(p),
83 None => cmd.arg(program),
84 };
85 cmd.args(args);
86
87 let status = cmd
88 .status()
89 .map_err(|e| format!("cannot start {}: {e}", engine.program))?;
90 Ok(status.code().unwrap_or(128))
91}
92
93fn env_words(name: &str) -> Vec<String> {
94 env::var(name)
95 .unwrap_or_default()
96 .split_whitespace()
97 .map(str::to_string)
98 .collect()
99}
100
101fn absolute(cwd: &Path, path: &Path) -> PathBuf {
102 if path.is_absolute() {
103 path.to_path_buf()
104 } else {
105 cwd.join(path)
106 }
107}
108
109struct TempFile(PathBuf);
111
112impl TempFile {
113 fn new(prefix: &str, suffix: &str) -> Result<Self, String> {
114 let nanos = SystemTime::now()
115 .duration_since(UNIX_EPOCH)
116 .map(|d| d.as_nanos())
117 .unwrap_or(0);
118 let name = format!("{prefix}-{}-{nanos}{suffix}", std::process::id());
119 let path = env::temp_dir().join(name);
120 fs::OpenOptions::new()
121 .write(true)
122 .create_new(true)
123 .open(&path)
124 .map_err(|e| format!("{}: {e}", path.display()))?;
125 Ok(TempFile(path))
126 }
127}
128
129impl Drop for TempFile {
130 fn drop(&mut self) {
131 let _ = fs::remove_file(&self.0);
132 }
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138 use crate::KernelVersion;
139
140 #[test]
141 fn rejects_missing_image_and_missing_host_program() {
142 let engine = Engine {
143 program: "definitely-not-a-container-engine".to_string(),
144 engine_args: Vec::new(),
145 run_args: Vec::new(),
146 };
147 let target = Target::kernel(KernelVersion::parse("4.12").unwrap());
148 assert!(run(&engine, &target, "", "sh", &[]).is_err());
149 let err = run(&engine, &target, "img", "./no/such/program", &[]).unwrap_err();
150 assert!(err.contains("not a file on this host"), "{err}");
151 let err = run(&engine, &target, "img", "sh", &[]).unwrap_err();
152 assert!(err.contains("cannot start"), "{err}");
153 }
154}