1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
// Copyright (C) 2023 Andreas Hartmann <hartan@7x.de>
// GNU General Public License v3.0+ (https://www.gnu.org/licenses/gpl-3.0.txt)
// SPDX-License-Identifier: GPL-3.0-or-later
//! Environment handlers.
//!
//! This module contains handlers for various environments. Generally a handler is characterized by
//! the presence of the following public functions within its submodule:
//!
//! - `detect` to find out if this is the current execution environment (where the command wasn't
//! found)
//! - `find` to see if a certain command exists in this execution environment
//! - `handle` to kick off the chain to look a certain command up from inside this environment
//! - `execute` to und a command in this environment
//!
//! Especially the latter function isn't
pub mod container;
pub mod distrobox;
pub mod host;
pub mod toolbx;
#[cfg(test)]
use crate::test::prelude::*;
use prelude::*;
pub(crate) mod prelude {
pub use crate::{
environment::{self, Environment},
util::{cmd, CommandLine, OutputMatcher},
};
pub use async_process::Command;
pub use serde_derive::{Deserialize, Serialize};
pub use std::fmt;
pub use thiserror::Error as ThisError;
}
/// Trait for usable environments.
pub trait IsEnvironment: fmt::Debug + fmt::Display {
type Err;
/// Returns true if the given Env is available at all.
///
/// We assume the environment `Host` to be available unconditionally. Other environments, such
/// as `toolbx`, can only be available when at least the `toolbx` executable is present, or we
/// are currently inside a toolbx.
fn exists(&self) -> bool;
/// Execute a command within this environment
///
/// [`IsProvider`](crate::provider::IsProvider) implementations should prefer calling
/// [`output_of()`] instead of interacting with an [`Environment`] instance directly.
/// Refer to [`output_of()`] for details.
///
/// [`output_of()`]: Environment::output_of()
fn execute(&self, command: CommandLine) -> Result<Command, Self::Err>;
}
/// All the execution environments known to the applicaiton.
#[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Environment {
//Container,
/// The host system
Host(host::Host),
/// A distrobox instance
Distrobox(distrobox::Distrobox),
/// A toolbx instance
Toolbx(toolbx::Toolbx),
/// Mock environment (test only)
#[cfg(test)]
Mock(Mock),
}
impl Environment {
/// Execute a command in this environment and collect stdout, if possible.
///
/// Executes `cmd` inside this env, collecting all output. If execution finishes successfully,
/// the stdout is returned as [`String`]. Otherwise, an [`ExecutionError`] is returned instead.
///
/// The [`ExecutionError`] type takes care of a lot of boilerplate code that is otherwise necessary
/// to detect specific error conditions caused by *different* environments (because they can
/// produce different output for similar/identical error conditions).
///
/// Refer to [`OutputMatcher`] for added convenience when trying to recover from a
/// [`NonZero`](ExecutionError::NonZero) error.
///
///
/// ### Test integration
///
/// In conjunction with the [`Mock`](crate::test::mock::Mock) type, this function allows
/// replaying the output of called commands. Use the [`quick_test!`](crate::test::quick_test)
/// macro to simulate command outputs inside tests.
// TODO(hartan): This swallows stderr in case of success. Is that a problem?
#[cfg(not(test))]
pub async fn output_of(&self, cmd: CommandLine) -> Result<String, ExecutionError> {
let main_command = cmd.command();
let output = self
.execute(cmd)
.map_err(ExecutionError::Environment)?
.output()
.await
.map_err(|err| match err.kind() {
std::io::ErrorKind::NotFound => ExecutionError::NotFound(main_command.clone()),
_ => ExecutionError::Unknown(err),
})?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).to_string())
} else {
let matcher = OutputMatcher::new(&output);
if matcher.starts_with(
// When calling into toolbx from host
&format!(
"Error: crun: executable file `{}` not found in $PATH: No such file or directory",
main_command.clone()
)
) ||
// When calling into host from toolbx
matcher.starts_with(
"Portal call failed: Failed to start command: Failed to execute child process"
) && matcher.ends_with("(No such file or directory)")
{
Err(ExecutionError::NotFound(main_command))
} else {
Err(ExecutionError::NonZero {
command: main_command,
output,
})
}
}
}
#[cfg(test)]
pub async fn output_of(&self, _command: CommandLine) -> Result<String, ExecutionError> {
match self {
Environment::Mock(ref mock) => mock.pop_raw(),
_ => panic!("cannot execute commands in tests with regular envs"),
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(&self)
.unwrap_or_else(|_| panic!("failed to serialize env '{}' to JSON", self))
}
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Host(val) => write!(f, "{}", val),
Self::Distrobox(val) => write!(f, "{}", val),
Self::Toolbx(val) => write!(f, "{}", val),
#[cfg(test)]
Self::Mock(val) => write!(f, "{}", val),
}
}
}
impl IsEnvironment for Environment {
type Err = Error;
fn exists(&self) -> bool {
match self {
Self::Host(val) => val.exists(),
Self::Distrobox(val) => val.exists(),
Self::Toolbx(val) => val.exists(),
#[cfg(test)]
Self::Mock(val) => val.exists(),
}
}
fn execute(&self, command: CommandLine) -> Result<Command, Self::Err> {
match self {
Self::Host(val) => val.execute(command).map_err(Error::ExecuteOnHost),
Self::Distrobox(val) => {
val.execute(command)
.map_err(|e| Self::Err::ExecuteInDistrobox {
distrobox: val.to_string(),
source: e,
})
}
Self::Toolbx(val) => val
.execute(command)
.map_err(|e| Self::Err::ExecuteInToolbx {
toolbx: val.to_string(),
source: e,
}),
#[cfg(test)]
Self::Mock(val) => Ok(val.execute(command).unwrap()),
}
}
}
impl From<host::Host> for Environment {
fn from(value: host::Host) -> Self {
Self::Host(value)
}
}
impl From<distrobox::Distrobox> for Environment {
fn from(value: distrobox::Distrobox) -> Self {
Self::Distrobox(value)
}
}
impl From<toolbx::Toolbx> for Environment {
fn from(value: toolbx::Toolbx) -> Self {
Self::Toolbx(value)
}
}
impl std::str::FromStr for Environment {
type Err = SerializationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let val: Self =
serde_json::from_str(s).map_err(|_| SerializationError { raw: s.to_owned() })?;
Ok(val)
}
}
// TODO(hartan): The error message from this is far from ideal.
#[derive(Debug, ThisError, Serialize, Deserialize)]
#[error("invalid environment specification '{raw}'")]
pub struct SerializationError {
raw: String,
}
/// Return the current execution environment.
// TODO(hartan): This should change. Ideally the lib loads all envs once during startup, storing
// them into a `Vec<Arc<Environment>>`, and then we can return a fresh `Arc<>` here. This way all
// envs exist exactly once and can sensibly share state (e.g. system info, if that ever becomes
// important).
pub fn current() -> Environment {
if toolbx::detect() {
Environment::Toolbx(toolbx::Toolbx::current().unwrap())
} else if distrobox::detect() {
Environment::Distrobox(distrobox::Distrobox::current().unwrap())
} else {
Environment::Host(host::Host::new())
}
}
/// Preserve the users environments.
///
/// Attempts to replicate all environment variables of the current process in the spawned
/// environment. Refer to the source code to see exactly which variables are preserved. Variables
/// are returned as a vector of strings with 'KEY=VALUE' notation.
pub fn read_env_vars() -> Vec<String> {
let exclude = vec![
"HOST",
"HOSTNAME",
"HOME",
"LANG",
"LC_CTYPE",
"PATH",
"PROFILEREAD",
"SHELL",
];
std::env::vars()
.filter_map(|(mut key, value)| {
if exclude.contains(&&key[..])
|| key.starts_with('_')
|| (key.starts_with("XDG_") && key.ends_with("_DIRS"))
{
None
} else {
key.push('=');
key.push_str(&value);
Some(key)
}
})
.collect::<Vec<_>>()
}
/// Common errors from command execution.
// TODO(hartan): This doesn't detect issues with privilege escalation yet. I should probably add a
// different error-variant for this.
#[derive(Debug, ThisError)]
pub enum ExecutionError {
/// Requested executable cannot be found
#[error("command not found: {0}")]
NotFound(String),
/// Error inside an [`Environment`]
#[error(transparent)]
Environment(#[from] Error),
/// Error from [`Command`](async_process::Command)
#[error(transparent)]
Unknown(#[from] std::io::Error),
/// Error from the called command
///
/// ## Note
///
/// When calling from the host into a toolbx container, *stdout* and *stderr* are both merged
/// into *stdout*. This is currently a shortcoming of the involved call to `podman exec -t
/// ...`. Refer to the manpage of `podman-exec(1)`, in particular the *NOTE* attached to
/// `--tty`.
///
/// This means that when checking for messages in `output.stderr`, you should **always** check
/// for the existence of your message in **both stderr and stdout**.
#[error("command '{command}' exited with nonzero code")]
NonZero {
command: String,
output: std::process::Output,
},
}
#[derive(Debug, ThisError)]
pub enum Error {
#[error("failed to execute command on host")]
ExecuteOnHost(#[from] <host::Host as IsEnvironment>::Err),
#[error("failed to execute command in '{toolbx}'")]
ExecuteInToolbx {
toolbx: String,
source: <toolbx::Toolbx as IsEnvironment>::Err,
},
#[error("failed to execute command in '{distrobox}'")]
ExecuteInDistrobox {
distrobox: String,
source: <distrobox::Distrobox as IsEnvironment>::Err,
},
}