Skip to main content

isothrum_machine/install/
linux.rs

1//! Installs and removals on Linux: one root script each ([`RootScript`]), run as root as the
2//! [`Elevation`] says, through apt and the vendors' apt repositories or dnf and the vendors' rpm
3//! repositories ([`scripts`]).
4
5use crate::host::{Arch, HostOs, LinuxPackages, Packages};
6use crate::install::root::RootScript;
7use crate::install::steps::Step;
8use crate::install::{Dependency, Elevation, Item, Refusal};
9
10pub mod scripts;
11
12use scripts::{
13    awscli_script, azurecli_script, docker_dnf_script, docker_script, gcloud_script, libvirt_dnf_script, libvirt_script, qemu_dnf_script, qemu_script,
14    terraform_dnf_script, terraform_script, vagrant_dnf_script, vagrant_script, virtualbox_dnf_script, virtualbox_script, vmware_utility_script,
15};
16
17/// The proxy variables a root step is handed: apt and curl need them behind a corporate proxy, and
18/// pkexec clears the environment.
19pub const PROXY_VARS: [&str; 6] = ["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"];
20
21/// The proxy variables `var` reads that are set, as `NAME=value` (what a root step is handed).
22pub fn proxy_assignments(var: impl Fn(&str) -> Option<String>) -> Vec<String> {
23    PROXY_VARS
24        .into_iter()
25        .filter_map(|name| var(name).filter(|v| !v.is_empty()).map(|v| format!("{name}={v}")))
26        .collect()
27}
28
29/// How root steps run here: elevated as `elevation` says, with the proxy variables `proxy`
30/// (`NAME=value`, [`proxy_assignments`]).
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct Root {
33    /// How a step is elevated.
34    pub elevation: Elevation,
35    /// The proxy variables handed to it.
36    pub proxy: Vec<String>,
37}
38
39impl Root {
40    /// Root steps run `elevation`'s way, handed this process's proxy variables.
41    pub(crate) fn with_this_proxy(elevation: Elevation) -> Root {
42        Root {
43            elevation,
44            proxy: proxy_assignments(|name| std::env::var(name).ok()),
45        }
46    }
47
48    /// `script` run as root. The proxy variables go in an owner-only file in a private folder
49    /// kept as long as the step, which the script reads right after its prelude: on pkexec's
50    /// command line, which every local user can read (`ps`, `/proc/<pid>/cmdline`) while the
51    /// prompt is up, a proxy's password would show.
52    ///
53    /// # Errors
54    ///
55    /// [`Refusal::PrivateFile`] when that file can't be written.
56    pub fn step(&self, script: RootScript) -> Result<Step, Refusal> {
57        let root = |text: String| {
58            let (program, args) = self.elevation.as_root("env", &["sh".into(), "-c".into(), text]);
59            Step {
60                program,
61                args,
62                note: None,
63                interactions: Vec::new(),
64                private: None,
65                not_served: None,
66            }
67        };
68        // A value over two lines can't be one line of the file; no proxy has one.
69        let proxy: Vec<&str> = self.proxy.iter().map(String::as_str).filter(|a| !a.contains(['\n', '\r'])).collect();
70        if proxy.is_empty() {
71            return Ok(root(script.into_string()));
72        }
73        let (dir, file) = private_file(&proxy).map_err(|e| Refusal::PrivateFile(e.to_string()))?;
74        let mut step = root(script.with_after_prelude(&read_proxy(&file)));
75        step.private = Some(dir);
76        Ok(step)
77    }
78}
79
80/// An owner-only folder (mode 0700 from its creation, under a name no one can take first) holding
81/// the owner-only file `proxy` (0600), one variable a line.
82fn private_file(proxy: &[&str]) -> std::io::Result<(tempfile::TempDir, std::path::PathBuf)> {
83    let mut private = tempfile::Builder::new();
84    private.prefix("isothrum-root-");
85    #[cfg(unix)]
86    private.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
87    let dir = private.tempdir()?;
88    let file = dir.path().join("proxy");
89    let mut lines = proxy.join("\n");
90    lines.push('\n');
91    let mut options = std::fs::OpenOptions::new();
92    options.write(true).create_new(true);
93    // Owner-only from its creation.
94    #[cfg(unix)]
95    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
96    std::io::Write::write_all(&mut options.open(&file)?, lines.as_bytes())?;
97    Ok((dir, file))
98}
99
100/// The shell that exports the proxy variables `file` lists (`NAME=value`, one a line), read as
101/// data: a line naming anything but a proxy variable is skipped, and nothing in a value is run.
102fn read_proxy(file: &std::path::Path) -> String {
103    let names = PROXY_VARS.map(|name| format!("{name}=*")).join("|");
104    let quoted = format!("'{}'", file.to_string_lossy().replace('\'', r"'\''"));
105    format!(r#"while IFS= read -r v; do case "$v" in {names}) export "$v" ;; esac; done < {quoted}"#)
106}
107
108/// The Linux distribution's package manager `packages` names, or why nothing installs without one.
109fn linux(dependency: Dependency, packages: Option<Packages>) -> Result<LinuxPackages, Refusal> {
110    packages.and_then(Packages::linux).ok_or(Refusal::WithoutPackages { dependency })
111}
112
113/// The install of `dep` on Linux on a CPU `arch`, as root, for the user `user` (joined to the
114/// groups a tool's devices need): apt and the vendors' apt repositories, or dnf and the vendors'
115/// rpm repositories. A tool its vendor ships no build of for `arch` is refused
116/// ([`Dependency::no_build`]), before the package manager is looked at.
117///
118/// # Errors
119///
120/// [`Refusal`]: why it can't be installed here.
121pub fn install(dep: Dependency, packages: Option<Packages>, arch: Arch, user: Option<&str>, root: &Root) -> Result<Vec<Step>, Refusal> {
122    dep.runs_here(HostOs::Linux)?;
123    if let Some(why) = dep.no_build(HostOs::Linux, arch) {
124        return Err(Refusal::NoBuild {
125            dependency: dep,
126            os: HostOs::Linux,
127            arch,
128            why,
129        });
130    }
131    let packages = linux(dep, packages)?;
132    let script = match (dep, packages) {
133        (Dependency::Wsl | Dependency::Hyperv | Dependency::Utm, _) => {
134            return Err(Refusal::NotHere {
135                dependency: dep,
136                os: HostOs::Linux,
137            });
138        }
139        // From HashiCorp's apt repository, not the distribution's (older than projects need).
140        (Dependency::Vagrant, LinuxPackages::Apt) => vagrant_script(),
141        (Dependency::Vagrant, LinuxPackages::Dnf) => vagrant_dnf_script(),
142        (Dependency::Docker, LinuxPackages::Apt) => docker_script(user),
143        (Dependency::Docker, LinuxPackages::Dnf) => docker_dnf_script(user),
144        (Dependency::Terraform, LinuxPackages::Apt) => terraform_script(),
145        (Dependency::Terraform, LinuxPackages::Dnf) => terraform_dnf_script(),
146        // Fedora: RPM Fusion's VirtualBox, the distribution's libvirt and QEMU.
147        (Dependency::Virtualbox, LinuxPackages::Apt) => virtualbox_script(),
148        (Dependency::Virtualbox, LinuxPackages::Dnf) => virtualbox_dnf_script(user),
149        // The user joins /dev/kvm's group: VMs boot with KVM.
150        (Dependency::Qemu, LinuxPackages::Apt) => qemu_script(user),
151        (Dependency::Qemu, LinuxPackages::Dnf) => qemu_dnf_script(user),
152        (Dependency::Libvirt, LinuxPackages::Apt) => libvirt_script(user),
153        (Dependency::Libvirt, LinuxPackages::Dnf) => libvirt_dnf_script(user),
154        // AWS CLI v2 from Amazon's signed bundle, in a private temporary directory: no package
155        // manager's.
156        (Dependency::Awscli, LinuxPackages::Apt | LinuxPackages::Dnf) => awscli_script(),
157        // Azure CLI and gcloud from Microsoft's and Google's apt repositories, their keys pinned;
158        // through apt only for now, as VMware's utility.
159        (Dependency::Azurecli, LinuxPackages::Apt) => azurecli_script(),
160        (Dependency::Gcloud, LinuxPackages::Apt) => gcloud_script(),
161        (Dependency::VmwareUtility, LinuxPackages::Apt) => vmware_utility_script(),
162        (Dependency::Azurecli | Dependency::Gcloud | Dependency::VmwareUtility, LinuxPackages::Dnf) => return Err(Refusal::AptOnly { dependency: dep }),
163    };
164    let step = root.step(script)?;
165    // Docker's install stops, changing nothing, outside the distributions it serves.
166    Ok(vec![if dep == Dependency::Docker {
167        step.not_served(super::steps::NotServed::DockerDistribution)
168    } else {
169        step
170    }])
171}
172
173/// The removal on Linux, as root, of what `added` lists of `dep` ([`Item`], as an install's
174/// record has it), and of nothing else: those of its packages ([`super::added::packages`]: a name
175/// on record that isn't one of them is never removed) through the package manager that installed
176/// them (a tool installed through dnf removed with `apt-get remove` failed with `apt-get: not
177/// found`); the AWS CLI's folder when the install added it. The package manager would take away
178/// with them every package that needs one of them, whoever installed it: the removal stops,
179/// removing nothing, when it would (`removal_script`).
180///
181/// # Errors
182///
183/// [`Refusal::NothingAdded`] when `added` lists nothing of `dep`'s, or why it can't be removed
184/// here.
185pub fn uninstall(dep: Dependency, packages: Option<Packages>, added: &[Item], root: &Root) -> Result<Vec<Step>, Refusal> {
186    dep.runs_here(HostOs::Linux)?;
187    // AWS CLI is a folder on every distribution.
188    if dep == Dependency::Awscli {
189        return if added.contains(&Item::Tool(dep)) {
190            Ok(vec![root.step(RootScript::new(AWS_CLI_REMOVAL))?])
191        } else {
192            Err(Refusal::NothingAdded { dependency: dep })
193        };
194    }
195    let manager = linux(dep, packages)?;
196    let own = super::added::packages(dep, manager);
197    let names: Vec<&str> = added
198        .iter()
199        .filter_map(|item| match item {
200            Item::Package(name) if package_name(name) && own.iter().any(|p| super::added::matches(p, name)) => Some(name.as_str()),
201            _ => None,
202        })
203        .collect();
204    if names.is_empty() {
205        return Err(Refusal::NothingAdded { dependency: dep });
206    }
207    Ok(vec![root.step(removal_script(manager, &names))?])
208}
209
210/// A package's name a script may carry unquoted: letters, digits and `+-._`, starting with a
211/// letter or a digit (never an option).
212fn package_name(name: &str) -> bool {
213    name.len() <= 128
214        && name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric())
215        && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.' | '_'))
216}
217
218/// The root script that removes the packages `names` (each a [`package_name`]) through
219/// `manager`, after checking it would remove nothing else: apt's simulated removal names every
220/// package it would take away (`Remv`), rpm's test refuses a package another needs. Either way,
221/// another package that needs one of them stops the removal before anything is removed.
222fn removal_script(manager: LinuxPackages, names: &[&str]) -> RootScript {
223    let list = names.join(" ");
224    match manager {
225        LinuxPackages::Apt => {
226            let ours: String = names.iter().flat_map(|n| [" -e ", n]).collect();
227            RootScript::new(format!(
228                r#"extra="$(apt-get -s remove {list} | awk '/^Remv /{{print $2}}' | sed 's/:.*//' | grep -vxF{ours} || true)"; if [ -n "$extra" ]; then echo "Removing $(echo {list}) would also remove packages that need them: $(echo $extra). Nothing was removed." >&2; exit 1; fi; apt-get remove -y {list}"#
229            ))
230        }
231        LinuxPackages::Dnf => RootScript::new(format!(
232            r#"if ! rpm -e --test {list}; then echo "Other packages need $(echo {list}). Nothing was removed." >&2; exit 1; fi; dnf remove -y {list}"#
233        )),
234    }
235}
236
237/// The AWS CLI's removal: its folder and its two links.
238const AWS_CLI_REMOVAL: &str = "rm -rf /usr/local/aws-cli /usr/local/bin/aws /usr/local/bin/aws_completer";
239
240#[cfg(test)]
241mod tests;