use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};
use std::time::{Duration, SystemTime};
use serde::Serialize;
use self::mach_o::{cpus, head, intel_only, mach_o_files};
use super::{Tool, first_line};
use crate::context::Context;
use crate::failure::{self, Failure};
use crate::host::{Arch, HostOs};
mod mach_o;
#[cfg(test)]
mod tests;
pub const VMWARE_TEAM: &str = "EG7KH642X6";
const CODESIGN: &str = "/usr/bin/codesign";
const XATTR: &str = "/usr/bin/xattr";
const MAX_FILES: usize = 2_000;
const MAX_BYTES: u64 = 1 << 30;
const LEFTOVER_AFTER: Duration = Duration::from_secs(600);
const WORK_PREFIX: &str = ".ovftool-";
#[must_use]
pub fn exe(os: HostOs) -> &'static str {
match os {
HostOs::Windows => "ovftool.exe",
HostOs::Macos | HostOs::Linux => "ovftool",
}
}
#[must_use]
pub fn workstation_dir(pf: &Path) -> PathBuf {
pf.join("VMware").join("VMware Workstation").join("OVFTool")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolSource"))]
#[serde(rename_all = "camelCase")]
pub enum Source {
Fusion,
Workstation,
Managed,
Path,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolLocation"))]
#[serde(rename_all = "camelCase")]
pub struct Location {
pub source: Source,
pub path: String,
pub needs_rosetta: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolRefusal"))]
#[serde(rename_all = "camelCase")]
pub enum Refusal {
NoTool,
NoLibraries,
TooLarge,
Unsigned,
NotVmware,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(any(test, feature = "ts-rs"), derive(ts_rs::TS), ts(rename = "OvftoolPlaced"))]
#[serde(tag = "outcome", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum Outcome {
Placed {
path: String,
needs_rosetta: bool,
},
Refused {
reason: Refusal,
detail: Option<String>,
},
}
impl Outcome {
fn refused(reason: Refusal, detail: Option<String>) -> Outcome {
Outcome::Refused { reason, detail }
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum PlaceError {
Io(std::io::Error),
Tool(Failure),
NotUtf8(PathBuf),
}
impl std::fmt::Display for PlaceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PlaceError::Io(e) => write!(f, "couldn't place the OVF Tool: {e}"),
PlaceError::Tool(e) => write!(f, "couldn't check the OVF Tool: {e}"),
PlaceError::NotUtf8(p) => write!(f, "the path {} isn't UTF-8", p.display()),
}
}
}
impl std::error::Error for PlaceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
PlaceError::Io(e) => Some(e),
PlaceError::Tool(e) => Some(e),
PlaceError::NotUtf8(_) => None,
}
}
}
impl From<std::io::Error> for PlaceError {
fn from(e: std::io::Error) -> PlaceError {
PlaceError::Io(e)
}
}
fn bundled_source(os: HostOs) -> Source {
match os {
HostOs::Windows => Source::Workstation,
HostOs::Macos | HostOs::Linux => Source::Fusion,
}
}
#[must_use]
pub fn locate(cx: &Context, managed: Option<&Path>, path: Option<&OsStr>) -> Option<(Source, PathBuf)> {
let exe = exe(cx.host.os);
let bundled = cx.host.devices.ovftool.iter().map(|f| (bundled_source(cx.host.os), f.clone()));
let managed = managed.map(|d| (Source::Managed, d.join(exe)));
let found = bundled.chain(managed).find(|(_, f)| f.is_file());
found.or_else(|| {
let on_path = std::env::split_paths(path?).map(|d| d.join(exe)).find(|f| f.is_file())?;
Some((Source::Path, on_path))
})
}
pub async fn probe(cx: &Context, managed: Option<&Path>, path: Option<&OsStr>) -> (Tool, Option<Location>) {
let Some((source, file)) = locate(cx, managed, path) else {
return (Tool::MISSING, None);
};
let tool = version_of(cx, &file).await;
let location = Location {
source,
path: file.display().to_string(),
needs_rosetta: needs_rosetta(cx, &file),
};
(tool, Some(location))
}
pub fn usable(tool: Tool, location: Option<&Location>) -> Result<String, String> {
match (tool, location) {
(Tool { installed: true, version }, _) => Ok(version.unwrap_or_else(|| "ovftool".into())),
(_, Some(at)) if at.needs_rosetta => Err(format!("VMware's OVF Tool at {} is built for Intel Macs and needs Rosetta", at.path)),
(_, Some(at)) => Err(format!("VMware's OVF Tool at {} doesn't run", at.path)),
(_, None) => Err("VMware's OVF Tool (`ovftool`) wasn't found (it comes with VMware Fusion or Workstation)".into()),
}
}
pub async fn version_of(cx: &Context, file: &Path) -> Tool {
match cx.read_ok(&file.to_string_lossy(), &["--version"]).await {
Ok(out) => Tool::installed(first_line(&out)),
Err(_) => Tool::MISSING,
}
}
pub async fn place(cx: &Context, picked: &Path, dest: &Path) -> Result<Outcome, PlaceError> {
let os = cx.host.os;
let Some(root) = tool_root(picked, exe(os)) else {
return Ok(Outcome::refused(Refusal::NoTool, None));
};
if !has_libraries(&root, os) {
return Ok(Outcome::refused(Refusal::NoLibraries, None));
}
let parent = dest.parent().map(Path::to_path_buf).unwrap_or_default();
std::fs::create_dir_all(&parent)?;
remove_leftovers(&parent);
let work = tempfile::Builder::new().prefix(&format!("{WORK_PREFIX}new-")).tempdir_in(&parent)?;
let staged = work.path().join("ovftool");
let copied = {
let (root, staged) = (root.clone(), staged.clone());
tokio::task::spawn_blocking(move || copy_tree(&root, &staged, &mut Budget::default()))
.await
.map_err(|e| std::io::Error::other(format!("copying the OVF Tool stopped: {e}")))?
};
match copied {
Ok(()) => finish(cx, &staged, dest).await,
Err(e) if e.kind() == std::io::ErrorKind::FileTooLarge => Ok(Outcome::refused(Refusal::TooLarge, None)),
Err(e) => Err(e.into()),
}
}
async fn finish(cx: &Context, staged: &Path, dest: &Path) -> Result<Outcome, PlaceError> {
let exe = exe(cx.host.os);
if !is_program(&staged.join(exe)) {
return Ok(Outcome::refused(Refusal::NoTool, None));
}
if cx.host.os == HostOs::Macos {
if let Some((reason, detail)) = signature_refusal(cx, staged).await? {
return Ok(Outcome::refused(reason, detail));
}
lift_quarantine(cx, staged).await?;
}
swap_in(staged, dest)?;
let placed = dest.join(exe);
Ok(Outcome::Placed {
path: placed.display().to_string(),
needs_rosetta: needs_rosetta(cx, &placed),
})
}
fn tool_root(picked: &Path, exe: &str) -> Option<PathBuf> {
if picked.join(exe).is_file() {
return Some(picked.to_path_buf());
}
let inside: Vec<PathBuf> = std::fs::read_dir(picked)
.ok()?
.flatten()
.map(|e| e.path())
.filter(|p| p.is_dir() && p.join(exe).is_file())
.collect();
match inside.as_slice() {
[one] => Some(one.clone()),
_ => None,
}
}
fn has_libraries(root: &Path, os: HostOs) -> bool {
if root.join("lib").is_dir() {
return true;
}
let library = |name: &str| match os {
HostOs::Windows => name.to_ascii_lowercase().ends_with(".dll"),
HostOs::Linux => name.contains(".so"),
HostOs::Macos => false,
};
std::fs::read_dir(root).is_ok_and(|entries| entries.flatten().any(|e| library(&e.file_name().to_string_lossy())))
}
fn is_program(file: &Path) -> bool {
let Ok(meta) = std::fs::metadata(file) else {
return false;
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
meta.is_file() && meta.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{
meta.is_file()
}
}
struct Budget {
files: usize,
bytes: u64,
}
impl Default for Budget {
fn default() -> Budget {
Budget {
files: MAX_FILES,
bytes: MAX_BYTES,
}
}
}
impl Budget {
fn take(&mut self, len: u64) -> std::io::Result<()> {
if self.files == 0 || len > self.bytes {
return Err(std::io::Error::new(
std::io::ErrorKind::FileTooLarge,
"the folder holds far more than the OVF Tool",
));
}
self.files -= 1;
self.bytes -= len;
Ok(())
}
}
fn copy_tree(from: &Path, to: &Path, budget: &mut Budget) -> std::io::Result<()> {
std::fs::create_dir(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let (src, dst) = (entry.path(), to.join(entry.file_name()));
let kind = entry.file_type()?;
if kind.is_dir() {
budget.take(0)?;
copy_tree(&src, &dst, budget)?;
} else if kind.is_file() {
budget.take(entry.metadata()?.len())?;
std::fs::copy(&src, &dst)?;
} else if kind.is_symlink() {
budget.take(0)?;
copy_link(&src, &dst)?;
}
}
Ok(())
}
fn copy_link(src: &Path, dst: &Path) -> std::io::Result<()> {
let target = std::fs::read_link(src)?;
let stays_inside = target.components().all(|c| matches!(c, Component::Normal(_)));
if !stays_inside {
return Ok(());
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, dst)
}
#[cfg(not(unix))]
{
let _ = dst;
Ok(())
}
}
fn swap_in(staged: &Path, dest: &Path) -> std::io::Result<()> {
let parent = dest.parent().unwrap_or_else(|| Path::new("."));
let aside_dir = tempfile::Builder::new().prefix(&format!("{WORK_PREFIX}old-")).tempdir_in(parent)?;
let aside = aside_dir.path().join("ovftool");
let had = match std::fs::rename(dest, &aside) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(e),
};
if let Err(e) = std::fs::rename(staged, dest) {
if had {
std::fs::rename(&aside, dest).ok();
}
return Err(e);
}
drop(aside_dir);
Ok(())
}
fn remove_leftovers(parent: &Path) {
let Ok(entries) = std::fs::read_dir(parent) else {
return;
};
let now = SystemTime::now();
for entry in entries.flatten() {
let old = entry
.metadata()
.and_then(|m| m.modified())
.is_ok_and(|at| now.duration_since(at).unwrap_or_default() >= LEFTOVER_AFTER);
if entry.file_name().to_string_lossy().starts_with(WORK_PREFIX) && old {
std::fs::remove_dir_all(entry.path()).ok();
}
}
}
fn text(path: &Path) -> Result<&str, PlaceError> {
path.to_str().ok_or_else(|| PlaceError::NotUtf8(path.to_path_buf()))
}
async fn signature_refusal(cx: &Context, staged: &Path) -> Result<Option<(Refusal, Option<String>)>, PlaceError> {
let requirement = format!("-R=anchor apple generic and certificate leaf[subject.OU] = \"{VMWARE_TEAM}\"");
for file in mach_o_files(staged) {
let shown = file.strip_prefix(staged).unwrap_or(&file).display().to_string();
let path = text(&file)?;
match failure::ask(cx, (CODESIGN, &["--verify", "--strict", path])).await {
Ok(_) => {}
Err(Failure::Refused { said, .. }) => return Ok(Some((Refusal::Unsigned, Some(format!("{shown}: {said}"))))),
Err(e) => return Err(PlaceError::Tool(e)),
}
match failure::ask(cx, (CODESIGN, &["--verify", "--strict", &requirement, path])).await {
Ok(_) => {}
Err(Failure::Refused { .. }) => {
let team = failure::ask(cx, (CODESIGN, &["-d", "-r-", path])).await.ok().and_then(|dr| signing_team(&dr));
return Ok(Some((Refusal::NotVmware, team)));
}
Err(e) => return Err(PlaceError::Tool(e)),
}
}
Ok(None)
}
fn signing_team(requirement: &str) -> Option<String> {
let (_, after) = requirement.split_once("leaf[subject.OU] = ")?;
let team: String = after.trim_start_matches('"').chars().take_while(char::is_ascii_alphanumeric).collect();
(!team.is_empty()).then_some(team)
}
async fn lift_quarantine(cx: &Context, staged: &Path) -> Result<(), PlaceError> {
failure::ask(cx, (XATTR, &["-d", "-r", "com.apple.quarantine", text(staged)?]))
.await
.map(drop)
.map_err(PlaceError::Tool)
}
fn needs_rosetta(cx: &Context, file: &Path) -> bool {
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)))
}