1use 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
32pub const VMWARE_TEAM: &str = "EG7KH642X6";
34
35const CODESIGN: &str = "/usr/bin/codesign";
37
38const XATTR: &str = "/usr/bin/xattr";
40
41const MAX_FILES: usize = 2_000;
44const MAX_BYTES: u64 = 1 << 30;
45
46const LEFTOVER_AFTER: Duration = Duration::from_secs(600);
49
50const WORK_PREFIX: &str = ".ovftool-";
52
53#[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#[must_use]
64pub fn workstation_dir(pf: &Path) -> PathBuf {
65 pf.join("VMware").join("VMware Workstation").join("OVFTool")
66}
67
68#[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 Fusion,
75 Workstation,
77 Managed,
79 Path,
81}
82
83#[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 pub source: Source,
90 pub path: String,
92 pub needs_rosetta: bool,
95}
96
97#[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 NoTool,
104 NoLibraries,
106 TooLarge,
108 Unsigned,
110 NotVmware,
112}
113
114#[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 Placed {
121 path: String,
123 needs_rosetta: bool,
125 },
126 Refused {
128 reason: Refusal,
130 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#[derive(Debug)]
146#[non_exhaustive]
147pub enum PlaceError {
148 Io(std::io::Error),
150 Tool(Failure),
152 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
182fn bundled_source(os: HostOs) -> Source {
184 match os {
185 HostOs::Windows => Source::Workstation,
186 HostOs::Macos | HostOs::Linux => Source::Fusion,
187 }
188}
189
190#[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
205pub 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
220pub 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
236pub 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
245pub 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 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
282async 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 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
304fn 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
322fn 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
336fn 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
352struct 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 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
382fn 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
405fn 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
424fn 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 drop(aside_dir);
445 Ok(())
446}
447
448fn 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
466fn text(path: &Path) -> Result<&str, PlaceError> {
468 path.to_str().ok_or_else(|| PlaceError::NotUtf8(path.to_path_buf()))
469}
470
471async 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
501fn 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
509async 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
522fn 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}