Skip to main content

isothrum_machine/tools/
ovftool.rs

1//! VMware's OVF Tool (`ovftool`), which the ESXi Vagrant plugin uploads VMs with. It isn't
2//! installed the way the other tools are: it comes inside VMware Fusion (Workstation on Windows),
3//! or as a standalone download from Broadcom, which unpacks to a loose folder nothing looks in
4//! (and, on macOS, quarantined). [`place`] copies such a folder, once verified as VMware's, into a
5//! folder the caller keeps (its own tools folder, which it puts on its `PATH`).
6//!
7//! [`locate`] finds the one to report, in this order: a hypervisor's own copy
8//! ([`crate::host::Devices::ovftool`]), then the caller's folder, then the first on the `PATH` it
9//! passes. [`probe`] asks the found file its version, and says whether it can't run until Rosetta
10//! is installed.
11//!
12//! Every program (the tool itself, `codesign`, `xattr`) runs through the context's runner; the
13//! signature check and the quarantine are macOS's, chosen by the context's host, never by the OS
14//! the crate is built for.
15
16use std::ffi::OsStr;
17use std::path::{Component, Path, PathBuf};
18use std::time::{Duration, SystemTime};
19
20use serde::Serialize;
21
22use self::mach_o::{cpus, head, intel_only, mach_o_files};
23use super::{Tool, first_line};
24use crate::context::Context;
25use crate::failure::{self, Failure};
26use crate::host::{Arch, HostOs};
27
28mod mach_o;
29#[cfg(test)]
30mod tests;
31
32/// The team identifier of VMware's Apple Developer ID (Broadcom still signs with it).
33pub const VMWARE_TEAM: &str = "EG7KH642X6";
34
35/// macOS's `codesign`, by its path: the system's own, never one on `PATH`.
36const CODESIGN: &str = "/usr/bin/codesign";
37
38/// macOS's `xattr`, by its path.
39const XATTR: &str = "/usr/bin/xattr";
40
41/// The most a picked folder may hold: the tool is about 60 files and 60 MB, so anything far
42/// bigger is the wrong folder (a whole Downloads folder holding it), not a copy to make.
43const MAX_FILES: usize = 2_000;
44const MAX_BYTES: u64 = 1 << 30;
45
46/// A placement left behind by a crash (a copy being made, or one being replaced) is removed once
47/// it is this old: younger, it may be another placement still running.
48const LEFTOVER_AFTER: Duration = Duration::from_secs(600);
49
50/// What the names of a placement's own folders start with, beside the placed one.
51const WORK_PREFIX: &str = ".ovftool-";
52
53/// The tool's file name on `os`.
54#[must_use]
55pub fn exe(os: HostOs) -> &'static str {
56    match os {
57        HostOs::Windows => "ovftool.exe",
58        HostOs::Macos | HostOs::Linux => "ovftool",
59    }
60}
61
62/// The OVF Tool folder inside VMware Workstation, installed under the Program Files folder `pf`.
63#[must_use]
64pub fn workstation_dir(pf: &Path) -> PathBuf {
65    pf.join("VMware").join("VMware Workstation").join("OVFTool")
66}
67
68/// Where the OVF Tool found comes from.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
70#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolSource"))]
71#[serde(rename_all = "camelCase")]
72pub enum Source {
73    /// Inside VMware Fusion (macOS).
74    Fusion,
75    /// Inside VMware Workstation (Windows).
76    Workstation,
77    /// The copy placed in the caller's folder ([`place`]).
78    Managed,
79    /// The first on `PATH`.
80    Path,
81}
82
83/// The OVF Tool found: where it comes from and its file.
84#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
85#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolLocation"))]
86#[serde(rename_all = "camelCase")]
87pub struct Location {
88    /// Where it comes from.
89    pub source: Source,
90    /// The program's path.
91    pub path: String,
92    /// It is built for Intel Macs only, this Mac has Apple silicon and Rosetta isn't installed:
93    /// it can't run until Rosetta is (`softwareupdate --install-rosetta`).
94    pub needs_rosetta: bool,
95}
96
97/// Why a picked folder wasn't placed.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
99#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolRefusal"))]
100#[serde(rename_all = "camelCase")]
101pub enum Refusal {
102    /// No `ovftool` program in the folder (nor in the one folder inside it).
103    NoTool,
104    /// The program is there, but not its libraries (`lib/` beside it): a partial copy.
105    NoLibraries,
106    /// The folder holds far more than the tool: the wrong folder.
107    TooLarge,
108    /// macOS: a program or library in it isn't validly signed.
109    Unsigned,
110    /// macOS: it is signed, but not by VMware.
111    NotVmware,
112}
113
114/// What [`place`] did with the picked folder.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolPlaced"))]
117#[serde(tag = "outcome", rename_all = "camelCase", rename_all_fields = "camelCase")]
118pub enum Outcome {
119    /// Copied into the caller's folder, where the next [`locate`] finds it.
120    Placed {
121        /// The placed program's path.
122        path: String,
123        /// Whether it can't run until Rosetta is installed (see [`Location::needs_rosetta`]).
124        needs_rosetta: bool,
125    },
126    /// Not placed, for `reason`.
127    Refused {
128        /// Why it wasn't placed.
129        reason: Refusal,
130        /// What macOS said of the signature, or the team that signed it instead of VMware, when
131        /// known.
132        detail: Option<String>,
133    },
134}
135
136impl Outcome {
137    fn refused(reason: Refusal, detail: Option<String>) -> Outcome {
138        Outcome::Refused { reason, detail }
139    }
140}
141
142/// Why [`place`] couldn't finish: not a folder that isn't VMware's OVF Tool (that is an
143/// [`Outcome::Refused`]), but a copy that couldn't be made or swapped in, or a check that couldn't
144/// run.
145#[derive(Debug)]
146#[non_exhaustive]
147pub enum PlaceError {
148    /// Copying, or swapping the copy in, failed (a full disk, a permission).
149    Io(std::io::Error),
150    /// A signature check or the quarantine's removal couldn't be run, or `xattr` failed.
151    Tool(Failure),
152    /// A path isn't UTF-8, so it can't be handed to a tool as an argument.
153    NotUtf8(PathBuf),
154}
155
156impl std::fmt::Display for PlaceError {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        match self {
159            PlaceError::Io(e) => write!(f, "couldn't place the OVF Tool: {e}"),
160            PlaceError::Tool(e) => write!(f, "couldn't check the OVF Tool: {e}"),
161            PlaceError::NotUtf8(p) => write!(f, "the path {} isn't UTF-8", p.display()),
162        }
163    }
164}
165
166impl std::error::Error for PlaceError {
167    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
168        match self {
169            PlaceError::Io(e) => Some(e),
170            PlaceError::Tool(e) => Some(e),
171            PlaceError::NotUtf8(_) => None,
172        }
173    }
174}
175
176impl From<std::io::Error> for PlaceError {
177    fn from(e: std::io::Error) -> PlaceError {
178        PlaceError::Io(e)
179    }
180}
181
182/// The hypervisor a copy in [`crate::host::Devices::ovftool`] comes with on `os`.
183fn bundled_source(os: HostOs) -> Source {
184    match os {
185        HostOs::Windows => Source::Workstation,
186        HostOs::Macos | HostOs::Linux => Source::Fusion,
187    }
188}
189
190/// The OVF Tool to report, in order: a hypervisor's own copy, the one in `managed` (the caller's
191/// folder [`place`] copies into), then the first on `path` (the caller's `PATH`). None when there
192/// is none.
193#[must_use]
194pub fn locate(cx: &Context, managed: Option<&Path>, path: Option<&OsStr>) -> Option<(Source, PathBuf)> {
195    let exe = exe(cx.host.os);
196    let bundled = cx.host.devices.ovftool.iter().map(|f| (bundled_source(cx.host.os), f.clone()));
197    let managed = managed.map(|d| (Source::Managed, d.join(exe)));
198    let found = bundled.chain(managed).find(|(_, f)| f.is_file());
199    found.or_else(|| {
200        let on_path = std::env::split_paths(path?).map(|d| d.join(exe)).find(|f| f.is_file())?;
201        Some((Source::Path, on_path))
202    })
203}
204
205/// What a machine check reports of the OVF Tool: its version (when `--version` runs) and where
206/// it was found ([`locate`]).
207pub async fn probe(cx: &Context, managed: Option<&Path>, path: Option<&OsStr>) -> (Tool, Option<Location>) {
208    let Some((source, file)) = locate(cx, managed, path) else {
209        return (Tool::MISSING, None);
210    };
211    let tool = version_of(cx, &file).await;
212    let location = Location {
213        source,
214        path: file.display().to_string(),
215        needs_rosetta: needs_rosetta(cx, &file),
216    };
217    (tool, Some(location))
218}
219
220/// The OVF Tool's version, or why it can't be used, from what [`probe`] found: the tool's
221/// answer, and where it is.
222///
223/// # Errors
224///
225/// Why it can't be used: built for Intel Macs and Rosetta missing, found but not running, or not
226/// found.
227pub fn usable(tool: Tool, location: Option<&Location>) -> Result<String, String> {
228    match (tool, location) {
229        (Tool { installed: true, version }, _) => Ok(version.unwrap_or_else(|| "ovftool".into())),
230        (_, Some(at)) if at.needs_rosetta => Err(format!("VMware's OVF Tool at {} is built for Intel Macs and needs Rosetta", at.path)),
231        (_, Some(at)) => Err(format!("VMware's OVF Tool at {} doesn't run", at.path)),
232        (_, None) => Err("VMware's OVF Tool (`ovftool`) wasn't found (it comes with VMware Fusion or Workstation)".into()),
233    }
234}
235
236/// `ovftool --version` of the program `file`, run by its path so it is that file that answers:
237/// installed when it exits 0, its version the first line it printed.
238pub async fn version_of(cx: &Context, file: &Path) -> Tool {
239    match cx.read_ok(&file.to_string_lossy(), &["--version"]).await {
240        Ok(out) => Tool::installed(first_line(&out)),
241        Err(_) => Tool::MISSING,
242    }
243}
244
245/// Places the OVF Tool unpacked at `picked` (the folder holding `ovftool`, or the one folder
246/// inside it that does) at `dest`, the caller's folder for it, replacing an earlier copy: it is
247/// copied first (beside `dest`, so swapping it in is a rename), the copy checked (on macOS,
248/// signed by VMware, its quarantine then lifted), and only then swapped in. The picked folder is
249/// only read.
250///
251/// # Errors
252///
253/// [`PlaceError`] when the copy can't be made or swapped in, or a check can't run. A folder that
254/// isn't VMware's OVF Tool is an [`Outcome::Refused`], not an error.
255pub async fn place(cx: &Context, picked: &Path, dest: &Path) -> Result<Outcome, PlaceError> {
256    let os = cx.host.os;
257    let Some(root) = tool_root(picked, exe(os)) else {
258        return Ok(Outcome::refused(Refusal::NoTool, None));
259    };
260    if !has_libraries(&root, os) {
261        return Ok(Outcome::refused(Refusal::NoLibraries, None));
262    }
263    let parent = dest.parent().map(Path::to_path_buf).unwrap_or_default();
264    std::fs::create_dir_all(&parent)?;
265    remove_leftovers(&parent);
266    let work = tempfile::Builder::new().prefix(&format!("{WORK_PREFIX}new-")).tempdir_in(&parent)?;
267    let staged = work.path().join("ovftool");
268    let copied = {
269        let (root, staged) = (root.clone(), staged.clone());
270        tokio::task::spawn_blocking(move || copy_tree(&root, &staged, &mut Budget::default()))
271            .await
272            .map_err(|e| std::io::Error::other(format!("copying the OVF Tool stopped: {e}")))?
273    };
274    // Whatever happens, `work` is removed when dropped: once swapped in, the copy isn't in it.
275    match copied {
276        Ok(()) => finish(cx, &staged, dest).await,
277        Err(e) if e.kind() == std::io::ErrorKind::FileTooLarge => Ok(Outcome::refused(Refusal::TooLarge, None)),
278        Err(e) => Err(e.into()),
279    }
280}
281
282/// Checks the copy `staged` and swaps it in at `dest`: the checks run on the copy, so what was
283/// checked is exactly what is placed.
284async fn finish(cx: &Context, staged: &Path, dest: &Path) -> Result<Outcome, PlaceError> {
285    let exe = exe(cx.host.os);
286    if !is_program(&staged.join(exe)) {
287        return Ok(Outcome::refused(Refusal::NoTool, None));
288    }
289    // macOS only: Windows and Linux carry no such signature check, nor a quarantine.
290    if cx.host.os == HostOs::Macos {
291        if let Some((reason, detail)) = signature_refusal(cx, staged).await? {
292            return Ok(Outcome::refused(reason, detail));
293        }
294        lift_quarantine(cx, staged).await?;
295    }
296    swap_in(staged, dest)?;
297    let placed = dest.join(exe);
298    Ok(Outcome::Placed {
299        path: placed.display().to_string(),
300        needs_rosetta: needs_rosetta(cx, &placed),
301    })
302}
303
304/// The folder holding the tool `exe`: `picked` itself, or the one folder inside it that holds it
305/// (the Windows and Linux downloads unpack into an `ovftool` folder).
306fn tool_root(picked: &Path, exe: &str) -> Option<PathBuf> {
307    if picked.join(exe).is_file() {
308        return Some(picked.to_path_buf());
309    }
310    let inside: Vec<PathBuf> = std::fs::read_dir(picked)
311        .ok()?
312        .flatten()
313        .map(|e| e.path())
314        .filter(|p| p.is_dir() && p.join(exe).is_file())
315        .collect();
316    match inside.as_slice() {
317        [one] => Some(one.clone()),
318        _ => None,
319    }
320}
321
322/// Whether the tool at `root` has its libraries: a `lib/` folder beside it (macOS, and the newer
323/// Linux downloads), or, on Windows and Linux, the libraries themselves beside it.
324fn has_libraries(root: &Path, os: HostOs) -> bool {
325    if root.join("lib").is_dir() {
326        return true;
327    }
328    let library = |name: &str| match os {
329        HostOs::Windows => name.to_ascii_lowercase().ends_with(".dll"),
330        HostOs::Linux => name.contains(".so"),
331        HostOs::Macos => false,
332    };
333    std::fs::read_dir(root).is_ok_and(|entries| entries.flatten().any(|e| library(&e.file_name().to_string_lossy())))
334}
335
336/// Whether `file` is a program this OS will start: a file, executable on Unix.
337fn is_program(file: &Path) -> bool {
338    let Ok(meta) = std::fs::metadata(file) else {
339        return false;
340    };
341    #[cfg(unix)]
342    {
343        use std::os::unix::fs::PermissionsExt as _;
344        meta.is_file() && meta.permissions().mode() & 0o111 != 0
345    }
346    #[cfg(not(unix))]
347    {
348        meta.is_file()
349    }
350}
351
352/// What a copy may still take, so a wrong folder (a whole Downloads) isn't copied whole.
353struct Budget {
354    files: usize,
355    bytes: u64,
356}
357
358impl Default for Budget {
359    fn default() -> Budget {
360        Budget {
361            files: MAX_FILES,
362            bytes: MAX_BYTES,
363        }
364    }
365}
366
367impl Budget {
368    /// Takes one entry of `len` bytes; `FileTooLarge` once the budget is spent.
369    fn take(&mut self, len: u64) -> std::io::Result<()> {
370        if self.files == 0 || len > self.bytes {
371            return Err(std::io::Error::new(
372                std::io::ErrorKind::FileTooLarge,
373                "the folder holds far more than the OVF Tool",
374            ));
375        }
376        self.files -= 1;
377        self.bytes -= len;
378        Ok(())
379    }
380}
381
382/// Copies the folder `from` to `to` (a new folder), its files with their permissions. A symbolic
383/// link is copied as one when it points inside its own folder (the versioned names of a Linux
384/// library); any other is left out.
385fn copy_tree(from: &Path, to: &Path, budget: &mut Budget) -> std::io::Result<()> {
386    std::fs::create_dir(to)?;
387    for entry in std::fs::read_dir(from)? {
388        let entry = entry?;
389        let (src, dst) = (entry.path(), to.join(entry.file_name()));
390        let kind = entry.file_type()?;
391        if kind.is_dir() {
392            budget.take(0)?;
393            copy_tree(&src, &dst, budget)?;
394        } else if kind.is_file() {
395            budget.take(entry.metadata()?.len())?;
396            std::fs::copy(&src, &dst)?;
397        } else if kind.is_symlink() {
398            budget.take(0)?;
399            copy_link(&src, &dst)?;
400        }
401    }
402    Ok(())
403}
404
405/// Copies the symbolic link `src` as `dst` when its target stays beside it (no `..`, not
406/// absolute); otherwise leaves it out (and every link, on Windows).
407fn copy_link(src: &Path, dst: &Path) -> std::io::Result<()> {
408    let target = std::fs::read_link(src)?;
409    let stays_inside = target.components().all(|c| matches!(c, Component::Normal(_)));
410    if !stays_inside {
411        return Ok(());
412    }
413    #[cfg(unix)]
414    {
415        std::os::unix::fs::symlink(target, dst)
416    }
417    #[cfg(not(unix))]
418    {
419        let _ = dst;
420        Ok(())
421    }
422}
423
424/// Swaps the folder `staged` in at `dest`: the earlier copy is moved aside, the new one renamed in
425/// its place (one rename each, on one file system), then the earlier one removed. If the new one
426/// can't go in, the earlier one is put back.
427fn swap_in(staged: &Path, dest: &Path) -> std::io::Result<()> {
428    let parent = dest.parent().unwrap_or_else(|| Path::new("."));
429    let aside_dir = tempfile::Builder::new().prefix(&format!("{WORK_PREFIX}old-")).tempdir_in(parent)?;
430    let aside = aside_dir.path().join("ovftool");
431    let had = match std::fs::rename(dest, &aside) {
432        Ok(()) => true,
433        Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
434        Err(e) => return Err(e),
435    };
436    if let Err(e) = std::fs::rename(staged, dest) {
437        if had {
438            std::fs::rename(&aside, dest).ok();
439        }
440        return Err(e);
441    }
442    // The earlier copy goes with `aside_dir`; one still running (Windows keeps its files locked)
443    // is removed with the next leftovers.
444    drop(aside_dir);
445    Ok(())
446}
447
448/// Removes, from `parent`, the folders an interrupted placement left behind (a copy being made,
449/// or one being replaced), once they are old enough not to be another placement's still running.
450fn remove_leftovers(parent: &Path) {
451    let Ok(entries) = std::fs::read_dir(parent) else {
452        return;
453    };
454    let now = SystemTime::now();
455    for entry in entries.flatten() {
456        let old = entry
457            .metadata()
458            .and_then(|m| m.modified())
459            .is_ok_and(|at| now.duration_since(at).unwrap_or_default() >= LEFTOVER_AFTER);
460        if entry.file_name().to_string_lossy().starts_with(WORK_PREFIX) && old {
461            std::fs::remove_dir_all(entry.path()).ok();
462        }
463    }
464}
465
466/// `path` as the text a tool's argument is.
467fn text(path: &Path) -> Result<&str, PlaceError> {
468    path.to_str().ok_or_else(|| PlaceError::NotUtf8(path.to_path_buf()))
469}
470
471/// macOS: why the copy `staged` isn't placed, when one of its programs or libraries isn't validly
472/// signed by VMware's team. Every Mach-O file in it is checked, so the quarantine lifted next is
473/// lifted from VMware's code only.
474///
475/// `codesign --verify --strict` checks the signature itself; with `-R`, that it chains to Apple
476/// and names VMware's team in its leaf certificate, which only Apple can issue. That is what
477/// decides; the team a refusal names comes from the signature's designated requirement
478/// (`-d -r-`).
479async fn signature_refusal(cx: &Context, staged: &Path) -> Result<Option<(Refusal, Option<String>)>, PlaceError> {
480    let requirement = format!("-R=anchor apple generic and certificate leaf[subject.OU] = \"{VMWARE_TEAM}\"");
481    for file in mach_o_files(staged) {
482        let shown = file.strip_prefix(staged).unwrap_or(&file).display().to_string();
483        let path = text(&file)?;
484        match failure::ask(cx, (CODESIGN, &["--verify", "--strict", path])).await {
485            Ok(_) => {}
486            Err(Failure::Refused { said, .. }) => return Ok(Some((Refusal::Unsigned, Some(format!("{shown}: {said}"))))),
487            Err(e) => return Err(PlaceError::Tool(e)),
488        }
489        match failure::ask(cx, (CODESIGN, &["--verify", "--strict", &requirement, path])).await {
490            Ok(_) => {}
491            Err(Failure::Refused { .. }) => {
492                let team = failure::ask(cx, (CODESIGN, &["-d", "-r-", path])).await.ok().and_then(|dr| signing_team(&dr));
493                return Ok(Some((Refusal::NotVmware, team)));
494            }
495            Err(e) => return Err(PlaceError::Tool(e)),
496        }
497    }
498    Ok(None)
499}
500
501/// The team a designated requirement (`codesign -d -r-`) names: its leaf certificate's
502/// organizational unit.
503fn signing_team(requirement: &str) -> Option<String> {
504    let (_, after) = requirement.split_once("leaf[subject.OU] = ")?;
505    let team: String = after.trim_start_matches('"').chars().take_while(char::is_ascii_alphanumeric).collect();
506    (!team.is_empty()).then_some(team)
507}
508
509/// macOS: lifts the quarantine from the copy `staged`, so Gatekeeper lets it run.
510///
511/// Only once [`signature_refusal`] passed on that very copy, and only on the copy: every program
512/// and library in it is verified as signed by VMware's Developer ID team. The tool isn't
513/// notarized (no hardened runtime), so with the quarantine on, Gatekeeper refuses to start it;
514/// with it lifted, it runs as VMware signed it. The picked download keeps its quarantine.
515async fn lift_quarantine(cx: &Context, staged: &Path) -> Result<(), PlaceError> {
516    failure::ask(cx, (XATTR, &["-d", "-r", "com.apple.quarantine", text(staged)?]))
517        .await
518        .map(drop)
519        .map_err(PlaceError::Tool)
520}
521
522/// Whether the program `file` can't run on the context's host until Rosetta is installed: it is
523/// built for Intel Macs only (the standalone OVF Tool is), the host is a Mac with Apple silicon,
524/// and Rosetta's runtime isn't there.
525fn needs_rosetta(cx: &Context, file: &Path) -> bool {
526    cx.host.os == HostOs::Macos && cx.host.arch == Arch::Arm64 && !cx.host.devices.rosetta_runtime.exists() && head(file).is_some_and(|h| intel_only(&cpus(&h)))
527}