Skip to main content

sapphire_framework_update/
install.rs

1//! Replacing the running executable with a newer release.
2
3use std::io::{BufRead, Write as _};
4use std::path::{Path, PathBuf};
5use std::time::Duration;
6
7use serde::Deserialize;
8
9use crate::release::{Release, ReleaseSource, latest_release};
10use crate::{Error, Result};
11
12/// The most a download may weigh. A release binary is tens of megabytes; this only stops a
13/// runaway response from filling memory.
14const MAX_DOWNLOAD: u64 = 512 * 1024 * 1024;
15
16/// How long one download may take.
17const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
18
19/// The `update` subcommand's arguments: replace this executable with its newest release.
20#[derive(Clone, Debug, Default, clap::Args)]
21pub struct UpdateArgs {
22    /// Only say whether a newer release exists; download nothing.
23    #[arg(long)]
24    pub check: bool,
25    /// Install without asking first.
26    #[arg(long, short = 'y')]
27    pub yes: bool,
28}
29
30/// How the running executable came to be where it is, which decides whether `update` may
31/// replace it.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub enum InstallMethod {
34    /// Downloaded from a release and placed by hand: `update` replaces it.
35    Release,
36    /// `cargo install`, under `$CARGO_HOME/bin`: cargo's records would no longer match a
37    /// replaced file, so `update` says to run `cargo install` instead.
38    Cargo,
39    /// `cargo binstall`, under `$CARGO_HOME/bin` and recorded in
40    /// `$CARGO_HOME/binstall/crates-v1.json`: `update` says to run `cargo binstall` again.
41    Binstall {
42        /// The crate it was installed from.
43        crate_name: String,
44        /// Where that crate came from.
45        source: BinstallSource,
46    },
47    /// A system or package-manager location (`/usr/bin`, the Nix store, Homebrew): the
48    /// package manager updates it.
49    PackageManager,
50}
51
52/// Where `cargo binstall` took a crate from, which decides how to run it again.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum BinstallSource {
55    /// crates.io: `cargo binstall <crate>`.
56    Registry,
57    /// A git repository, by its URL without the commit: `cargo binstall --git <url> <crate>`.
58    /// The crates that are only released on GitHub, such as the desktop apps.
59    Git(String),
60    /// A local manifest, or a source this does not know.
61    Other,
62}
63
64/// How the executable at `exe` was installed, judged by where it is and, under
65/// `$CARGO_HOME/bin`, by `cargo binstall`'s records. `cargo_home` is `$CARGO_HOME`, or
66/// `~/.cargo` when unset.
67pub fn install_method(exe: &Path, cargo_home: Option<&Path>) -> InstallMethod {
68    if let Some(home) = cargo_home
69        && exe.starts_with(home.join("bin"))
70    {
71        let records = std::fs::read_to_string(home.join("binstall").join("crates-v1.json"));
72        let bin = exe.file_name().and_then(|name| name.to_str()).map(|name| {
73            name.strip_suffix(std::env::consts::EXE_SUFFIX)
74                .unwrap_or(name)
75        });
76        return match (records, bin) {
77            (Ok(records), Some(bin)) => binstalled(&records, bin),
78            _ => None,
79        }
80        .unwrap_or(InstallMethod::Cargo);
81    }
82    // `/usr/local` is where binaries placed by hand go; the rest of `/usr` is the
83    // distribution's.
84    if exe.starts_with("/usr/local") {
85        return InstallMethod::Release;
86    }
87    const MANAGED: [&str; 7] = [
88        "/usr",
89        "/bin",
90        "/sbin",
91        "/nix",
92        "/opt/homebrew",
93        "/home/linuxbrew",
94        "/snap",
95    ];
96    if MANAGED.iter().any(|dir| exe.starts_with(dir)) {
97        return InstallMethod::PackageManager;
98    }
99    InstallMethod::Release
100}
101
102/// One crate in `$CARGO_HOME/binstall/crates-v1.json`, as far as this reads it.
103#[derive(Deserialize)]
104struct BinstallRecord {
105    name: String,
106    #[serde(default)]
107    source: Option<BinstallRecordSource>,
108    #[serde(default)]
109    bins: Vec<String>,
110}
111
112#[derive(Deserialize)]
113struct BinstallRecordSource {
114    source_type: String,
115    url: String,
116}
117
118/// How `cargo binstall` installed the binary `bin`, from `records`, the contents of
119/// `$CARGO_HOME/binstall/crates-v1.json`: one JSON object per crate, one after another. `None`
120/// when binstall did not install it, which leaves `cargo install`.
121///
122/// A binary binstall installed and `cargo install` replaced afterwards still reads as
123/// binstall's; running binstall again puts the release back, which is what `update` is for.
124fn binstalled(records: &str, bin: &str) -> Option<InstallMethod> {
125    serde_json::Deserializer::from_str(records)
126        .into_iter::<BinstallRecord>()
127        .map_while(std::result::Result::ok)
128        .filter(|record| record.bins.iter().any(|b| b == bin))
129        .last()
130        .map(|record| InstallMethod::Binstall {
131            source: match record.source {
132                Some(source) if source.source_type == "Registry" => BinstallSource::Registry,
133                Some(source) if source.source_type == "Git" => {
134                    let url = source
135                        .url
136                        .split_once('#')
137                        .map_or(source.url.as_str(), |(u, _)| u);
138                    BinstallSource::Git(url.to_owned())
139                }
140                _ => BinstallSource::Other,
141            },
142            crate_name: record.name,
143        })
144}
145
146/// This machine as release files name it: `linux-x86_64`, `macos-aarch64`,
147/// `windows-x86_64`.
148pub fn platform() -> String {
149    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
150}
151
152/// The file a release publishes `base` under for this machine:
153/// `<base>-<os>-<arch>`, with `.exe` on Windows.
154pub fn asset_name(base: &str) -> String {
155    format!("{base}-{}{}", platform(), std::env::consts::EXE_SUFFIX)
156}
157
158/// Write `bytes` beside `exe` and hand the new file to `replace`, which puts it in `exe`'s
159/// place. The staging file is removed afterwards, whatever `replace` did.
160///
161/// The staging file is in `exe`'s directory so the replacement is a rename on one file
162/// system, never a half-written executable.
163pub fn install(
164    bytes: &[u8],
165    exe: &Path,
166    replace: impl FnOnce(&Path) -> std::io::Result<()>,
167) -> Result<()> {
168    let dir = exe.parent().ok_or_else(|| {
169        Error::Io(std::io::Error::other(format!(
170            "{} has no directory",
171            exe.display()
172        )))
173    })?;
174    let mut staged = tempfile::Builder::new()
175        .prefix(".update-")
176        .tempfile_in(dir)?;
177    staged.write_all(bytes)?;
178    staged.as_file().sync_all()?;
179    #[cfg(unix)]
180    {
181        use std::os::unix::fs::PermissionsExt;
182        std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755))?;
183    }
184    replace(staged.path())?;
185    Ok(())
186}
187
188/// Download `url`, refusing anything larger than [`MAX_DOWNLOAD`].
189async fn download(client: &reqwest::Client, url: &str) -> Result<Vec<u8>> {
190    let response = client
191        .get(url)
192        .timeout(DOWNLOAD_TIMEOUT)
193        .send()
194        .await
195        .and_then(reqwest::Response::error_for_status)
196        .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
197    if response.content_length().is_some_and(|n| n > MAX_DOWNLOAD) {
198        return Err(Error::Http(format!(
199            "{url} is larger than {MAX_DOWNLOAD} bytes"
200        )));
201    }
202    let bytes = response
203        .bytes()
204        .await
205        .map_err(|e| Error::Http(format!("downloading {url}: {e}")))?;
206    if bytes.len() as u64 > MAX_DOWNLOAD {
207        return Err(Error::Http(format!(
208            "{url} is larger than {MAX_DOWNLOAD} bytes"
209        )));
210    }
211    Ok(bytes.to_vec())
212}
213
214/// Download `release`'s file for this machine.
215async fn fetch(
216    client: &reqwest::Client,
217    source: &ReleaseSource,
218    release: &Release,
219    base: &str,
220) -> Result<Vec<u8>> {
221    let name = asset_name(base);
222    let binary = release
223        .assets
224        .iter()
225        .find(|a| a.name == name)
226        .ok_or_else(|| {
227            Error::NoAsset(format!(
228                "{} {} has no {name}",
229                source.repository(),
230                release.version
231            ))
232        })?;
233    let bytes = download(client, &binary.download_url).await?;
234    if bytes.is_empty() {
235        return Err(Error::Http(format!("{name} downloaded empty")));
236    }
237    Ok(bytes)
238}
239
240/// Where the user installs what this binary is, by hand or with cargo, as advice.
241fn manual_advice(source: &ReleaseSource, release: &Release, method: &InstallMethod) -> String {
242    match (method, source.crate_name()) {
243        (InstallMethod::Cargo, Some(name)) => {
244            format!("installed with cargo; run: cargo install {name} --locked")
245        }
246        (InstallMethod::Cargo, None) => {
247            "installed with cargo; update it with cargo install".to_owned()
248        }
249        (InstallMethod::Binstall { crate_name, source }, _) => match source {
250            BinstallSource::Registry => {
251                format!("installed with cargo binstall; run: cargo binstall {crate_name}")
252            }
253            BinstallSource::Git(url) => format!(
254                "installed with cargo binstall; run: cargo binstall --git {url} {crate_name}"
255            ),
256            BinstallSource::Other => {
257                "installed with cargo binstall; update it with cargo binstall".to_owned()
258            }
259        },
260        (InstallMethod::PackageManager, _) => {
261            "installed by a package manager; update it with that".to_owned()
262        }
263        (InstallMethod::Release, _) => format!("download it from {}", release.url),
264    }
265}
266
267/// `$CARGO_HOME`, or `~/.cargo`.
268fn cargo_home() -> Option<PathBuf> {
269    std::env::var_os("CARGO_HOME")
270        .map(PathBuf::from)
271        .or_else(|| std::env::home_dir().map(|home| home.join(".cargo")))
272}
273
274/// Carry out `update` for the binary `name` at `current`, whose releases `source` names;
275/// returns the exit code.
276///
277/// Prints what it finds and does. Exit 0 is up to date, installed, or (with `--check`) a
278/// newer release found; 1 is a newer release this binary does not install itself.
279pub async fn run(
280    args: &UpdateArgs,
281    source: &ReleaseSource,
282    name: &str,
283    current: &str,
284) -> Result<i32> {
285    let current_v = semver::Version::parse(current).map_err(|e| {
286        Error::NotConfigured(format!(
287            "this binary's version {current:?} is not semver: {e}"
288        ))
289    })?;
290    let client = crate::client(&format!("{name}/{current}"))?;
291    let release = latest_release(&client, source).await?;
292    if release.version <= current_v {
293        println!(
294            "{name} {current} is up to date (latest release {})",
295            release.version
296        );
297        return Ok(0);
298    }
299    println!(
300        "{name} {} is available (installed: {current}): {}",
301        release.version, release.url
302    );
303    if args.check {
304        return Ok(0);
305    }
306
307    let Some(base) = source.asset_base() else {
308        println!(
309            "{name} does not update itself; {}",
310            manual_advice(source, &release, &InstallMethod::Release)
311        );
312        return Ok(1);
313    };
314    let exe = std::env::current_exe()?;
315    let exe = exe.canonicalize().unwrap_or(exe);
316    let method = install_method(&exe, cargo_home().as_deref());
317    if method != InstallMethod::Release {
318        println!(
319            "{} is {}",
320            exe.display(),
321            manual_advice(source, &release, &method)
322        );
323        return Ok(1);
324    }
325
326    if !args.yes
327        && !confirm(&format!(
328            "replace {} with {}?",
329            exe.display(),
330            release.version
331        ))?
332    {
333        println!("not updated");
334        return Ok(1);
335    }
336    let bytes = fetch(&client, source, &release, base).await?;
337    install(&bytes, &exe, |staged| self_replace::self_replace(staged))?;
338    println!(
339        "installed {name} {}; restart the {name} service to run it",
340        release.version
341    );
342    Ok(0)
343}
344
345/// Ask `question` on the terminal; only `y` or `yes` is a yes.
346fn confirm(question: &str) -> Result<bool> {
347    print!("{question} [y/N] ");
348    std::io::stdout().flush()?;
349    let mut answer = String::new();
350    std::io::stdin().lock().read_line(&mut answer)?;
351    Ok(matches!(
352        answer.trim().to_ascii_lowercase().as_str(),
353        "y" | "yes"
354    ))
355}
356
357#[cfg(test)]
358mod tests {
359    use super::*;
360
361    fn v(s: &str) -> semver::Version {
362        semver::Version::parse(s).unwrap()
363    }
364
365    #[test]
366    fn a_binary_is_replaced_only_where_it_was_placed_by_hand() {
367        let home = Path::new("/home/u/.cargo");
368        let method = |p: &str| install_method(Path::new(p), Some(home));
369        assert_eq!(method("/home/u/.cargo/bin/app"), InstallMethod::Cargo);
370        assert_eq!(method("/usr/bin/app"), InstallMethod::PackageManager);
371        assert_eq!(
372            method("/nix/store/abc-app/bin/app"),
373            InstallMethod::PackageManager
374        );
375        assert_eq!(
376            method("/opt/homebrew/bin/app"),
377            InstallMethod::PackageManager
378        );
379        assert_eq!(method("/usr/local/bin/app"), InstallMethod::Release);
380        assert_eq!(method("/home/u/.local/bin/app"), InstallMethod::Release);
381    }
382
383    #[test]
384    fn binstall_s_records_name_the_crate_and_where_it_came_from() {
385        let records = concat!(
386            r#"{"name":"dioxus-cli","version_req":"*","current_version":"0.7.3","#,
387            r#""source":{"source_type":"Registry","url":"https://github.com/rust-lang/crates.io-index"},"#,
388            r#""target":"x86_64-unknown-linux-gnu","bins":["dx"]}"#,
389            r#"{"name":"sapphire-journal-desktop","version_req":"*","current_version":"0.3.0","#,
390            r#""source":{"source_type":"Git","url":"https://github.com/sapphire-turtle/sapphire-journal#b05d5c2"},"#,
391            r#""target":"x86_64-unknown-linux-gnu","bins":["sapphire-journal-desktop"]}"#,
392        );
393        assert_eq!(
394            binstalled(records, "dx"),
395            Some(InstallMethod::Binstall {
396                crate_name: "dioxus-cli".to_owned(),
397                source: BinstallSource::Registry,
398            })
399        );
400        assert_eq!(
401            binstalled(records, "sapphire-journal-desktop"),
402            Some(InstallMethod::Binstall {
403                crate_name: "sapphire-journal-desktop".to_owned(),
404                source: BinstallSource::Git(
405                    "https://github.com/sapphire-turtle/sapphire-journal".to_owned()
406                ),
407            })
408        );
409        assert_eq!(binstalled(records, "sapphire-journal"), None);
410        assert_eq!(binstalled("", "dx"), None);
411    }
412
413    #[test]
414    fn a_binary_under_cargo_s_bin_is_binstall_s_only_when_it_says_so() {
415        let tmp = tempfile::tempdir().unwrap();
416        let exe = tmp
417            .path()
418            .join("bin")
419            .join(format!("dx{}", std::env::consts::EXE_SUFFIX));
420        assert_eq!(install_method(&exe, Some(tmp.path())), InstallMethod::Cargo);
421        std::fs::create_dir(tmp.path().join("binstall")).unwrap();
422        std::fs::write(
423            tmp.path().join("binstall").join("crates-v1.json"),
424            r#"{"name":"dioxus-cli","source":{"source_type":"Registry","url":""},"bins":["dx"]}"#,
425        )
426        .unwrap();
427        assert_eq!(
428            install_method(&exe, Some(tmp.path())),
429            InstallMethod::Binstall {
430                crate_name: "dioxus-cli".to_owned(),
431                source: BinstallSource::Registry,
432            }
433        );
434    }
435
436    #[test]
437    fn the_asset_names_this_machine() {
438        let name = asset_name("sapphire-bridge");
439        assert!(name.starts_with("sapphire-bridge-"));
440        assert!(name.contains(std::env::consts::OS));
441        assert!(name.contains(std::env::consts::ARCH));
442    }
443
444    #[test]
445    fn install_puts_the_bytes_in_place_and_leaves_no_staging_file() {
446        let tmp = tempfile::tempdir().unwrap();
447        let exe = tmp.path().join("app");
448        std::fs::write(&exe, b"old").unwrap();
449        install(b"new", &exe, |staged| {
450            std::fs::copy(staged, &exe).map(|_| ())
451        })
452        .unwrap();
453        assert_eq!(std::fs::read(&exe).unwrap(), b"new");
454        let left: Vec<_> = std::fs::read_dir(tmp.path()).unwrap().collect();
455        assert_eq!(left.len(), 1, "the staging file is gone");
456        #[cfg(unix)]
457        {
458            use std::os::unix::fs::PermissionsExt;
459            let staged_mode = std::fs::metadata(&exe).unwrap().permissions().mode();
460            assert_eq!(
461                staged_mode & 0o111,
462                0o111,
463                "the copy keeps the executable bit"
464            );
465        }
466    }
467
468    /// Serve the routes `routes` builds from the server's own root (path → body) on a
469    /// loopback port until the test ends; returns the root.
470    async fn serve(routes: impl FnOnce(&str) -> Vec<(String, Vec<u8>)>) -> String {
471        use tokio::io::{AsyncReadExt, AsyncWriteExt};
472        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
473        let root = format!("http://{}", listener.local_addr().unwrap());
474        let routes = routes(&root);
475        tokio::spawn(async move {
476            loop {
477                let (mut socket, _) = listener.accept().await.unwrap();
478                let mut buf = vec![0u8; 8192];
479                let n = socket.read(&mut buf).await.unwrap();
480                let request = String::from_utf8_lossy(&buf[..n]);
481                let path = request.split_whitespace().nth(1).unwrap_or("").to_owned();
482                let (status, body) = match routes.iter().find(|(p, _)| *p == path) {
483                    Some((_, body)) => ("200 OK", body.clone()),
484                    None => ("404 Not Found", Vec::new()),
485                };
486                let head = format!(
487                    "HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
488                    body.len()
489                );
490                socket.write_all(head.as_bytes()).await.unwrap();
491                socket.write_all(&body).await.unwrap();
492            }
493        });
494        root
495    }
496
497    const RELEASES: &str = "/repos/o/r/releases?per_page=100";
498
499    /// A repository with release 0.20.0 of `app`: its file for this machine.
500    async fn repository(binary: &[u8]) -> String {
501        let name = asset_name("app");
502        let binary = binary.to_vec();
503        serve(move |root| {
504            let releases = format!(
505                r#"[{{"tag_name":"v0.20.0","html_url":"{root}/r/v0.20.0","assets":[
506                    {{"name":"{name}","browser_download_url":"{root}/dl/{name}"}}]}}]"#
507            );
508            vec![
509                (RELEASES.to_owned(), releases.into_bytes()),
510                (format!("/dl/{name}"), binary),
511            ]
512        })
513        .await
514    }
515
516    #[tokio::test]
517    async fn a_release_is_fetched_end_to_end() {
518        let root = repository(b"new binary").await;
519        let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
520        let client = crate::client("test/0.0.0").unwrap();
521        let release = latest_release(&client, &source).await.unwrap();
522        assert_eq!(release.version, v("0.20.0"));
523        let bytes = fetch(&client, &source, &release, "app").await.unwrap();
524        assert_eq!(bytes, b"new binary");
525    }
526
527    #[tokio::test]
528    async fn an_empty_download_is_refused() {
529        let root = repository(b"").await;
530        let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
531        let client = crate::client("test/0.0.0").unwrap();
532        let release = latest_release(&client, &source).await.unwrap();
533        let err = fetch(&client, &source, &release, "app").await.unwrap_err();
534        assert!(matches!(err, Error::Http(_)), "{err}");
535    }
536
537    #[tokio::test]
538    async fn a_release_without_this_platforms_file_is_refused() {
539        let root = serve(|_| {
540            vec![(
541                RELEASES.to_owned(),
542                br#"[{"tag_name":"v0.20.0","html_url":"https://example.invalid","assets":[]}]"#
543                    .to_vec(),
544            )]
545        })
546        .await;
547        let source = ReleaseSource::github("o", "r").api_base(&root).asset("app");
548        let client = crate::client("test/0.0.0").unwrap();
549        let release = latest_release(&client, &source).await.unwrap();
550        let err = fetch(&client, &source, &release, "app").await.unwrap_err();
551        assert!(matches!(err, Error::NoAsset(_)), "{err}");
552    }
553}