Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.2 KB
Raw Blame
//! Squirrel.Mac's part of updateService.darwin.ts: the read-only check before a check, the verification of a
//! downloaded zip and its bundle, and ShipIt, the helper that swaps the bundle after the app quit.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Context, bail};
use sha2::{Digest, Sha256};

/// The app bundle the running executable sits in (`<bundle>.app/Contents/MacOS/<executable>`); none when it runs
/// out of a build folder.
#[cfg(target_os = "macos")]
pub fn running_bundle() -> Option<PathBuf> {
    let executable = std::env::current_exe().ok()?;
    let bundle = executable.parent()?.parent()?.parent()?;
    (bundle.extension()? == "app" && executable.parent()?.ends_with("Contents/MacOS")).then(|| bundle.to_path_buf())
}

/// The Linux and Windows archive's folder (port/tools/package-linux): the executable beside `resources/app`.
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub fn running_bundle() -> Option<PathBuf> {
    let folder = std::env::current_exe().ok()?.parent()?.to_path_buf();
    folder.join("resources/app").is_dir().then_some(folder)
}

/// Squirrel.Mac's `<bundle id>.ShipIt` cache folder: the download (`update`, removed at startup) and the helper's log.
pub fn shipit_dir() -> PathBuf {
    let id = crate::product::get("darwinBundleIdentifier").as_str().expect("product.json has darwinBundleIdentifier");
    PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(format!("Library/Caches/{id}.ShipIt"))
}

/// SQRLUpdater's check before it looks for updates: a bundle that cannot be replaced (a mounted disk image, App
/// Translocation's read-only mount, a folder without write access) is never updated. Its message, as Electron
/// joins the error's description and recovery suggestion.
#[cfg(unix)]
pub fn check_writable(bundle: &Path) -> anyhow::Result<()> {
    let writable = |path: &Path| {
        let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).expect("a path without NUL");
        // SAFETY: `path` is a NUL-terminated C string alive for the call.
        unsafe { libc::access(path.as_ptr(), libc::W_OK) == 0 }
    };
    let translocated = bundle.components().any(|part| part.as_os_str() == "AppTranslocation");
    if translocated || !writable(bundle) || !bundle.parent().is_some_and(writable) {
        bail!(
            "Cannot update while running on a read-only volume. The application is on a read-only volume. Please move the application and try again. If you're on macOS Sierra or later, you'll need to move the application out of the Downloads directory. See https://github.com/Squirrel/Squirrel.Mac/issues/182 for more information."
        );
    }
    Ok(())
}

/// Checks the zip against the feed's hash, extracts it into `staging` and verifies the bundle in it against the
/// installed one; answers the extracted bundle.
pub fn verify_download(zip: &Path, sha256hash: &str, staging: &Path, installed: &Path) -> anyhow::Result<PathBuf> {
    let actual = sha256_file(zip)?;
    if actual != sha256hash {
        bail!("The update's SHA-256 {actual} is not the feed's {sha256hash}");
    }
    let extracted = staging.join("extracted");
    let _ = std::fs::remove_dir_all(&extracted);
    run(Command::new("/usr/bin/ditto").args(["-x", "-k"]).arg(zip).arg(&extracted)).context("Could not extract the update")?;
    let mut entries = std::fs::read_dir(&extracted)?.collect::<Result<Vec<_>, _>>()?;
    let app = match entries.pop() {
        Some(entry) if entries.is_empty() && entry.path().extension().is_some_and(|extension| extension == "app") && entry.file_type()?.is_dir() => entry.path(),
        _ => bail!("The update zip does not hold exactly one app bundle"),
    };
    verify_signature(&app, installed)?;
    Ok(app)
}

fn sha256_file(path: &Path) -> anyhow::Result<String> {
    let mut file = std::fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buffer = vec![0; 1 << 20];
    loop {
        let read = file.read(&mut buffer)?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hasher.finalize().iter().map(|byte| format!("{byte:02x}")).collect())
}

/// SQRLCodeSignature: the candidate must satisfy the installed bundle's designated requirement (Squirrel.Mac's
/// check, which pins an Apple-issued certificate, the Team ID and the bundle id) and carry the same bundle id and
/// Team ID. An installed bundle without a Team ID (ad-hoc signed) cannot vouch for any update.
pub fn verify_signature(candidate: &Path, installed: &Path) -> anyhow::Result<()> {
    let (identifier, team) = signing_identity(installed)?;
    let Some(team) = team else {
        bail!("{} is not signed with a Developer ID, so an update cannot be verified", installed.display());
    };
    let requirement = designated_requirement(installed)?;
    run(Command::new("/usr/bin/codesign").args(["--verify", "--deep", "--strict", "-R"]).arg(format!("={requirement}")).arg(candidate))
        .with_context(|| format!("The update's code signature is not valid or does not satisfy {requirement}"))?;
    let (candidate_identifier, candidate_team) = signing_identity(candidate)?;
    if candidate_identifier != identifier || candidate_team.as_deref() != Some(team.as_str()) {
        bail!("The update is signed as {candidate_identifier} ({}), not as {identifier} ({team})", candidate_team.as_deref().unwrap_or("no Team ID"));
    }
    Ok(())
}

/// `Identifier` and `TeamIdentifier` of `codesign -dv` (none for "not set").
fn signing_identity(bundle: &Path) -> anyhow::Result<(String, Option<String>)> {
    let details = run(Command::new("/usr/bin/codesign").args(["-dv", "--verbose=2"]).arg(bundle)).with_context(|| format!("{} is not signed", bundle.display()))?;
    let field = |name: &str| details.lines().find_map(|line| line.strip_prefix(name)?.strip_prefix('=')).map(str::to_owned);
    let identifier = field("Identifier").context("codesign printed no Identifier")?;
    Ok((identifier, field("TeamIdentifier").filter(|team| team != "not set")))
}

fn designated_requirement(bundle: &Path) -> anyhow::Result<String> {
    let output = run(Command::new("/usr/bin/codesign").args(["-d", "-r-"]).arg(bundle))?;
    // An implicit requirement prints as "# designated => ...".
    output.lines().find_map(|line| line.trim_start_matches("# ").strip_prefix("designated => ")).map(str::to_owned).context("codesign printed no designated requirement")
}

/// The helper's first argument: `vsrustium --apply-update <pid> <staged .app> <installed .app> [--relaunch <args>...]`.
pub const APPLY_UPDATE: &str = "--apply-update";

/// Starts the helper (ShipIt) from this executable, in its own process group so it outlives the app, logging to
/// `ShipIt_stderr.log`. With `relaunch` it starts the app again with this process's arguments.
#[cfg(unix)]
pub fn spawn_helper(staged: &Path, installed: &Path, relaunch: bool) -> anyhow::Result<()> {
    use std::os::unix::process::CommandExt;
    let log = std::fs::OpenOptions::new().create(true).append(true).open(shipit_dir().join("ShipIt_stderr.log"))?;
    let mut command = Command::new(std::env::current_exe()?);
    command.arg(APPLY_UPDATE).arg(std::process::id().to_string()).arg(staged).arg(installed);
    if relaunch {
        command.arg("--relaunch").args(std::env::args_os().skip(1));
    }
    command.stdin(std::process::Stdio::null()).stdout(log.try_clone()?).stderr(log).process_group(0).spawn()?;
    Ok(())
}

/// The helper: waits for the app to exit, verifies the staged bundle against the installed one, swaps them
/// (`replace`), relaunches, then deletes the old copy. A failed swap leaves the installed app as it was.
pub fn apply_update(args: &[String]) -> anyhow::Result<()> {
    let [pid, staged, installed, rest @ ..] = args else { bail!("usage: {APPLY_UPDATE} <pid> <staged .app> <installed .app> [--relaunch <args>...]") };
    let (staged, installed) = (Path::new(staged), Path::new(installed));
    let relaunch = rest.first().is_some_and(|arg| arg == "--relaunch").then(|| &rest[1..]);
    let log = |message: String| eprintln!("{} [ShipIt] {message}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f"));
    wait_for_exit(pid.parse()?)?;
    let aside = installed.with_file_name(format!(".{}.old", installed.file_name().context("an app path")?.to_string_lossy()));
    let swapped = verify_signature(staged, installed).and_then(|()| replace(staged, installed, &aside));
    match &swapped {
        Ok(()) => log(format!("installed {} at {}", staged.display(), installed.display())),
        Err(error) => log(format!("update not installed: {error:#}")),
    }
    if let Some(args) = relaunch {
        let executable = installed.join("Contents/MacOS").join(std::env::current_exe()?.file_name().context("an executable name")?);
        Command::new(&executable).args(args).spawn().with_context(|| format!("relaunching {}", executable.display()))?;
        log(format!("relaunched {}", executable.display()));
    }
    if swapped.is_ok() {
        std::fs::remove_dir_all(&aside)?;
    }
    swapped
}

/// Windows updates are a download link (port/ledger.md decision "Windows updates"): no update is ever staged.
#[cfg(windows)]
pub fn spawn_helper(_staged: &Path, _installed: &Path, _relaunch: bool) -> anyhow::Result<()> {
    bail!("updates are not installed in place on Windows")
}

#[cfg(windows)]
fn wait_for_exit(_pid: u32) -> anyhow::Result<()> {
    bail!("updates are not installed in place on Windows")
}

#[cfg(unix)]
fn wait_for_exit(pid: libc::pid_t) -> anyhow::Result<()> {
    for _ in 0..3000 {
        // SAFETY: signal 0 only asks whether the process exists; no pointers pass.
        if unsafe { libc::kill(pid, 0) } != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) {
            return Ok(());
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
    }
    bail!("process {pid} did not exit in 5 minutes")
}

/// Moves `installed` to `aside`, then `new` to `installed` (a copy with ditto across volumes); any failure after the
/// first move puts the installed app back, so a failed update never leaves a broken install.
pub fn replace(new: &Path, installed: &Path, aside: &Path) -> anyhow::Result<()> {
    let _ = std::fs::remove_dir_all(aside);
    std::fs::rename(installed, aside).with_context(|| format!("Could not move {} aside", installed.display()))?;
    let moved = match std::fs::rename(new, installed) {
        Err(error) if error.raw_os_error() == Some(libc::EXDEV) => run(Command::new("/usr/bin/ditto").arg(new).arg(installed)).map(drop),
        moved => moved.map_err(anyhow::Error::from),
    };
    let Err(error) = moved else { return Ok(()) };
    let _ = std::fs::remove_dir_all(installed);
    std::fs::rename(aside, installed).with_context(|| format!("Could not move the update in ({error:#}), nor {} back", aside.display()))?;
    Err(error).context("Could not move the update in; the installed app was put back")
}

/// Runs the command; its stdout and stderr together on success (codesign prints its details to stderr), an error
/// with stderr otherwise.
fn run(command: &mut Command) -> anyhow::Result<String> {
    let output = command.output()?;
    if !output.status.success() {
        bail!("{}", String::from_utf8_lossy(&output.stderr).trim());
    }
    Ok(format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)))
}

#[cfg(test)]
mod tests;