diff --git a/src/inject.rs b/src/inject.rs index 1f6179f..ee7bb84 100644 --- a/src/inject.rs +++ b/src/inject.rs @@ -87,46 +87,29 @@ pub fn build_exec_script(command: &str, env: &[String], working_dir: Option<&str lines } +/// Write `content` to a temp file and install it into the mounted rootfs at +/// `/slim/` with the given mode. +fn install_into_rootfs(mount: &str, name: &str, mode: &str, content: &str) -> Result<()> { + let temp = tempfile::NamedTempFile::new()?; + fs::write(temp.path(), content)?; + let src = temp.path().to_str().context("temp path is not UTF-8")?; + let dest = format!("{mount}/slim/{name}"); + cmd(&[ + "podman", "unshare", "--", "install", "-D", "-m", mode, src, &dest, + ])?; + Ok(()) +} + /// Inject /slim/init, /slim/exec, and optionally /slim/user into a mounted /// container image rootfs. pub fn inject(mount_path: &Path, exec_script: &str, user: Option<&str>) -> Result<()> { let mount_str = mount_path.to_str().context("mount path is not UTF-8")?; - let init_temp = tempfile::NamedTempFile::new()?; - let exec_temp = tempfile::NamedTempFile::new()?; - fs::write(init_temp.path(), SLIM_INIT)?; - fs::write(exec_temp.path(), exec_script)?; - - let init_src = init_temp - .path() - .to_str() - .context("temp path is not UTF-8")?; - let exec_src = exec_temp - .path() - .to_str() - .context("temp path is not UTF-8")?; - - let init_dest = format!("{mount_str}/slim/init"); - let exec_dest = format!("{mount_str}/slim/exec"); - - cmd(&[ - "podman", "unshare", "--", "install", "-D", "-m", "755", init_src, &init_dest, - ])?; - cmd(&[ - "podman", "unshare", "--", "install", "-D", "-m", "755", exec_src, &exec_dest, - ])?; + install_into_rootfs(mount_str, "init", "755", SLIM_INIT)?; + install_into_rootfs(mount_str, "exec", "755", exec_script)?; if let Some(user) = user.filter(|u| !u.is_empty()) { - let user_temp = tempfile::NamedTempFile::new()?; - fs::write(user_temp.path(), user)?; - let user_src = user_temp - .path() - .to_str() - .context("temp path is not UTF-8")?; - let user_dest = format!("{mount_str}/slim/user"); - cmd(&[ - "podman", "unshare", "--", "install", "-D", "-m", "644", user_src, &user_dest, - ])?; + install_into_rootfs(mount_str, "user", "644", user)?; } Ok(())