Skip to main content

smriti/services/
self_replace.rs

1//! Per-install-method update download + install logic.
2//!
3//! The update checker hands us a `LatestRelease` and the detected
4//! `InstallMethod`; this module picks the right artifact, downloads
5//! it, verifies its SHA256 against the published `SHA256SUMS`, and
6//! either self-replaces the running binary or triggers the platform
7//! installer.
8//!
9//! Critical invariant: for package-manager installs we **never**
10//! download or replace anything. The package manager owns the
11//! binary; stomping on it would confuse the system. Callers should
12//! check `InstallMethod` before calling `install_update`, but the
13//! function defensively short-circuits on those variants anyway.
14
15use std::path::Path;
16#[cfg(target_os = "linux")]
17use std::path::PathBuf;
18
19use futures::StreamExt;
20use sha2::{Digest, Sha256};
21use tokio::io::AsyncWriteExt;
22
23use super::install_method::InstallMethod;
24use super::update_checker::{LatestRelease, ReleaseAsset};
25
26/// What happened when the user clicked "Download update".
27#[derive(Debug, Clone)]
28#[allow(dead_code)] // variant payload fields are observed via match
29                    // arms; Rust's dead-code pass can't see through.
30pub enum InstallOutcome {
31    /// The running binary was replaced in place. The UI should prompt
32    /// the user to relaunch.
33    ReplacedRestartRequired,
34
35    /// A platform installer was spawned (msiexec, `open dmg`). The app
36    /// should exit so the installer can complete. The UI prompts.
37    InstallerLaunched { installer: String },
38
39    /// The user's install method is managed externally (apt, brew, ...).
40    /// Banner should have shown the upgrade command; we refused to
41    /// touch the install.
42    HandedOffToPackageManager { name: String, upgrade_cmd: String },
43
44    /// The install method is unknown; open the release page in the
45    /// user's default browser as a fallback.
46    OpenedReleasePage { url: String },
47}
48
49/// Errors from the install pipeline. Distinguished so the UI can
50/// decide whether to show a retry affordance.
51#[derive(Debug, thiserror::Error)]
52pub enum UpdateError {
53    #[error("no matching release asset for this platform")]
54    NoAssetForPlatform,
55
56    #[error("SHA256SUMS file missing from the release")]
57    NoChecksumFile,
58
59    #[error("downloaded {got} bytes, expected {expected}")]
60    SizeMismatch { got: u64, expected: u64 },
61
62    #[error("SHA256 checksum mismatch for {asset}")]
63    ChecksumMismatch { asset: String },
64
65    #[error("SHA256SUMS does not list an entry for {asset}")]
66    ChecksumEntryMissing { asset: String },
67
68    #[error("network error while downloading: {0}")]
69    Network(String),
70
71    #[error("filesystem error: {0}")]
72    Io(#[from] std::io::Error),
73
74    #[error("failed to replace running binary: {0}")]
75    Replace(String),
76
77    #[error("failed to launch platform installer: {0}")]
78    SpawnInstaller(String),
79
80    #[error("failed to open the release page: {0}")]
81    OpenBrowser(String),
82}
83
84/// Full install flow. Dispatches to the right strategy based on the
85/// detected install method.
86///
87/// `progress` is an optional callback invoked with
88/// `(downloaded_bytes, total_bytes)` as bytes stream in, so the UI
89/// can render a progress bar. Called at most every ~256 KB.
90pub type ProgressCallback = Box<dyn FnMut(u64, u64) + Send>;
91
92pub async fn install_update(
93    method: InstallMethod,
94    latest: LatestRelease,
95    progress: Option<ProgressCallback>,
96) -> Result<InstallOutcome, UpdateError> {
97    match method {
98        // Managed externally — never download.
99        InstallMethod::PackageManager { name, upgrade_cmd } => {
100            Ok(InstallOutcome::HandedOffToPackageManager { name, upgrade_cmd })
101        }
102
103        // Unknown install → open the release page instead of guessing.
104        InstallMethod::Unknown | InstallMethod::SourceBuild => {
105            open_in_browser(&latest.html_url)?;
106            Ok(InstallOutcome::OpenedReleasePage {
107                url: latest.html_url,
108            })
109        }
110
111        // AppImage on Linux or portable zip on Windows: atomic swap.
112        InstallMethod::Portable => {
113            // Archives are not executables. Until archive extraction and bundle
114            // installation are supported, use the release page on those systems.
115            if !cfg!(target_os = "linux") || std::env::var_os("APPIMAGE").is_none() {
116                open_in_browser(&latest.html_url)?;
117                return Ok(InstallOutcome::OpenedReleasePage {
118                    url: latest.html_url,
119                });
120            }
121            let asset = pick_portable_asset(&latest.assets)?.clone();
122            let downloaded = download_and_verify(&asset, &latest.assets, progress).await?;
123            replace_running_binary(&downloaded).await?;
124            Ok(InstallOutcome::ReplacedRestartRequired)
125        }
126
127        // .deb/.rpm from the release: nothing to upgrade through, and
128        // installing a system package needs the user's own package tool.
129        InstallMethod::LinuxPackage { .. } => {
130            open_in_browser(&latest.html_url)?;
131            Ok(InstallOutcome::OpenedReleasePage {
132                url: latest.html_url,
133            })
134        }
135
136        // Windows NSIS: download the new setup and run it in passive mode.
137        // The installer closes the running app, updates and relaunches it.
138        InstallMethod::NsisInstaller => {
139            let asset = pick_nsis_asset(&latest.assets)?.clone();
140            let downloaded = download_and_verify(&asset, &latest.assets, progress).await?;
141            launch_nsis(&downloaded)?;
142            downloaded
143                .keep()
144                .map_err(|error| UpdateError::Io(error.error))?;
145            Ok(InstallOutcome::InstallerLaunched {
146                installer: asset.name,
147            })
148        }
149
150        // Windows MSI: download + invoke msiexec with UAC.
151        InstallMethod::MsiInstaller => {
152            let asset = pick_msi_asset(&latest.assets)?.clone();
153            let downloaded = download_and_verify(&asset, &latest.assets, progress).await?;
154            launch_msi(&downloaded)?;
155            downloaded
156                .keep()
157                .map_err(|error| UpdateError::Io(error.error))?;
158            Ok(InstallOutcome::InstallerLaunched {
159                installer: asset.name,
160            })
161        }
162
163        // macOS .dmg: download + open so the user drags into /Applications.
164        InstallMethod::MacOsApp => {
165            let asset = pick_dmg_asset(&latest.assets)?.clone();
166            let downloaded = download_and_verify(&asset, &latest.assets, progress).await?;
167            open_dmg(&downloaded)?;
168            downloaded
169                .keep()
170                .map_err(|error| UpdateError::Io(error.error))?;
171            Ok(InstallOutcome::InstallerLaunched {
172                installer: asset.name,
173            })
174        }
175    }
176}
177
178// --- Asset selection --------------------------------------------------
179
180fn pick_portable_asset(assets: &[ReleaseAsset]) -> Result<&ReleaseAsset, UpdateError> {
181    #[cfg(target_os = "linux")]
182    let patterns: &[&str] = &[".AppImage"];
183    #[cfg(target_os = "windows")]
184    let patterns: &[&str] = &["pc-windows-msvc.zip", "windows-x64.zip"];
185    #[cfg(target_os = "macos")]
186    let patterns: &[&str] = &["apple-darwin.tar.gz"];
187
188    assets
189        .iter()
190        .find(|a| {
191            patterns.iter().any(|p| a.name.ends_with(p))
192                && asset_matches_arch(&a.name, std::env::consts::ARCH)
193        })
194        .ok_or(UpdateError::NoAssetForPlatform)
195}
196
197fn pick_msi_asset(assets: &[ReleaseAsset]) -> Result<&ReleaseAsset, UpdateError> {
198    assets
199        .iter()
200        .find(|a| {
201            a.name.to_ascii_lowercase().ends_with(".msi")
202                && asset_matches_arch(&a.name, std::env::consts::ARCH)
203        })
204        .ok_or(UpdateError::NoAssetForPlatform)
205}
206
207fn pick_nsis_asset(assets: &[ReleaseAsset]) -> Result<&ReleaseAsset, UpdateError> {
208    assets
209        .iter()
210        .find(|a| {
211            a.name.to_ascii_lowercase().ends_with("-setup.exe")
212                && asset_matches_arch(&a.name, std::env::consts::ARCH)
213        })
214        .ok_or(UpdateError::NoAssetForPlatform)
215}
216
217fn pick_dmg_asset(assets: &[ReleaseAsset]) -> Result<&ReleaseAsset, UpdateError> {
218    assets
219        .iter()
220        .find(|a| {
221            a.name.to_ascii_lowercase().ends_with(".dmg")
222                && asset_matches_arch(&a.name, std::env::consts::ARCH)
223        })
224        .ok_or(UpdateError::NoAssetForPlatform)
225}
226
227fn asset_matches_arch(name: &str, arch: &str) -> bool {
228    let name = name.to_ascii_lowercase();
229    let aliases: &[&str] = match arch {
230        "x86_64" => &["x86_64", "amd64", "x64"],
231        "aarch64" => &["aarch64", "arm64", "apple-silicon"],
232        _ => return false,
233    };
234    aliases.iter().any(|alias| name.contains(alias)) || name.contains("universal")
235}
236
237// --- Download + verify -------------------------------------------------
238
239/// Download `asset` to a temp file and verify its SHA256 matches the
240/// entry in the release's `SHA256SUMS` asset. Returns the path to the
241/// verified temp file; caller is responsible for moving it into place.
242async fn download_and_verify(
243    asset: &ReleaseAsset,
244    all_assets: &[ReleaseAsset],
245    mut progress: Option<ProgressCallback>,
246) -> Result<tempfile::TempPath, UpdateError> {
247    let expected_hash = fetch_expected_hash(all_assets, &asset.name).await?;
248
249    let staged = tempfile::Builder::new()
250        .prefix("smriti-update-")
251        .suffix(&format!("-{}", safe_temp_file_name(&asset.name)))
252        .tempfile()?;
253    let (file, temp_path) = staged.into_parts();
254    let client = build_client()?;
255
256    let response = client
257        .get(&asset.browser_download_url)
258        .send()
259        .await
260        .and_then(|r| r.error_for_status())
261        .map_err(|e| UpdateError::Network(e.to_string()))?;
262
263    let total = response.content_length().unwrap_or(asset.size_bytes);
264    let mut file = tokio::fs::File::from_std(file);
265    let mut hasher = Sha256::new();
266    let mut downloaded: u64 = 0;
267    let mut last_progress_report: u64 = 0;
268
269    let mut stream = response.bytes_stream();
270    while let Some(chunk) = stream.next().await {
271        let chunk = chunk.map_err(|e| UpdateError::Network(e.to_string()))?;
272        if asset.size_bytes != 0 && downloaded.saturating_add(chunk.len() as u64) > asset.size_bytes
273        {
274            return Err(UpdateError::SizeMismatch {
275                got: downloaded + chunk.len() as u64,
276                expected: asset.size_bytes,
277            });
278        }
279        hasher.update(&chunk);
280        file.write_all(&chunk).await?;
281        downloaded += chunk.len() as u64;
282
283        if let Some(cb) = progress.as_mut() {
284            // Report at most once per ~256 KB to keep the UI event
285            // stream from drowning in ticks.
286            if downloaded - last_progress_report > 256 * 1024 || downloaded == total {
287                cb(downloaded, total);
288                last_progress_report = downloaded;
289            }
290        }
291    }
292    file.flush().await?;
293    file.sync_all().await?;
294    drop(file);
295
296    if asset.size_bytes != 0 && downloaded != asset.size_bytes {
297        return Err(UpdateError::SizeMismatch {
298            got: downloaded,
299            expected: asset.size_bytes,
300        });
301    }
302
303    let actual_hash = format!("{:x}", hasher.finalize());
304    if !actual_hash.eq_ignore_ascii_case(&expected_hash) {
305        // Clean up the tainted file so we don't accidentally install
306        // it on a retry.
307        let _ = tokio::fs::remove_file(&temp_path).await;
308        return Err(UpdateError::ChecksumMismatch {
309            asset: asset.name.clone(),
310        });
311    }
312
313    Ok(temp_path)
314}
315
316/// Download and parse the `SHA256SUMS` file, returning the expected
317/// hash for `asset_name`.
318async fn fetch_expected_hash(
319    assets: &[ReleaseAsset],
320    asset_name: &str,
321) -> Result<String, UpdateError> {
322    let sums_asset = assets
323        .iter()
324        .find(|a| a.name.eq_ignore_ascii_case("SHA256SUMS"))
325        .ok_or(UpdateError::NoChecksumFile)?;
326
327    let client = build_client()?;
328    let body = client
329        .get(&sums_asset.browser_download_url)
330        .send()
331        .await
332        .and_then(|r| r.error_for_status())
333        .map_err(|e| UpdateError::Network(e.to_string()))?
334        .text()
335        .await
336        .map_err(|e| UpdateError::Network(e.to_string()))?;
337
338    parse_sha256sums(&body, asset_name).ok_or_else(|| UpdateError::ChecksumEntryMissing {
339        asset: asset_name.to_string(),
340    })
341}
342
343fn safe_temp_file_name(name: &str) -> String {
344    let mut out = String::with_capacity(name.len().max(1));
345    for ch in name.chars() {
346        if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') {
347            out.push(ch);
348        } else {
349            out.push('_');
350        }
351    }
352    let trimmed = out.trim_matches('.');
353    if trimmed.is_empty() {
354        "download".into()
355    } else {
356        trimmed.to_string()
357    }
358}
359
360/// Parse a single entry out of a standard `sha256sum` file. Each line
361/// looks like: `<64-hex-chars>  <filename>` or `<64-hex-chars> *<filename>`.
362pub(crate) fn parse_sha256sums(body: &str, want: &str) -> Option<String> {
363    for line in body.lines() {
364        let mut parts = line.split_whitespace();
365        let Some(hash) = parts.next() else { continue };
366        let Some(name) = parts.next() else { continue };
367        let name = name.trim_start_matches('*');
368        if name == want {
369            return Some(hash.to_lowercase());
370        }
371    }
372    None
373}
374
375fn build_client() -> Result<reqwest::Client, UpdateError> {
376    reqwest::Client::builder()
377        .timeout(std::time::Duration::from_secs(120))
378        .user_agent(format!("smriti/{}", env!("CARGO_PKG_VERSION")))
379        .build()
380        .map_err(|e| UpdateError::Network(e.to_string()))
381}
382
383// --- Binary swap / installer spawn ------------------------------------
384
385#[cfg(target_os = "linux")]
386async fn replace_running_binary(new_binary: &Path) -> Result<(), UpdateError> {
387    let current = std::env::var_os("APPIMAGE")
388        .map(PathBuf::from)
389        .filter(|path| path.is_absolute() && path.is_file())
390        .ok_or_else(|| UpdateError::Replace("AppImage installation path is unavailable".into()))?;
391    let new_binary = new_binary.to_path_buf();
392    let current_clone = current.clone();
393
394    tokio::task::spawn_blocking(move || -> Result<(), UpdateError> {
395        use std::io::Write;
396        use std::os::unix::fs::PermissionsExt;
397
398        let parent = current_clone.parent().ok_or_else(|| {
399            UpdateError::Replace("AppImage installation directory is unavailable".into())
400        })?;
401        // The download usually lives on another filesystem. Copy into the
402        // destination directory first, fsync it, then atomically rename over
403        // the running AppImage. Linux permits replacing an executing inode.
404        let mut source = std::fs::File::open(&new_binary)?;
405        let mut staged = tempfile::NamedTempFile::new_in(parent)?;
406        std::io::copy(&mut source, &mut staged)?;
407        staged.flush()?;
408        let mut permissions = staged.as_file().metadata()?.permissions();
409        permissions.set_mode(permissions.mode() | 0o755);
410        staged.as_file().set_permissions(permissions)?;
411        staged.as_file().sync_all()?;
412        staged
413            .persist(&current_clone)
414            .map_err(|error| UpdateError::Io(error.error))?;
415        std::fs::File::open(parent)?.sync_all()?;
416        Ok(())
417    })
418    .await
419    .map_err(|e| UpdateError::Replace(format!("spawn_blocking panicked: {}", e)))??;
420
421    Ok(())
422}
423
424#[cfg(not(target_os = "linux"))]
425async fn replace_running_binary(_new_binary: &Path) -> Result<(), UpdateError> {
426    Err(UpdateError::Replace(
427        "in-place replacement is only supported for Linux AppImages".into(),
428    ))
429}
430
431#[cfg(target_os = "windows")]
432fn launch_msi(msi: &Path) -> Result<(), UpdateError> {
433    use std::os::windows::process::CommandExt;
434    std::process::Command::new("msiexec")
435        .arg("/i")
436        .arg(msi)
437        .arg("/passive")
438        .arg("/norestart")
439        // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP so our exit
440        // doesn't take msiexec down with us.
441        .creation_flags(0x0000_0008 | 0x0000_0200)
442        .spawn()
443        .map(|_| ())
444        .map_err(|e| UpdateError::SpawnInstaller(e.to_string()))
445}
446
447/// `/P` is Tauri's passive mode (progress only, no questions) and `/R`
448/// relaunches Smriti once the files are replaced.
449#[cfg(target_os = "windows")]
450fn launch_nsis(setup: &Path) -> Result<(), UpdateError> {
451    use std::os::windows::process::CommandExt;
452    std::process::Command::new(setup)
453        .args(["/P", "/R"])
454        .creation_flags(0x0000_0008 | 0x0000_0200)
455        .spawn()
456        .map(|_| ())
457        .map_err(|e| UpdateError::SpawnInstaller(e.to_string()))
458}
459
460#[cfg(not(target_os = "windows"))]
461fn launch_nsis(_setup: &Path) -> Result<(), UpdateError> {
462    Err(UpdateError::SpawnInstaller(
463        "NSIS setup is only supported on Windows".into(),
464    ))
465}
466
467#[cfg(not(target_os = "windows"))]
468fn launch_msi(_msi: &Path) -> Result<(), UpdateError> {
469    Err(UpdateError::SpawnInstaller(
470        "MSI launch is only supported on Windows".into(),
471    ))
472}
473
474#[cfg(target_os = "macos")]
475fn open_dmg(dmg: &Path) -> Result<(), UpdateError> {
476    std::process::Command::new("open")
477        .arg("-g")
478        .arg(dmg)
479        .spawn()
480        .map(|_| ())
481        .map_err(|e| UpdateError::SpawnInstaller(e.to_string()))
482}
483
484#[cfg(not(target_os = "macos"))]
485fn open_dmg(_dmg: &Path) -> Result<(), UpdateError> {
486    Err(UpdateError::SpawnInstaller(
487        "DMG launch is only supported on macOS".into(),
488    ))
489}
490
491fn open_in_browser(url: &str) -> Result<(), UpdateError> {
492    open::that(url).map_err(|e| UpdateError::OpenBrowser(e.to_string()))
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    #[test]
500    fn release_assets_must_match_the_running_architecture() {
501        assert!(asset_matches_arch("Smriti-Linux-x64.AppImage", "x86_64"));
502        assert!(!asset_matches_arch("Smriti-Linux-x64.AppImage", "aarch64"));
503        assert!(asset_matches_arch(
504            "Smriti-macOS-Apple-Silicon.dmg",
505            "aarch64"
506        ));
507        assert!(!asset_matches_arch(
508            "Smriti-macOS-Apple-Silicon.dmg",
509            "x86_64"
510        ));
511        assert!(!asset_matches_arch("Smriti.dmg", "x86_64"));
512    }
513
514    #[test]
515    fn installer_assets_follow_tauri_release_names() {
516        let asset = |name: &str| ReleaseAsset {
517            name: name.into(),
518            browser_download_url: String::new(),
519            size_bytes: 0,
520        };
521        let assets = vec![
522            asset("Smriti_0.5.0_x64_en-US.msi"),
523            asset("Smriti_0.5.0_x64-setup.exe"),
524            asset("Smriti_0.5.0_aarch64.dmg"),
525        ];
526        if std::env::consts::ARCH == "x86_64" {
527            assert_eq!(
528                pick_nsis_asset(&assets).unwrap().name,
529                "Smriti_0.5.0_x64-setup.exe"
530            );
531            assert_eq!(
532                pick_msi_asset(&assets).unwrap().name,
533                "Smriti_0.5.0_x64_en-US.msi"
534            );
535        }
536    }
537
538    #[test]
539    fn sha256sums_parse_plain_format() {
540        let body = "\
541abc123  Smriti-x86_64.AppImage
542def456  Smriti-Setup-x64.msi
543";
544        assert_eq!(
545            parse_sha256sums(body, "Smriti-x86_64.AppImage"),
546            Some("abc123".to_string())
547        );
548        assert_eq!(
549            parse_sha256sums(body, "Smriti-Setup-x64.msi"),
550            Some("def456".to_string())
551        );
552    }
553
554    #[test]
555    fn sha256sums_parse_binary_star_format() {
556        // Some sha256sum implementations use `*` to mark binary mode.
557        let body = "abc123 *Smriti-x86_64.AppImage\n";
558        assert_eq!(
559            parse_sha256sums(body, "Smriti-x86_64.AppImage"),
560            Some("abc123".to_string())
561        );
562    }
563
564    #[test]
565    fn sha256sums_returns_none_when_missing() {
566        let body = "abc123  other-file\n";
567        assert!(parse_sha256sums(body, "Smriti-x86_64.AppImage").is_none());
568    }
569
570    #[test]
571    fn sha256sums_skips_blank_lines() {
572        let body = "\n\nabc123  Smriti-x86_64.AppImage\n\n";
573        assert_eq!(
574            parse_sha256sums(body, "Smriti-x86_64.AppImage"),
575            Some("abc123".to_string())
576        );
577    }
578
579    #[test]
580    fn temp_file_name_removes_path_separators() {
581        assert_eq!(
582            safe_temp_file_name("../Smriti Setup/x64.msi"),
583            "_Smriti_Setup_x64.msi"
584        );
585        assert_eq!(safe_temp_file_name("..."), "download");
586    }
587}