Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat(linux): HTTP client, self-updater, and setup uninstaller (Part 6)

Jochen Kirstätter5898bf96423d
diff --git a/desktop/app/i18n/nectarlink_de.ts b/desktop/app/i18n/nectarlink_de.ts
index 962b83c..9d4adbd 100644
--- a/desktop/app/i18n/nectarlink_de.ts
+++ b/desktop/app/i18n/nectarlink_de.ts
@@ -7579,25 +7579,35 @@ Voraussetzungen
<context>
<name>Setup</name>
<message>
- <location filename="rust_strings.h" line="401" />
+ <location filename="rust_strings.h" line="402" />
<source>Couldn't start setup: %1</source>
<translation>Installation konnte nicht gestartet werden: %1</translation>
</message>
<message>
- <location filename="rust_strings.h" line="402" />
+ <location filename="rust_strings.h" line="403" />
+ <source>Couldn't uninstall NectarLink: %1</source>
+ <translation>NectarLink konnte nicht deinstalliert werden: %1</translation>
+ </message>
+ <message>
+ <location filename="rust_strings.h" line="404" />
<source>Setup is taking too long. Try again after restarting the PC.</source>
<translation>Die Installation dauert zu lange. Starte den PC neu und versuche es erneut.</translation>
</message>
<message>
- <location filename="rust_strings.h" line="403" />
+ <location filename="rust_strings.h" line="405" />
<source>Setup stopped with code %1.</source>
<translation>Installation mit Code %1 abgebrochen.</translation>
</message>
<message>
- <location filename="rust_strings.h" line="404" />
+ <location filename="rust_strings.h" line="406" />
<source>The uninstaller is missing. Reinstall NectarLink, then uninstall it.</source>
<translation>Das Deinstallationsprogramm fehlt. Installiere NectarLink erneut und deinstalliere es anschließend.</translation>
</message>
+ <message>
+ <location filename="rust_strings.h" line="407" />
+ <source>Uninstall stopped with code %1.</source>
+ <translation>Deinstallation mit Code %1 abgebrochen.</translation>
+ </message>
</context>
<context>
<name>SetupWindow</name>
diff --git a/desktop/app/i18n/nectarlink_zh_CN.ts b/desktop/app/i18n/nectarlink_zh_CN.ts
index f33756c..0b67d35 100644
--- a/desktop/app/i18n/nectarlink_zh_CN.ts
+++ b/desktop/app/i18n/nectarlink_zh_CN.ts
@@ -7575,25 +7575,35 @@ What it needs
<context>
<name>Setup</name>
<message>
- <location filename="rust_strings.h" line="401"/>
+ <location filename="rust_strings.h" line="402"/>
<source>Couldn&apos;t start setup: %1</source>
<translation>无法启动安装程序:%1</translation>
</message>
<message>
- <location filename="rust_strings.h" line="402"/>
+ <location filename="rust_strings.h" line="403"/>
+ <source>Couldn&apos;t uninstall NectarLink: %1</source>
+ <translation>无法卸载 NectarLink:%1</translation>
+ </message>
+ <message>
+ <location filename="rust_strings.h" line="404"/>
<source>Setup is taking too long. Try again after restarting the PC.</source>
<translation>安装时间过长。请重启电脑后再试。</translation>
</message>
<message>
- <location filename="rust_strings.h" line="403"/>
+ <location filename="rust_strings.h" line="405"/>
<source>Setup stopped with code %1.</source>
<translation>安装已停止,代码 %1。</translation>
</message>
<message>
- <location filename="rust_strings.h" line="404"/>
+ <location filename="rust_strings.h" line="406"/>
<source>The uninstaller is missing. Reinstall NectarLink, then uninstall it.</source>
<translation>缺少卸载程序。请重新安装 NectarLink,然后再卸载。</translation>
</message>
+ <message>
+ <location filename="rust_strings.h" line="407"/>
+ <source>Uninstall stopped with code %1.</source>
+ <translation>卸载已停止,代码 %1。</translation>
+ </message>
</context>
<context>
<name>SetupWindow</name>
diff --git a/desktop/app/i18n/rust_strings.h b/desktop/app/i18n/rust_strings.h
index 482f012..b765bd7 100644
--- a/desktop/app/i18n/rust_strings.h
+++ b/desktop/app/i18n/rust_strings.h
@@ -400,9 +400,11 @@ static const char *const nectarlink_rust_strings[] = {
QT_TRANSLATE_NOOP("SendTo", "The transfer didn't go through."), // desktop/app/src/send_to.rs
QT_TRANSLATE_NOOP("SendTo", "Waiting for %1…"), // desktop/app/src/send_to.rs
QT_TRANSLATE_NOOP("Setup", "Couldn't start setup: %1"), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "Couldn't uninstall NectarLink: %1"), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Setup", "Setup is taking too long. Try again after restarting the PC."), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Setup", "Setup stopped with code %1."), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Setup", "The uninstaller is missing. Reinstall NectarLink, then uninstall it."), // desktop/app/src/setup.rs
+ QT_TRANSLATE_NOOP("Setup", "Uninstall stopped with code %1."), // desktop/app/src/setup.rs
QT_TRANSLATE_NOOP("Timeline", "App window #%1"), // desktop/app/src/i18n.rs
QT_TRANSLATE_NOOP("Timeline", "Clip (removed from clipboard history)"), // desktop/app/src/bridge/timeline.rs
QT_TRANSLATE_NOOP("Timeline", "Copied image"), // desktop/app/src/bridge/timeline.rs
diff --git a/desktop/app/src/linux/http.rs b/desktop/app/src/linux/http.rs
index 01e2273..ae2b6b0 100644
--- a/desktop/app/src/linux/http.rs
+++ b/desktop/app/src/linux/http.rs
@@ -1,25 +1,237 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-#![allow(dead_code, unused_variables)]
+//! HTTPS client for Linux (`win::http` equivalent), used by the auto-updater
+//! and metadata checks. Uses `curl` (with `wget` fallback) so system CA
+//! certificates and proxy settings are respected without pulling in an extra
+//! TLS stack.
-use std::path::Path;
+use std::{
+ fs,
+ io::{Read, Write},
+ path::Path,
+ process::{Command, Stdio},
+ time::Duration,
+};
-pub fn get(_url: &str, _limit: usize) -> Result<Vec<u8>, String> {
- Err("not supported on Linux yet".into())
+/// Retry delays for transient failures in [`get_retrying`].
+const RETRY_DELAYS: [Duration; 2] = [Duration::from_secs(1), Duration::from_secs(3)];
+
+fn user_agent() -> String {
+ format!("NectarLink/{}", env!("CARGO_PKG_VERSION"))
+}
+
+fn validate_https(url: &str) -> Result<(), String> {
+ if !url.get(..8).is_some_and(|p| p.eq_ignore_ascii_case("https://")) {
+ return Err("only https:// URLs are fetched".into());
+ }
+ Ok(())
}
-pub fn get_retrying(_url: &str, _limit: usize) -> Result<Vec<u8>, String> {
- Err("not supported on Linux yet".into())
+
+/// Builds the `curl` argument list for fetching `url` with HTTPS-only redirect enforcement.
+fn curl_get_args(max_size: &str, ua: &str, url: &str) -> Vec<String> {
+ vec![
+ "-fsSL".into(),
+ "--proto".into(),
+ "=https".into(),
+ "--proto-redir".into(),
+ "=https".into(),
+ "--max-time".into(),
+ "60".into(),
+ "--max-filesize".into(),
+ max_size.into(),
+ "-A".into(),
+ ua.into(),
+ "--".into(),
+ url.into(),
+ ]
+}
+
+/// Builds the `wget` argument list for fetching `url` with HTTPS-only redirect enforcement.
+fn wget_get_args(ua: &str, url: &str) -> Vec<String> {
+ vec![
+ "-qO-".into(),
+ "--https-only".into(),
+ "--timeout=60".into(),
+ format!("--user-agent={ua}"),
+ "--".into(),
+ url.into(),
+ ]
}
+
+/// Fetches `url` over HTTPS, returning at most `limit` bytes.
+pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ validate_https(url)?;
+ let ua = user_agent();
+ let max_size = (limit.saturating_add(1)).to_string();
+
+ if let Ok(output) =
+ Command::new("curl").args(curl_get_args(&max_size, &ua, url)).stdin(Stdio::null()).output()
+ {
+ if output.status.success() {
+ if output.stdout.len() > limit {
+ return Err(format!("response exceeds {limit} bytes"));
+ }
+ return Ok(output.stdout);
+ }
+ // Exit code 63 from curl means `--max-filesize` was exceeded.
+ if output.status.code() == Some(63) {
+ return Err(format!("response exceeds {limit} bytes"));
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
+ return Err(if stderr.is_empty() {
+ format!("curl failed with status {}", output.status)
+ } else {
+ stderr
+ });
+ }
+
+ // Fallback to `wget`.
+ let output = Command::new("wget")
+ .args(wget_get_args(&ua, url))
+ .stdin(Stdio::null())
+ .output()
+ .map_err(|e| format!("neither curl nor wget is available: {e}"))?;
+ if !output.status.success() {
+ return Err(format!("wget failed with status {}", output.status));
+ }
+ if output.stdout.len() > limit {
+ return Err(format!("response exceeds {limit} bytes"));
+ }
+ Ok(output.stdout)
+}
+
+/// Fetches `url` with up to 3 attempts on transient errors.
+pub fn get_retrying(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ validate_https(url)?;
+ let mut delays = RETRY_DELAYS.iter();
+ loop {
+ match get(url, limit) {
+ Ok(bytes) => return Ok(bytes),
+ Err(err) => {
+ if err.contains("exceeds") {
+ return Err(err);
+ }
+ match delays.next() {
+ Some(&delay) => {
+ tracing::debug!(url, error = %err, ?delay, "retrying HTTPS request");
+ std::thread::sleep(delay);
+ }
+ None => return Err(err),
+ }
+ }
+ }
+ }
+}
+
+/// Downloads `url` over HTTPS to `file`, failing if it exceeds `limit` bytes,
+/// and reporting `(downloaded_bytes, total_bytes)` to `progress`.
pub fn download(
- _url: &str,
- _file: &Path,
- _limit: u64,
- _progress: impl FnMut(u64, u64),
+ url: &str,
+ file: &Path,
+ limit: u64,
+ mut progress: impl FnMut(u64, u64),
) -> Result<(), String> {
- Err("not supported on Linux yet".into())
+ validate_https(url)?;
+ if let Some(parent) = file.parent() {
+ fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+ let ua = user_agent();
+ let mut child = Command::new("curl")
+ .args([
+ "-fsSL",
+ "--proto",
+ "=https",
+ "--proto-redir",
+ "=https",
+ "--max-time",
+ "300",
+ "-A",
+ &ua,
+ "--",
+ url,
+ ])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .or_else(|_| {
+ Command::new("wget")
+ .args(["-qO-", "--https-only", "--timeout=300", &format!("--user-agent={ua}"), "--", url])
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ })
+ .map_err(|e| format!("neither curl nor wget is available: {e}"))?;
+
+ let mut stdout = child.stdout.take().ok_or_else(|| "missing downloader stdout".to_owned())?;
+ let mut out = {
+ use std::os::unix::fs::OpenOptionsExt;
+ fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(file)
+ .map_err(|e| e.to_string())?
+ };
+ let mut received = 0u64;
+ let mut buf = vec![0u8; 64 * 1024];
+ loop {
+ let n = stdout.read(&mut buf).map_err(|e| e.to_string())?;
+ if n == 0 {
+ break;
+ }
+ received += n as u64;
+ if received > limit {
+ let _ = child.kill();
+ let _ = fs::remove_file(file);
+ return Err(format!("download exceeds {limit} bytes"));
+ }
+ out.write_all(&buf[..n]).map_err(|e| e.to_string())?;
+ progress(received, 0);
+ }
+ out.flush().map_err(|e| e.to_string())?;
+ let status = child.wait().map_err(|e| e.to_string())?;
+ if !status.success() {
+ let _ = fs::remove_file(file);
+ return Err(format!("download failed with status {status}"));
+ }
+ progress(received, received);
+ Ok(())
+}
+
+/// Fetches a JSON document as a UTF-8 `String` (up to 2 MiB).
+pub fn get_json(url: &str) -> Result<String, String> {
+ let bytes = get_retrying(url, 2 * 1024 * 1024)?;
+ String::from_utf8(bytes).map_err(|e| e.to_string())
}
-pub fn get_json(_url: &str) -> Result<String, String> {
- Err("not supported on Linux yet".into())
+
+/// Downloads `url` to `dest` (up to 512 MiB).
+pub fn download_to_file(url: &str, dest: &Path, on_progress: impl FnMut(u64, u64)) -> Result<(), String> {
+ download(url, dest, 512 * 1024 * 1024, on_progress)
}
-pub fn download_to_file(_url: &str, _dest: &Path, _on_progress: impl FnMut(u64, u64)) -> Result<(), String> {
- Err("not supported on Linux yet".into())
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn refuses_plain_http_urls() {
+ assert!(get("http://example.com/releases", 1024).is_err());
+ assert!(get_retrying("http://example.com/releases", 1024).is_err());
+ assert!(download("http://example.com/setup", Path::new("out.bin"), 1024, |_, _| {}).is_err());
+ }
+
+ #[test]
+ fn curl_and_wget_args_enforce_https_redirects_and_end_of_options() {
+ let curl_args = curl_get_args("1025", "NectarLink/0.1", "https://example.com/feed.json");
+ assert!(curl_args.windows(2).any(|w| w[0] == "--proto" && w[1] == "=https"));
+ assert!(curl_args.windows(2).any(|w| w[0] == "--proto-redir" && w[1] == "=https"));
+ assert_eq!(&curl_args[curl_args.len() - 2..], ["--", "https://example.com/feed.json"]);
+
+ let wget_args = wget_get_args("NectarLink/0.1", "https://example.com/feed.json");
+ assert!(wget_args.iter().any(|a| a == "--https-only"));
+ assert_eq!(&wget_args[wget_args.len() - 2..], ["--", "https://example.com/feed.json"]);
+ }
}
diff --git a/desktop/app/src/setup.rs b/desktop/app/src/setup.rs
index 9928acd..d867df2 100644
--- a/desktop/app/src/setup.rs
+++ b/desktop/app/src/setup.rs
@@ -38,7 +38,8 @@ pub const ANDROID_URL: &str = "https://github.com/thtbee/nectarlink/releases/lat
const APP_EXE: &str = if cfg!(windows) { "nectarlink-desktop.exe" } else { "nectarlink-desktop" };
#[cfg(windows)]
const UNINSTALL_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\Nectarlink";
-const SETUP_COPY_NAME: &str = if cfg!(windows) { "Nectarlink Uninstall.exe" } else { "Nectarlink Uninstall" };
+#[cfg(windows)]
+const SETUP_COPY_NAME: &str = "Nectarlink Uninstall.exe";
#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
@@ -61,22 +62,82 @@ pub struct Installed {
pub version: String,
}
+#[cfg(windows)]
pub fn installed() -> Option<Installed> {
- #[cfg(windows)]
- {
- use windows::Win32::System::Registry::HKEY_LOCAL_MACHINE;
- let dir = crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "InstallLocation")?;
- let version =
- crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "DisplayVersion").unwrap_or_default();
- let dir = PathBuf::from(dir);
- dir.join(APP_EXE).is_file().then_some(Installed { dir, version })
- }
- #[cfg(not(windows))]
- {
+ use windows::Win32::System::Registry::HKEY_LOCAL_MACHINE;
+ let dir = crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "InstallLocation")?;
+ let version =
+ crate::win::reg_string(HKEY_LOCAL_MACHINE, UNINSTALL_KEY, "DisplayVersion").unwrap_or_default();
+ let dir = PathBuf::from(dir);
+ dir.join(APP_EXE).is_file().then_some(Installed { dir, version })
+}
+
+#[cfg(target_os = "linux")]
+pub fn installed() -> Option<Installed> {
+ if let Some(version) = dpkg_installed_version("nectarlink") {
+ let dir = PathBuf::from("/usr/bin");
+ if dir.join(APP_EXE).is_file() {
+ return Some(Installed { dir, version });
+ }
+ }
+ for candidate in ["/opt/nectarlink", "/usr/local/bin", "/usr/bin"] {
+ let dir = PathBuf::from(candidate);
+ let exe = dir.join(APP_EXE);
+ if exe.is_file() {
+ let version = read_installed_version(&dir, &exe).unwrap_or_default();
+ return Some(Installed { dir, version });
+ }
+ }
+ None
+}
+
+#[cfg(target_os = "linux")]
+fn dpkg_installed_version(pkg: &str) -> Option<String> {
+ let out = std::process::Command::new("dpkg-query")
+ .args(["-W", "-f=${db:Status-Status}\\t${Version}\\n", pkg])
+ .stdin(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .output()
+ .ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ parse_dpkg_query_output(&String::from_utf8_lossy(&out.stdout))
+}
+
+#[cfg(any(target_os = "linux", test))]
+fn parse_dpkg_query_output(output: &str) -> Option<String> {
+ let line = output.lines().next()?.trim();
+ let (status, version) = line.split_once('\t')?;
+ if status.eq_ignore_ascii_case("installed") && !version.trim().is_empty() {
+ Some(version.trim().to_owned())
+ } else {
None
}
}
+#[cfg(target_os = "linux")]
+fn read_installed_version(dir: &Path, exe: &Path) -> Option<String> {
+ if let Ok(text) = std::fs::read_to_string(dir.join("VERSION")) {
+ let trimmed = text.trim();
+ if !trimmed.is_empty() {
+ return Some(trimmed.to_owned());
+ }
+ }
+ let out = std::process::Command::new(exe)
+ .arg("--version")
+ .stdin(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .output()
+ .ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let text = String::from_utf8_lossy(&out.stdout);
+ let token = text.split_whitespace().last()?.trim();
+ (!token.is_empty()).then(|| token.to_owned())
+}
+
/// How this install relates to the copy already on the PC.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
@@ -120,7 +181,10 @@ impl Step {
match self {
Step::Closing => "Closing NectarLink",
Step::Files => "Copying files",
+ #[cfg(windows)]
Step::Firewall => "Allowing through Windows Firewall",
+ #[cfg(target_os = "linux")]
+ Step::Firewall => "Configure Linux firewall rules",
Step::Updates => "Setting up updates",
Step::Shortcuts => "Adding shortcuts",
Step::Cleanup => "Removing files",
@@ -178,6 +242,7 @@ pub fn install(installer: &Path, on_event: impl FnMut(Event)) -> Outcome {
/// Removes the copy in `installed` with administrator rights, then this
/// user's data.
+#[cfg(windows)]
pub fn remove(installed: &Path, mut on_event: impl FnMut(Event)) -> Outcome {
let uninstaller = installed.join("uninstall.exe");
if !uninstaller.is_file() {
@@ -198,6 +263,48 @@ pub fn remove(installed: &Path, mut on_event: impl FnMut(Event)) -> Outcome {
outcome
}
+#[cfg(target_os = "linux")]
+pub fn remove(installed: &Path, mut on_event: impl FnMut(Event)) -> Outcome {
+ on_event(Event::Step(Step::Closing));
+ let _ = crate::win::autostart::set_enabled(false);
+ crate::win::jumplist::unregister();
+ let _ = crate::send_to::remove_all();
+ crate::storage::unregister_all();
+
+ on_event(Event::Step(Step::Cleanup));
+ let res = if dpkg_installed_version("nectarlink").is_some()
+ || Path::new("/var/lib/dpkg/info/nectarlink.list").is_file()
+ {
+ crate::win::elevated::run_elevated(Path::new("dpkg"), &["-r", "nectarlink"])
+ } else if installed == Path::new("/opt/nectarlink") {
+ crate::win::elevated::run_elevated(
+ Path::new("rm"),
+ &["-rf", "--", "/opt/nectarlink", "/usr/local/bin/nectarlink-desktop"],
+ )
+ } else {
+ crate::win::elevated::run_elevated(
+ Path::new("rm"),
+ &[
+ "-rf",
+ "--",
+ "/opt/nectarlink",
+ "/usr/local/bin/nectarlink-desktop",
+ "/usr/bin/nectarlink-desktop",
+ ],
+ )
+ };
+ match res {
+ Ok(0) => {
+ remove_user_data();
+ on_event(Event::Done);
+ Outcome::Done
+ }
+ Ok(126 | 127) => Outcome::Declined,
+ Ok(code) => Outcome::Failed(tr!("Setup", "Uninstall stopped with code %1.", code)),
+ Err(e) => Outcome::Failed(tr!("Setup", "Couldn't uninstall NectarLink: %1", e)),
+ }
+}
+
/// Removes this user's settings, pairings, history and caches. Received
/// files, recordings and synced folders live elsewhere and stay.
pub fn remove_user_data() {
@@ -210,11 +317,17 @@ pub fn remove_user_data() {
}
/// `%LOCALAPPDATA%\Nectarlink`, the app's default data folder.
+#[cfg(windows)]
fn user_data_dir() -> Option<PathBuf> {
let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from)?;
local.is_absolute().then(|| local.join("Nectarlink"))
}
+#[cfg(target_os = "linux")]
+fn user_data_dir() -> Option<PathBuf> {
+ dirs::data_local_dir().map(|d| d.join("Nectarlink"))
+}
+
/// Runs `program` elevated with `params` and follows `progress` until it
/// reports done or an error. With `wait_for_exit`, the process ending also
/// ends the run (its exit code decides when the file says nothing).
@@ -288,35 +401,60 @@ fn new_events(path: &Path, read: &mut usize) -> Vec<Event> {
}
fn progress_file(what: &str) -> PathBuf {
- std::env::temp_dir().join(format!("nectarlink-{what}-{}.progress", std::process::id()))
+ #[cfg(target_os = "linux")]
+ {
+ use std::os::unix::fs::{DirBuilderExt, MetadataExt};
+ let uid = std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(0);
+ let dir = dirs::runtime_dir()
+ .or_else(dirs::cache_dir)
+ .filter(|p| p.is_absolute())
+ .map(|base| base.join("nectarlink"))
+ .unwrap_or_else(|| std::env::temp_dir().join(format!("nectarlink-{uid}")));
+ let _ = std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir);
+ dir.join(format!("nectarlink-{what}-{}.progress", std::process::id()))
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ std::env::temp_dir().join(format!("nectarlink-{what}-{}.progress", std::process::id()))
+ }
}
/// Starts the installed app as this user, not elevated. Through Explorer, so
/// it starts as a fresh process of the shell and inherits nothing from
/// whatever launched setup.
+#[cfg(windows)]
pub fn open_app(dir: &Path) -> Result<(), String> {
let app = dir.join(APP_EXE);
if !app.is_file() {
return Err(format!("{} is missing", app.display()));
}
- #[cfg(windows)]
- {
- std::process::Command::new("explorer.exe")
- .arg(&app)
- .creation_flags(DETACHED_PROCESS)
- .spawn()
- .map(|_| ())
- .map_err(|e| e.to_string())
- }
- #[cfg(not(windows))]
- {
- std::process::Command::new("open").arg(&app).spawn().map(|_| ()).map_err(|e| e.to_string())
+ std::process::Command::new("explorer.exe")
+ .arg(&app)
+ .creation_flags(DETACHED_PROCESS)
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+}
+
+#[cfg(target_os = "linux")]
+pub fn open_app(dir: &Path) -> Result<(), String> {
+ let app = dir.join(APP_EXE);
+ if !app.is_file() {
+ return Err(format!("{} is missing", app.display()));
}
+ std::process::Command::new(&app)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| e.to_string())
}
/// For `--remove` started from the installed folder: carries on from a copy
/// in a temporary folder, so the installed one can be deleted. `Ok(true)`
/// when the copy took over and this process should exit.
+#[cfg(windows)]
pub fn hand_over_removal(installed: &Path) -> Result<bool, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let temp = std::env::temp_dir();
@@ -340,7 +478,15 @@ pub fn hand_over_removal(installed: &Path) -> Result<bool, String> {
Ok(true)
}
+#[cfg(target_os = "linux")]
+pub fn hand_over_removal(_installed: &Path) -> Result<bool, String> {
+ // On Linux, open executables can be unlinked while running, and `installed`
+ // may be `/usr/bin` which must never be copied into `/tmp`.
+ Ok(false)
+}
+
/// Deletes this program's temporary copy once it has exited.
+#[cfg(windows)]
pub fn delete_own_copy_later() {
let Ok(exe) = std::env::current_exe() else { return };
let Some(dir) = exe.parent() else { return };
@@ -351,20 +497,35 @@ pub fn delete_own_copy_later() {
if !ours {
return;
}
- #[cfg(windows)]
- {
- let script = format!("/c ping -n 4 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display());
- let _ = std::process::Command::new("cmd.exe")
- .raw_arg(script)
- .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
- .spawn();
- }
- #[cfg(not(windows))]
- {
- let _ = std::fs::remove_dir_all(dir);
+ let script = format!("/c ping -n 4 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display());
+ let _ = std::process::Command::new("cmd.exe")
+ .raw_arg(script)
+ .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
+ .spawn();
+}
+
+#[cfg(target_os = "linux")]
+pub fn delete_own_copy_later() {
+ let Ok(exe) = std::env::current_exe() else { return };
+ let Some(dir) = exe.parent() else { return };
+ let temp = std::env::temp_dir();
+ let ours = dir.starts_with(&temp)
+ && dir.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("Nectarlink-uninstall-"));
+ if !ours {
+ return;
}
+ let _ = std::process::Command::new("sh")
+ .arg("-c")
+ .arg("sleep 3 && rm -rf \"$1\"")
+ .arg("sh")
+ .arg(dir)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn();
}
+#[cfg(any(windows, test))]
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
@@ -437,6 +598,13 @@ mod tests {
assert_eq!(kind(Some("0.2.0"), "0.1.0"), Kind::Older);
}
+ #[test]
+ fn dpkg_query_output_parses_only_installed_packages() {
+ assert_eq!(parse_dpkg_query_output("installed\t0.1.0\n"), Some("0.1.0".to_owned()));
+ assert_eq!(parse_dpkg_query_output("config-files\t0.1.0\n"), None);
+ assert_eq!(parse_dpkg_query_output("not-installed\t\n"), None);
+ }
+
#[test]
fn new_events_reads_only_what_was_added() {
let dir = std::env::temp_dir().join(format!("nectarlink-setup-test-{}", std::process::id()));
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index c894168..bab6f15 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -40,12 +40,10 @@ use std::{
use serde::Deserialize;
use sha2::{Digest, Sha256};
-#[cfg(windows)]
-use crate::win::autostart;
use crate::{
core_host,
state::Changes,
- win::{http, toast},
+ win::{autostart, http, toast},
};
const LATEST: &str = "https://api.github.com/repos/thtbee/nectarlink/releases/latest";
@@ -67,7 +65,6 @@ pub struct Update {
}
/// The scheduled task the installer registers (see the module docs).
-#[cfg(windows)]
pub const TASK: &str = "Nectarlink Update";
/// What the task runs: `nectarlink-desktop.exe --update-service`.
pub const SERVICE_ARG: &str = "--update-service";
@@ -106,10 +103,6 @@ pub fn set_auto_install(on: bool) {
/// Whether this copy updates itself (an installed one, not a build run
/// from its folder).
pub fn can_update() -> bool {
- #[cfg(not(windows))]
- return false;
-
- #[cfg(windows)]
std::env::current_exe().is_ok_and(|exe| autostart::is_installed(&exe))
}
@@ -221,18 +214,47 @@ fn latest() -> Result<Option<Update>, String> {
Ok(newer_release(release, env!("CARGO_PKG_VERSION")))
}
+#[cfg(windows)]
const INSTALLER_SUFFIX: &str =
if cfg!(target_arch = "aarch64") { "-arm64-setup.exe" } else { "-x64-setup.exe" };
+#[cfg(target_os = "linux")]
+const APPIMAGE_SUFFIXES: &[&str] = if cfg!(target_arch = "aarch64") {
+ &["-aarch64.AppImage", "_arm64.deb", "-linux-aarch64.tar.gz"]
+} else {
+ &["-x86_64.AppImage", "_amd64.deb", "-linux-x86_64.tar.gz"]
+};
+
+#[cfg(target_os = "linux")]
+const DEB_SUFFIXES: &[&str] = if cfg!(target_arch = "aarch64") {
+ &["_arm64.deb", "-aarch64.AppImage", "-linux-aarch64.tar.gz"]
+} else {
+ &["_amd64.deb", "-x86_64.AppImage", "-linux-x86_64.tar.gz"]
+};
+
/// The release as an update, if it's a newer published one with an
/// installer for this architecture and its sums.
+#[cfg(windows)]
fn newer_release(release: Release, current: &str) -> Option<Update> {
- if !cfg!(windows) {
- return None;
- }
newer_release_for(release, current, INSTALLER_SUFFIX)
}
+#[cfg(target_os = "linux")]
+fn newer_release(release: Release, current: &str) -> Option<Update> {
+ newer_release_linux(release, current, std::env::var_os("APPIMAGE").is_some())
+}
+
+#[cfg(target_os = "linux")]
+fn newer_release_linux(release: Release, current: &str, is_appimage: bool) -> Option<Update> {
+ let suffixes = if is_appimage { APPIMAGE_SUFFIXES } else { DEB_SUFFIXES };
+ for &suffix in suffixes {
+ if let Some(u) = newer_release_for(release.clone(), current, suffix) {
+ return Some(u);
+ }
+ }
+ None
+}
+
fn newer_release_for(release: Release, current: &str, suffix: &str) -> Option<Update> {
if release.draft || release.prerelease {
return None;
@@ -244,7 +266,9 @@ fn newer_release_for(release: Release, current: &str, suffix: &str) -> Option<Up
// The name becomes a file name under %TEMP%: a plain name only, never a path.
let installer = release.assets.iter().find(|a| {
a.name.ends_with(suffix)
- && a.name.starts_with("Nectarlink-")
+ && (a.name.starts_with("Nectarlink-")
+ || a.name.starts_with("nectarlink_")
+ || a.name.starts_with("nectarlink-"))
&& a.name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_'))
&& !a.name.contains("..")
})?;
@@ -317,21 +341,20 @@ fn quiet() -> bool {
}
/// Whether the installer registered [`TASK`] on this PC.
+#[cfg(windows)]
fn task_registered() -> bool {
- #[cfg(windows)]
- {
- std::process::Command::new("schtasks.exe")
- .args(["/Query", "/TN", TASK])
- .creation_flags(CREATE_NO_WINDOW)
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .status()
- .is_ok_and(|s| s.success())
- }
- #[cfg(not(windows))]
- {
- false
- }
+ std::process::Command::new("schtasks.exe")
+ .args(["/Query", "/TN", TASK])
+ .creation_flags(CREATE_NO_WINDOW)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .is_ok_and(|s| s.success())
+}
+
+#[cfg(target_os = "linux")]
+fn task_registered() -> bool {
+ false
}
/// Installs the update found: downloads it (reporting `progress(done,
@@ -340,28 +363,20 @@ fn task_registered() -> bool {
/// Blocking. Returns what went wrong, in words for the user. On success the
/// app is about to quit for the installer.
pub fn install(progress: impl FnMut(u64, u64)) -> Result<(), String> {
- #[cfg(not(windows))]
- {
- let _ = progress;
- Err("Updates are not supported on this platform.".into())
- }
- #[cfg(windows)]
- {
- let update = available().ok_or("There's no update to install.")?;
- let staged = stage(&update, progress).map_err(|e| {
- tracing::warn!(error = %e, "update download failed");
- e.for_user()
- })?;
- if task_registered() {
- match install_with_task(true) {
- Ok(()) => return Ok(()),
- Err(e) => {
- tracing::warn!(error = e, "the update task didn't start; asking for permission instead")
- }
+ let update = available().ok_or("There's no update to install.")?;
+ let staged = stage(&update, progress).map_err(|e| {
+ tracing::warn!(error = %e, "update download failed");
+ e.for_user()
+ })?;
+ if task_registered() {
+ match install_with_task(true) {
+ Ok(()) => return Ok(()),
+ Err(e) => {
+ tracing::warn!(error = e, "the update task didn't start; asking for permission instead")
}
}
- install_with_prompt(&update, &staged)
}
+ install_with_prompt(&update, &staged)
}
/// Why a download didn't produce a checked installer.
@@ -404,6 +419,7 @@ impl std::fmt::Display for StageError {
/// Where the app leaves a downloaded installer for the task:
/// `%ProgramData%\Nectarlink\updates`. Anyone may write here; the task only
/// runs a copy that matches the release's own sums.
+#[cfg(windows)]
fn staging_dir() -> PathBuf {
std::env::var_os("ProgramData")
.map(PathBuf::from)
@@ -413,6 +429,22 @@ fn staging_dir() -> PathBuf {
.join("updates")
}
+#[cfg(target_os = "linux")]
+fn current_euid() -> u32 {
+ use std::os::unix::fs::MetadataExt;
+ std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(0)
+}
+
+#[cfg(target_os = "linux")]
+fn staging_dir() -> PathBuf {
+ if let Some(base) = dirs::cache_dir().filter(|p| p.is_absolute()) {
+ base.join("nectarlink").join("updates")
+ } else {
+ let uid = current_euid();
+ std::env::temp_dir().join(format!("nectarlink-{uid}")).join("updates")
+ }
+}
+
/// The release's SHA-256 for its installer.
fn expected_hash(update: &Update) -> Result<String, StageError> {
let sums = http::get_retrying(&update.sums_url, 64 * 1024).map_err(StageError::Network)?;
@@ -440,7 +472,24 @@ fn sha256_file(path: &Path) -> std::io::Result<String> {
pub fn stage(update: &Update, progress: impl FnMut(u64, u64)) -> Result<PathBuf, StageError> {
let expected = expected_hash(update)?;
let dir = staging_dir();
- std::fs::create_dir_all(&dir).map_err(|e| StageError::Disk(e.to_string()))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::{DirBuilderExt, MetadataExt};
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(&dir)
+ .map_err(|e| StageError::Disk(e.to_string()))?;
+ let meta = std::fs::symlink_metadata(&dir).map_err(|e| StageError::Disk(e.to_string()))?;
+ let euid = current_euid();
+ if meta.file_type().is_symlink() || !meta.is_dir() || meta.uid() != euid {
+ return Err(StageError::Disk("untrusted staging directory".into()));
+ }
+ }
+ #[cfg(not(unix))]
+ {
+ std::fs::create_dir_all(&dir).map_err(|e| StageError::Disk(e.to_string()))?;
+ }
let path = dir.join(&update.installer_name);
let part = dir.join(format!("{}.part", update.installer_name));
// Older versions' files.
@@ -473,68 +522,69 @@ pub fn stage(update: &Update, progress: impl FnMut(u64, u64)) -> Result<PathBuf,
/// hidden relauncher opens the new version afterwards. `shown`: open its
/// window again (the user asked for the update) rather than start in the tray.
fn install_with_task(shown: bool) -> Result<(), String> {
+ let update = available().ok_or("no update")?;
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
+ spawn_relauncher(&exe, &update.version, shown)?;
+ let mut cmd = std::process::Command::new("schtasks.exe");
+ cmd.args(["/Run", "/TN", TASK]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
#[cfg(windows)]
- {
- let update = available().ok_or("no update")?;
- let exe = std::env::current_exe().map_err(|e| e.to_string())?;
- spawn_relauncher(&exe, &update.version, shown)?;
- let started = std::process::Command::new("schtasks.exe")
- .args(["/Run", "/TN", TASK])
- .creation_flags(CREATE_NO_WINDOW)
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .status()
- .map_err(|e| e.to_string())?;
- if !started.success() {
- return Err(format!("schtasks /Run: {started}"));
- }
- tracing::info!(version = update.version, "updating; quitting for the installer");
- crate::bridge::app::request_quit();
- Ok(())
- }
- #[cfg(not(windows))]
- {
- let _ = shown;
- Err("scheduled update task is only supported on Windows".into())
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ let started = cmd.status().map_err(|e| e.to_string())?;
+ if !started.success() {
+ return Err(format!("schtasks /Run: {started}"));
}
+ tracing::info!(version = update.version, "updating; quitting for the installer");
+ crate::bridge::app::request_quit();
+ Ok(())
}
/// A hidden PowerShell that waits (up to ten minutes) until `version` is
/// installed and the installer has finished, then opens the app again.
-#[allow(dead_code)]
+#[cfg(windows)]
fn spawn_relauncher(exe: &Path, version: &str, shown: bool) -> Result<(), String> {
- #[cfg(windows)]
- {
- // Both come from this program (its own path, and a version the release
- // check already parsed); checked again so they can't break out of the
- // script's quotes.
- let exe =
- exe.to_str().filter(|e| !e.contains('\'') && !e.contains('\n')).ok_or("unusual install path")?;
- if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
- return Err("unusual version".into());
- }
- let arguments = if shown { UPDATED_ARG.to_owned() } else { format!("--minimized {UPDATED_ARG}") };
- let script = relauncher_script(exe, version, &arguments);
- let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
- std::process::Command::new("powershell.exe")
- .args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
- .arg(data_encoding::BASE64.encode(&encoded))
- .creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS)
- .stdin(std::process::Stdio::null())
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .map(|_| ())
- .map_err(|e| format!("relauncher: {e}"))
- }
- #[cfg(not(windows))]
- {
- let _ = (exe, version, shown);
- Err("relauncher is not supported on non-Windows".into())
+ // Both come from this program (its own path, and a version the release
+ // check already parsed); checked again so they can't break out of the
+ // script's quotes.
+ let exe =
+ exe.to_str().filter(|e| !e.contains('\'') && !e.contains('\n')).ok_or("unusual install path")?;
+ if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
+ return Err("unusual version".into());
+ }
+ let arguments = if shown { UPDATED_ARG.to_owned() } else { format!("--minimized {UPDATED_ARG}") };
+ let script = relauncher_script(exe, version, &arguments);
+ let encoded: Vec<u8> = script.encode_utf16().flat_map(u16::to_le_bytes).collect();
+ let mut cmd = std::process::Command::new("powershell.exe");
+ cmd.args(["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-EncodedCommand"])
+ .arg(data_encoding::BASE64.encode(&encoded))
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null());
+ cmd.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
+ cmd.spawn().map(|_| ()).map_err(|e| format!("relauncher: {e}"))
+}
+
+#[cfg(target_os = "linux")]
+fn spawn_relauncher(exe: &Path, version: &str, shown: bool) -> Result<(), String> {
+ let exe =
+ exe.to_str().filter(|e| !e.contains('\'') && !e.contains('\n')).ok_or("unusual install path")?;
+ if !version.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) {
+ return Err("unusual version".into());
+ }
+ let mut cmd = std::process::Command::new("sh");
+ cmd.arg("-c").arg("sleep 2 && exec \"$@\"").arg("sh").arg(exe);
+ if !shown {
+ cmd.arg("--minimized");
}
+ cmd.arg(UPDATED_ARG);
+ cmd.stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| format!("relauncher: {e}"))
}
-#[allow(dead_code)]
+#[cfg_attr(target_os = "linux", allow(dead_code))]
fn relauncher_script(exe: &str, version: &str, arguments: &str) -> String {
let start = if arguments.is_empty() {
format!("Start-Process -FilePath '{exe}'")
@@ -605,12 +655,10 @@ pub fn run_service() -> ExitCode {
}
};
// Not waited for: the installer replaces this program, which must not be running.
- #[cfg(windows)]
let mut cmd = std::process::Command::new(&path);
+ cmd.arg("/S");
#[cfg(windows)]
- cmd.arg("/S").creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
- #[cfg(not(windows))]
- let mut cmd = std::process::Command::new(&path);
+ cmd.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
match cmd.spawn() {
Ok(_) => {
log(&format!("installing {}", update.version));
@@ -633,6 +681,7 @@ fn unix_seconds_now() -> String {
/// can change: Windows' `SystemTemp` (older Windows: the SYSTEM account's
/// temp folder, whose new subfolders users can't write to). Earlier ones are
/// removed first (in `SystemTemp` only, where nobody else can create them).
+#[cfg(windows)]
fn service_dir() -> std::io::Result<PathBuf> {
let windows =
std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
@@ -659,6 +708,20 @@ fn service_dir() -> std::io::Result<PathBuf> {
Ok(dir)
}
+#[cfg(target_os = "linux")]
+fn service_dir() -> std::io::Result<PathBuf> {
+ use std::os::unix::fs::DirBuilderExt;
+ let parent = PathBuf::from("/var/cache");
+ let mut random = [0u8; 8];
+ if !crate::win::secure_random(&mut random) {
+ return Err(std::io::Error::other("no secure random source"));
+ }
+ let name = format!("nectarlink-update-{}", random.iter().map(|b| format!("{b:02x}")).collect::<String>());
+ let dir = parent.join(name);
+ std::fs::DirBuilder::new().mode(0o700).create(&dir)?;
+ Ok(dir)
+}
+
/// The installer in `dir` (only SYSTEM can write there), checked against
/// the release's sums: copied from the app's download when that matches,
/// downloaded otherwise. Errors are for the log.
@@ -684,7 +747,7 @@ fn download_verified(update: &Update, dir: &Path) -> Result<PathBuf, String> {
/// The installer with Windows' administrator prompt (no update task): a
/// fresh copy of the download in this user's temp folder, checked again, so
/// what runs is what was checked.
-#[allow(dead_code)]
+#[cfg(windows)]
fn install_with_prompt(update: &Update, staged: &Path) -> Result<(), String> {
let failed = |e: String| {
tracing::warn!(error = e, "update failed");
@@ -710,6 +773,76 @@ fn install_with_prompt(update: &Update, staged: &Path) -> Result<(), String> {
Ok(())
}
+/// Root-executed shell script that copies a user-staged `.deb` into a
+/// root-owned `0700` directory (`/var/cache/nectarlink-update`), verifies its
+/// SHA-256 digest as root on the root-owned copy, and only then runs
+/// `dpkg -i`. Prevents TOCTOU replacement in the user-writable cache directory.
+#[cfg(target_os = "linux")]
+const PRIVILEGED_DEB_INSTALL_SCRIPT: &str = "\
+dir=\"/var/cache/nectarlink-update\"\n\
+rm -rf -- \"$dir\"\n\
+install -d -m 0700 -o 0 -g 0 \"$dir\"\n\
+trap 'rm -rf -- \"$dir\"' EXIT\n\
+dst=\"$dir/nectarlink-update.deb\"\n\
+install -m 0600 -o 0 -g 0 \"$1\" \"$dst\"\n\
+printf '%s %s\\n' \"$2\" \"$dst\" | sha256sum -c --status -\n\
+dpkg -i -- \"$dst\"\n";
+
+#[cfg(target_os = "linux")]
+fn install_with_prompt(update: &Update, staged: &Path) -> Result<(), String> {
+ use std::os::unix::fs::PermissionsExt;
+
+ let failed = |e: String| {
+ tracing::warn!(error = e, "update failed");
+ tr!("Updater", "The update couldn't be started. Try again.")
+ };
+ let expected = expected_hash(update).map_err(|e| e.for_user())?;
+ if expected.len() != 64 || !expected.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Err(StageError::Damaged.for_user());
+ }
+ if sha256_file(staged).map_err(|e| failed(e.to_string()))? != expected {
+ let _ = std::fs::remove_file(staged);
+ return Err(StageError::Damaged.for_user());
+ }
+
+ let staged_name = staged.file_name().and_then(|s| s.to_str()).unwrap_or_default();
+ if let Some(appimage_os) = std::env::var_os("APPIMAGE")
+ && staged_name.ends_with(".AppImage")
+ {
+ let appimage_path = PathBuf::from(appimage_os);
+ let new_path = appimage_path.with_extension("AppImage.new");
+ std::fs::copy(staged, &new_path).map_err(|e| failed(e.to_string()))?;
+ std::fs::set_permissions(&new_path, std::fs::Permissions::from_mode(0o755))
+ .map_err(|e| failed(e.to_string()))?;
+ std::fs::rename(&new_path, &appimage_path).map_err(|e| failed(e.to_string()))?;
+ spawn_relauncher(&appimage_path, &update.version, true)?;
+ crate::bridge::app::request_quit();
+ return Ok(());
+ }
+
+ if staged_name.ends_with(".deb") {
+ let staged_str = staged.to_string_lossy();
+ let code = crate::win::elevated::run_elevated(
+ Path::new("sh"),
+ &["-e", "-c", PRIVILEGED_DEB_INSTALL_SCRIPT, "sh", &staged_str, &expected],
+ )
+ .map_err(failed)?;
+ if code != 0 {
+ return Err(failed(format!("privileged .deb install exited with status {code}")));
+ }
+ if let Ok(exe) = std::env::current_exe() {
+ let _ = spawn_relauncher(&exe, &update.version, true);
+ }
+ crate::bridge::app::request_quit();
+ return Ok(());
+ }
+
+ if crate::win::shell::open_url(&update.notes_url).is_err() {
+ return Err(tr!("Updater", "The update couldn't be started. Try again."));
+ }
+ Ok(())
+}
+
/// The flag the relauncher passes to the new version.
pub const UPDATED_ARG: &str = "--updated";
@@ -779,6 +912,23 @@ fn after_start(shown: bool, title: String, body: String) {
});
}
+impl Clone for Asset {
+ fn clone(&self) -> Self {
+ Self { name: self.name.clone(), browser_download_url: self.browser_download_url.clone() }
+ }
+}
+impl Clone for Release {
+ fn clone(&self) -> Self {
+ Self {
+ tag_name: self.tag_name.clone(),
+ html_url: self.html_url.clone(),
+ draft: self.draft,
+ prerelease: self.prerelease,
+ assets: self.assets.clone(),
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -809,6 +959,14 @@ mod tests {
name: "Nectarlink-9.0.0-arm64-setup.exe".into(),
browser_download_url: "https://x/setup-arm64".into(),
},
+ Asset {
+ name: "Nectarlink-9.0.0-x86_64.AppImage".into(),
+ browser_download_url: "https://x/appimage-x64".into(),
+ },
+ Asset {
+ name: "nectarlink_9.0.0_amd64.deb".into(),
+ browser_download_url: "https://x/deb-amd64".into(),
+ },
Asset { name: "SHA256SUMS.txt".into(), browser_download_url: "https://x/sums".into() },
],
}
@@ -882,6 +1040,37 @@ mod tests {
assert!(newer_release(no_sums, "0.0.1").is_none());
}
+ #[test]
+ fn matches_linux_appimage_and_deb_assets() {
+ let appimage = newer_release_for(release("v9.0.0"), "0.0.1", "-x86_64.AppImage").unwrap();
+ assert_eq!(
+ (appimage.installer_name.as_str(), appimage.installer_url.as_str()),
+ ("Nectarlink-9.0.0-x86_64.AppImage", "https://x/appimage-x64")
+ );
+ let deb = newer_release_for(release("v9.0.0"), "0.0.1", "_amd64.deb").unwrap();
+ assert_eq!(
+ (deb.installer_name.as_str(), deb.installer_url.as_str()),
+ ("nectarlink_9.0.0_amd64.deb", "https://x/deb-amd64")
+ );
+ #[cfg(target_os = "linux")]
+ {
+ let picked_appimage = newer_release_linux(release("v9.0.0"), "0.0.1", true).unwrap();
+ assert!(picked_appimage.installer_name.ends_with(".AppImage"));
+ let picked_deb = newer_release_linux(release("v9.0.0"), "0.0.1", false).unwrap();
+ assert!(picked_deb.installer_name.ends_with(".deb"));
+ assert!(PRIVILEGED_DEB_INSTALL_SCRIPT.contains("install -d -m 0700 -o 0 -g 0"));
+ assert!(PRIVILEGED_DEB_INSTALL_SCRIPT.contains("sha256sum -c --status -"));
+ assert!(PRIVILEGED_DEB_INSTALL_SCRIPT.contains("dpkg -i -- \"$dst\""));
+ }
+ }
+
+ #[test]
+ fn linux_staging_dir_is_absolute_and_under_nectarlink_updates() {
+ let dir = staging_dir();
+ assert!(dir.is_absolute(), "staging_dir must be absolute: {}", dir.display());
+ assert!(dir.ends_with("updates"));
+ }
+
#[test]
fn finds_the_installer_hash() {
let hash = "a".repeat(64);