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
// 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

//! # Toolbx Environment Handler.
//!
//! This module handles command-not-found errors that occur while executing inside a Toolbx
//! container. Currently, this means that commands are forwarded to the host using `flatpak-spawn`.
//! If `flatpak-spawn` isn't present, an error is thrown instead.
use super::prelude::*;

use log;
use users::{get_current_gid, get_current_uid};

use std::{io::IsTerminal, path::Path};

const TOOLBX_ENV: &str = "/run/.toolboxenv";
const CONTAINER_ENV: &str = "/run/.containerenv";
const OS_RELEASE: &str = "/etc/os-release";

#[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Toolbx {
    name: String,
}

impl fmt::Display for Toolbx {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "toolbx '{}'", self.name)
    }
}

impl Toolbx {
    /// Spawn a Toolbx container with a given name.
    ///
    /// Checks if the toolbx container exists and starts it, if necessary. If `None` is given as
    /// name, will try to determine the default toolbx name and start that instead. Returns an
    /// error if unsuccessful.
    pub fn new(name: Option<String>) -> Result<Toolbx, NewToolbxError> {
        let name = match name {
            Some(name) if !name.is_empty() => name,
            _ => match Toolbx::default_name() {
                Ok(toolbx_name) => toolbx_name,
                Err(e) => return Err(NewToolbxError::UnknownDefault(e)),
            },
        };

        // Do an optimistic start:
        // - If the container exists and isn't started, it will be started
        // - If the container exists and is started, nothing happens
        // - If the container doesn't exist, we get an error and report that
        let output = std::process::Command::new("podman")
            .args(["start", &name])
            .output()
            .map_err(|e| match e.kind() {
                std::io::ErrorKind::NotFound => NewToolbxError::NeedPodman,
                _ => NewToolbxError::IoError(e),
            })?;
        if output.status.success() {
            // All good
            Ok(Toolbx { name })
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.starts_with("Error: no container with name or ID")
                && stderr.contains("found: no such container")
            {
                Err(NewToolbxError::NonExistent(name))
            } else {
                Err(NewToolbxError::Podman(output))
            }
        }
    }

    /// Get the Toolbx container currently executing CNF.
    ///
    /// Will return an error if the current execution environment isn't Toolbx.
    pub fn current() -> Result<Toolbx, CurrentToolbxError> {
        if !detect() {
            return Err(CurrentToolbxError::NotAToolbx);
        }

        let content = std::fs::read_to_string(CONTAINER_ENV).map_err(|e| {
            CurrentToolbxError::Environment {
                env_file: CONTAINER_ENV.to_string(),
                source: e,
            }
        })?;
        let name = content
            .lines()
            .find(|line| line.contains("name=\""))
            .ok_or_else(|| CurrentToolbxError::Name(CONTAINER_ENV.to_string()))?
            .trim_start_matches("name=\"")
            .trim_end_matches('"');

        Ok(Toolbx {
            name: name.to_string(),
        })
    }

    /// Get the name of the default toolbx to lookup/execute commands in.
    ///
    /// The default toolbx container name is assembled from the contents of `/etc/os-release`.
    pub fn default_name() -> Result<String, DefaultToolbxError> {
        // Construct default toolbox name by hand. Format is $ID-toolbox-$VERSION_ID, with ID
        // and VERSION_ID taken from /etc/os-release. See here:
        // https://containertoolbx.org/distros/
        log::debug!("Determining default toolbx name via {}", OS_RELEASE);

        let content =
            std::fs::read_to_string(OS_RELEASE).map_err(|e| DefaultToolbxError::UnknownOs {
                file: OS_RELEASE.to_string(),
                source: e,
            })?;
        let id = content
            .lines()
            .find(|line| line.starts_with("ID="))
            .map(|line| line.trim_start_matches("ID=").trim_matches('"'))
            .ok_or(DefaultToolbxError::Id)?;
        let version_id = content
            .lines()
            .find(|line| line.starts_with("VERSION_ID="))
            .map(|line| line.trim_start_matches("VERSION_ID=").trim_matches('"'))
            .ok_or(DefaultToolbxError::VersionId)?;

        Ok(format!("{}-toolbox-{}", id, version_id))
    }
}

impl environment::IsEnvironment for Toolbx {
    type Err = Error;

    fn exists(&self) -> bool {
        if detect() {
            true
        } else if let Environment::Host(host) = environment::current() {
            host.execute(crate::environment::cmd!("toolbox", "--version"))
                .map(|mut cmd| {
                    async_std::task::block_on(async move {
                        cmd.stdout(async_process::Stdio::null())
                            .stderr(async_process::Stdio::null())
                            .status()
                            .await
                            .map(|status| status.success())
                            .unwrap_or(false)
                    })
                })
                .unwrap_or(false)
        } else {
            false
        }
    }

    fn execute(&self, command: CommandLine) -> Result<Command, Self::Err> {
        log::debug!("Executing command '{}' in toolbx '{}'", command, self.name);

        let mut cmd: Command;
        match environment::current() {
            Environment::Distrobox(_) => {
                return Err(Error::Unimplemented(
                    "running in a toolbx from a distrobox".to_string(),
                ));
            }
            Environment::Toolbx(t) => {
                if self == &t {
                    // This is the toolbx container we are currently running in
                    // We expect toolbx containers to *always* run a unix OS, or at least something
                    // that has `sudo`.
                    if command.get_privileged() {
                        cmd = Command::new("sudo");
                        if !command.get_interactive() {
                            cmd.arg("-n");
                        }

                        cmd.arg(command.command());
                    } else {
                        cmd = Command::new(command.command());
                    }

                    cmd.args(command.args());
                } else {
                    return Err(Error::Unimplemented(
                        "running in a toolbx from another toolbx".to_string(),
                    ));
                }
            }
            Environment::Host(_) => {
                cmd = Command::new("podman");

                cmd.args(["exec", "-i"]);
                // The toolbx container by default isn't launched with the `--user` option, we must
                // take care of this ourselves.
                cmd.arg("--user");
                cmd.arg(format!("{}:{}", get_current_uid(), get_current_gid()));
                // Fix the working directory
                cmd.arg("--workdir");
                cmd.arg(std::env::current_dir().map_err(Error::UnknownCwd)?);
                // Keep some env vars
                for var in environment::read_env_vars() {
                    cmd.args(["-e", &var]);
                }

                // Only attach to the tty if we really have a tty, too
                // FIXME: Is this really the correct way to check?
                if std::io::stdout().is_terminal() && std::io::stdin().is_terminal() {
                    cmd.arg("-t");
                }

                // Can't run command in toolbx if we don't have one
                cmd.arg(&self.name);

                // This is the real command we're looking for (with arguments)
                if command.get_privileged() {
                    cmd.args(["sudo", "-S", "-E"]);
                    // NOTE: We ignore `get_interactive` here. because toolbox seems to do weird
                    // things regarding sudo. When adding the `-n` flag to request non-interactive
                    // auth, sudo will fail, requiring a pssword. However, factually running `sudo`
                    // in a toolbx container *does not* require a password under normal
                    // circumstances. Just ignoring interactivity here solves this issue (but don't
                    // ask me why).
                }

                cmd.arg(command.command()).args(command.args());

                log::debug!("Calling: {:?}", cmd);
            }
            #[cfg(test)]
            Environment::Mock(_) => unimplemented!(),
        }
        Ok(cmd)
    }
}

/// Detect if the current execution environment is a Toolbx container.
///
/// Checks for the presence of the `.toolboxenv` files.
pub fn detect() -> bool {
    Path::new(TOOLBX_ENV).exists()
}

#[derive(Debug, ThisError)]
pub enum NewToolbxError {
    #[error("working with toolbx containers requires the 'podman' executable")]
    NeedPodman,

    #[error("podman exited with non-zero code: {0:#?}")]
    Podman(std::process::Output),

    #[error("no toolbx with name {0} exists")]
    NonExistent(String),

    #[error("unknown I/O error occured")]
    IoError(#[from] std::io::Error),

    #[error("failed to determine default toolbx name")]
    UnknownDefault(#[from] DefaultToolbxError),
}

#[derive(Debug, ThisError)]
pub enum CurrentToolbxError {
    #[error("cannot read toolbx info from environment file '{env_file}'")]
    Environment {
        env_file: String,
        source: std::io::Error,
    },

    #[error("program currently isn't run from a toolbx")]
    NotAToolbx,

    #[error("failed to read toolbx name from environment file '{0}'")]
    Name(String),
}

#[derive(Debug, ThisError)]
pub enum DefaultToolbxError {
    #[error("failed to read OS information from '{file}'")]
    UnknownOs {
        file: String,
        source: std::io::Error,
    },

    #[error("cannot determine OS ID from os-release info")]
    Id,

    #[error("cannot determine OS VERSION_ID from os-release info")]
    VersionId,
}

#[derive(Debug, ThisError)]
pub enum Error {
    #[error("cannot determine current working directory")]
    UnknownCwd(#[from] std::io::Error),

    #[error("not implemented: {0}")]
    Unimplemented(String),
}