Skip to content

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

fix(desktop): integrate Part 6 review fixes and fix macOS cfg coverage

Jochen Kirstätterea0ba788c6af
diff --cc desktop/app/src/linux/http.rs
index ae2b6b0,01e2273..773fc9c
--- a/desktop/app/src/linux/http.rs
+++ b/desktop/app/src/linux/http.rs
@@@ -1,237 -1,25 +1,506 @@@
// 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},
++ io::{BufRead, BufReader, Read, Write},
+ path::Path,
+ process::{Command, Stdio},
- time::Duration,
++ sync::mpsc,
++ time::{Duration, Instant},
+};
- /// Retry delays for transient failures in [`get_retrying`].
- const RETRY_DELAYS: [Duration; 2] = [Duration::from_secs(1), Duration::from_secs(3)];
-pub fn get(_url: &str, _limit: usize) -> Result<Vec<u8>, String> {
- Err("not supported on Linux yet".into())
++/// Tries in a row without progress before a download gives up.
++const ATTEMPTS: u32 = 6;
++
++/// Waits between tries; the last one repeats.
++const BACKOFF: [Duration; 5] = [
++ Duration::from_secs(1),
++ Duration::from_secs(2),
++ Duration::from_secs(5),
++ Duration::from_secs(10),
++ Duration::from_secs(20),
++];
+
+fn user_agent() -> String {
- format!("NectarLink/{}", env!("CARGO_PKG_VERSION"))
++ format!("Nectarlink/{} (Linux)", 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());
++ return Err("only https".into());
+ }
+ Ok(())
+}
+
+/// 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(),
++ "-sSL".into(),
++ "-D".into(),
++ "/dev/stderr".into(),
+ "--proto".into(),
+ "=https".into(),
+ "--proto-redir".into(),
+ "=https".into(),
++ "--connect-timeout".into(),
++ "30".into(),
+ "--max-time".into(),
+ "60".into(),
+ "--max-filesize".into(),
+ max_size.into(),
++ "-H".into(),
++ "Accept: application/vnd.github+json, application/octet-stream".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(),
++ "-qSO-".into(),
+ "--https-only".into(),
+ "--timeout=60".into(),
++ "--header=Accept: application/vnd.github+json, application/octet-stream".into(),
+ format!("--user-agent={ua}"),
+ "--".into(),
+ url.into(),
+ ]
+}
+
++#[derive(Debug, Default, Clone, PartialEq, Eq)]
++struct ResponseHeaders {
++ status: u32,
++ content_length: Option<u64>,
++ range_total: Option<u64>,
++}
++
++/// Parses an HTTP status line (`HTTP/1.1 200 OK` or `HTTP/2 404`).
++fn parse_status_line(line: &str) -> Option<u32> {
++ let trimmed = line.trim();
++ let rest = trimmed.strip_prefix("HTTP/")?;
++ let (_, after_ver) = rest.split_once(char::is_whitespace)?;
++ let code_str = after_ver.split_whitespace().next()?;
++ code_str.parse::<u32>().ok()
++}
++
++/// The full size from a `Content-Range` header (`bytes 100-199/200`).
++fn range_total(header: &str) -> Option<u64> {
++ header.rsplit_once('/')?.1.trim().parse().ok().filter(|&n| n > 0)
+ }
-pub fn get_retrying(_url: &str, _limit: usize) -> Result<Vec<u8>, String> {
- Err("not supported on Linux yet".into())
++
++/// Extracts the final HTTP status code from raw header output (`curl -D` or `wget -S`).
++fn parse_last_http_status(stderr_text: &str) -> Option<u32> {
++ stderr_text.lines().filter_map(parse_status_line).next_back()
+ }
++
++/// Reads response header blocks from `stderr` until the final non-1xx, non-3xx
++/// response header block completes, then returns its parsed headers and drains
++/// the remainder of `stderr`.
++fn spawn_header_reader(stderr: std::process::ChildStderr) -> mpsc::Receiver<ResponseHeaders> {
++ let (tx, rx) = mpsc::sync_channel(1);
++ std::thread::spawn(move || {
++ let mut reader = BufReader::new(stderr);
++ let mut line = String::new();
++ let mut current: Option<ResponseHeaders> = None;
++ let mut sent = false;
++
++ loop {
++ line.clear();
++ let Ok(n) = reader.read_line(&mut line) else { break };
++ if n == 0 {
++ break;
++ }
++ if sent {
++ continue;
++ }
++ let trimmed = line.trim();
++ if let Some(code) = parse_status_line(trimmed) {
++ current = Some(ResponseHeaders { status: code, content_length: None, range_total: None });
++ continue;
++ }
++ if let Some(ref mut hdrs) = current {
++ if trimmed.is_empty() {
++ let code = hdrs.status;
++ if !(100..200).contains(&code) && !(300..400).contains(&code) {
++ let _ = tx.send(hdrs.clone());
++ sent = true;
++ }
++ current = None;
++ } else if let Some((name, val)) = trimmed.split_once(':') {
++ let name = name.trim();
++ let val = val.trim();
++ if name.eq_ignore_ascii_case("content-length") {
++ hdrs.content_length = val.parse::<u64>().ok();
++ } else if name.eq_ignore_ascii_case("content-range") {
++ hdrs.range_total = range_total(val);
++ }
++ }
++ }
++ }
++ if !sent && let Some(hdrs) = current {
++ let _ = tx.send(hdrs);
++ }
++ });
++ rx
++}
++
+/// 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 let Ok(mut child) = Command::new("curl")
++ .args(curl_get_args(&max_size, &ua, url))
++ .stdin(Stdio::null())
++ .stdout(Stdio::piped())
++ .stderr(Stdio::piped())
++ .spawn()
+ {
- if output.status.success() {
- if output.stdout.len() > limit {
- return Err(format!("response exceeds {limit} bytes"));
- }
- return Ok(output.stdout);
++ let mut stdout = child.stdout.take().ok_or_else(|| "missing curl stdout".to_owned())?;
++ let mut stderr = child.stderr.take().ok_or_else(|| "missing curl stderr".to_owned())?;
++ let stderr_handle = std::thread::spawn(move || {
++ let mut s = String::new();
++ let _ = stderr.read_to_string(&mut s);
++ s
++ });
++ let mut body = Vec::new();
++ let read_res = (&mut stdout).take(limit as u64 + 1).read_to_end(&mut body);
++ if body.len() > limit {
++ let _ = child.kill();
++ let _ = child.wait();
++ return Err("too large".into());
+ }
- // Exit code 63 from curl means `--max-filesize` was exceeded.
- if output.status.code() == Some(63) {
- return Err(format!("response exceeds {limit} bytes"));
++ let status = child.wait().map_err(|e| e.to_string())?;
++ let stderr_text = stderr_handle.join().unwrap_or_default();
++ read_res.map_err(|e| e.to_string())?;
++
++ if status.code() == Some(63) {
++ return Err("too large".into());
+ }
- 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
- });
++ if let Some(http_code) = parse_last_http_status(&stderr_text)
++ && http_code != 200
++ {
++ return Err(format!("HTTP {http_code}"));
++ }
++ if !status.success() {
++ let msg = stderr_text.lines().last().unwrap_or("").trim();
++ return Err(if msg.is_empty() {
++ format!("curl failed with status {status}")
++ } else {
++ msg.to_owned()
++ });
++ }
++ return Ok(body);
+ }
+
- // Fallback to `wget`.
- let output = Command::new("wget")
++ // Fallback to `wget` with bounded stdout read.
++ let mut child = Command::new("wget")
+ .args(wget_get_args(&ua, url))
+ .stdin(Stdio::null())
- .output()
++ .stdout(Stdio::piped())
++ .stderr(Stdio::piped())
++ .spawn()
+ .map_err(|e| format!("neither curl nor wget is available: {e}"))?;
- if !output.status.success() {
- return Err(format!("wget failed with status {}", output.status));
++
++ let mut stdout = child.stdout.take().ok_or_else(|| "missing wget stdout".to_owned())?;
++ let mut stderr = child.stderr.take().ok_or_else(|| "missing wget stderr".to_owned())?;
++ let stderr_handle = std::thread::spawn(move || {
++ let mut s = String::new();
++ let _ = stderr.read_to_string(&mut s);
++ s
++ });
++ let mut body = Vec::new();
++ let read_res = (&mut stdout).take(limit as u64 + 1).read_to_end(&mut body);
++ if body.len() > limit {
++ let _ = child.kill();
++ let _ = child.wait();
++ return Err("too large".into());
+ }
- if output.stdout.len() > limit {
- return Err(format!("response exceeds {limit} bytes"));
++ let status = child.wait().map_err(|e| e.to_string())?;
++ let stderr_text = stderr_handle.join().unwrap_or_default();
++ read_res.map_err(|e| e.to_string())?;
++
++ if let Some(http_code) = parse_last_http_status(&stderr_text)
++ && http_code != 200
++ {
++ return Err(format!("HTTP {http_code}"));
+ }
- Ok(output.stdout)
++ if !status.success() {
++ return Err(format!("wget failed with status {status}"));
++ }
++ Ok(body)
+}
+
- /// Fetches `url` with up to 3 attempts on transient errors.
++/// Network trouble or a server hiccup, worth another try. Not missing
++/// files, refusals or a body that's too large.
++fn retryable(error: &str) -> bool {
++ match error.strip_prefix("HTTP ").and_then(|code| code.parse::<u32>().ok()) {
++ Some(code) => code >= 500 || code == 408 || code == 429,
++ None => !matches!(error, "too large" | "only https") && !error.contains("exceeds"),
++ }
++}
++
++/// Fetches `url` retrying transient network errors a few times.
+pub fn get_retrying(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ validate_https(url)?;
- let mut delays = RETRY_DELAYS.iter();
++ let mut attempt = 0;
+ 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),
- }
++ Ok(body) => return Ok(body),
++ Err(e) if attempt + 1 < ATTEMPTS && retryable(&e) => {
++ tracing::info!(error = e, attempt, "retrying");
++ std::thread::sleep(BACKOFF[(attempt as usize).min(BACKOFF.len() - 1)]);
++ attempt += 1;
+ }
++ Err(e) => return Err(e),
+ }
+ }
+}
+
- /// Downloads `url` over HTTPS to `file`, failing if it exceeds `limit` bytes,
- /// and reporting `(downloaded_bytes, total_bytes)` to `progress`.
++/// Downloads `url` into `file`, continuing from what `file` already holds
++/// (a download cut short earlier, even by a restart). Retries network
++/// errors, giving up after [`ATTEMPTS`] tries in a row that got nowhere.
++/// `progress(done, total)` reports as it goes (`total` is 0 when unknown).
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 mut failures = 0;
++ loop {
++ let before = file.metadata().map(|m| m.len()).unwrap_or(0);
++ match download_once(url, file, limit, &mut progress) {
++ Ok(()) => return Ok(()),
++ Err(e) if retryable(&e) => {
++ let after = file.metadata().map(|m| m.len()).unwrap_or(0);
++ failures = if after > before { 1 } else { failures + 1 };
++ if failures >= ATTEMPTS {
++ return Err(e);
++ }
++ tracing::info!(error = e, done = after, "download interrupted; resuming");
++ std::thread::sleep(BACKOFF[(failures as usize - 1).min(BACKOFF.len() - 1)]);
++ }
++ Err(e) => return Err(e),
++ }
++ }
+ }
-pub fn get_json(_url: &str) -> Result<String, String> {
- Err("not supported on Linux yet".into())
++
++fn download_once(
++ url: &str,
++ file: &Path,
++ limit: u64,
++ progress: &mut impl FnMut(u64, u64),
++) -> Result<(), String> {
++ let have = file.metadata().map(|m| m.len()).unwrap_or(0);
+ let ua = user_agent();
++
++ let mut curl_args = vec![
++ "-sSL".to_owned(),
++ "-D".to_owned(),
++ "/dev/stderr".to_owned(),
++ "--proto".to_owned(),
++ "=https".to_owned(),
++ "--proto-redir".to_owned(),
++ "=https".to_owned(),
++ "--connect-timeout".to_owned(),
++ "30".to_owned(),
++ "--speed-time".to_owned(),
++ "60".to_owned(),
++ "--speed-limit".to_owned(),
++ "1".to_owned(),
++ "-H".to_owned(),
++ "Accept: application/vnd.github+json, application/octet-stream".to_owned(),
++ "-A".to_owned(),
++ ua.clone(),
++ ];
++ if have > 0 {
++ curl_args.push("-H".to_owned());
++ curl_args.push(format!("Range: bytes={have}-"));
++ }
++ curl_args.push("--".to_owned());
++ curl_args.push(url.to_owned());
++
+ let mut child = Command::new("curl")
- .args([
- "-fsSL",
- "--proto",
- "=https",
- "--proto-redir",
- "=https",
- "--max-time",
- "300",
- "-A",
- &ua,
- "--",
- url,
- ])
++ .args(&curl_args)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .or_else(|_| {
++ let mut wget_args = vec![
++ "-qSO-".to_owned(),
++ "--https-only".to_owned(),
++ "--timeout=60".to_owned(),
++ "--header=Accept: application/vnd.github+json, application/octet-stream".to_owned(),
++ format!("--user-agent={ua}"),
++ ];
++ if have > 0 {
++ wget_args.push(format!("--header=Range: bytes={have}-"));
++ }
++ wget_args.push("--".to_owned());
++ wget_args.push(url.to_owned());
+ Command::new("wget")
- .args(["-qO-", "--https-only", "--timeout=300", &format!("--user-agent={ua}"), "--", url])
++ .args(&wget_args)
+ .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 stderr = child.stderr.take().ok_or_else(|| "missing downloader stderr".to_owned())?;
++ let hdr_rx = spawn_header_reader(stderr);
++
++ let hdrs = match hdr_rx.recv_timeout(Duration::from_secs(60)) {
++ Ok(h) => h,
++ Err(_) => {
++ let _ = child.kill();
++ let status = child.wait().map_err(|e| e.to_string())?;
++ return Err(format!("download failed before response headers ({status})"));
++ }
++ };
++
++ let (append, total) = match hdrs.status {
++ 206 => (true, hdrs.range_total.or_else(|| hdrs.content_length.map(|l| have + l)).unwrap_or(0)),
++ 200 => (false, hdrs.content_length.unwrap_or(0)),
++ 416 if have > 0 => {
++ let _ = child.kill();
++ let _ = child.wait();
++ return Ok(());
++ }
++ status => {
++ let _ = child.kill();
++ let _ = child.wait();
++ return Err(format!("HTTP {status}"));
++ }
++ };
++
++ if total > limit {
++ let _ = child.kill();
++ let _ = child.wait();
++ return Err("too large".into());
++ }
++
+ let mut out = {
+ use std::os::unix::fs::OpenOptionsExt;
+ fs::OpenOptions::new()
- .write(true)
+ .create(true)
- .truncate(true)
++ .write(true)
++ .append(append)
++ .truncate(!append)
+ .custom_flags(libc::O_NOFOLLOW)
+ .mode(0o600)
+ .open(file)
- .map_err(|e| e.to_string())?
++ .map_err(|e| format!("write: {e}"))?
+ };
- let mut received = 0u64;
- let mut buf = vec![0u8; 64 * 1024];
++
++ let mut done = if append { have } else { 0 };
++ progress(done, total);
++ let mut buf = vec![0u8; 256 * 1024];
++ let mut reported = Instant::now();
+ loop {
- let n = stdout.read(&mut buf).map_err(|e| e.to_string())?;
++ let n = stdout.read(&mut buf).map_err(|e| format!("read: {e}"))?;
+ if n == 0 {
+ break;
+ }
- received += n as u64;
- if received > limit {
++ done += n as u64;
++ if done > limit {
+ let _ = child.kill();
++ let _ = child.wait();
+ let _ = fs::remove_file(file);
- return Err(format!("download exceeds {limit} bytes"));
++ return Err("too large".into());
++ }
++ out.write_all(&buf[..n]).map_err(|e| format!("write: {e}"))?;
++ if reported.elapsed() >= Duration::from_millis(200) {
++ reported = Instant::now();
++ progress(done, total);
+ }
- out.write_all(&buf[..n]).map_err(|e| e.to_string())?;
- progress(received, 0);
+ }
- out.flush().map_err(|e| e.to_string())?;
++ out.sync_all().map_err(|e| format!("write: {e}"))?;
+ let status = child.wait().map_err(|e| e.to_string())?;
++ progress(done, total);
++ if total > 0 && done < total {
++ return Err("the download ended early".into());
++ }
+ 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 download_to_file(_url: &str, _dest: &Path, _on_progress: impl FnMut(u64, u64)) -> Result<(), 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)
+}
+
+#[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());
++ assert_eq!(get("http://example.com/releases", 1024).unwrap_err(), "only https");
++ assert_eq!(get_retrying("http://example.com/releases", 1024).unwrap_err(), "only https");
++ assert_eq!(
++ download("http://example.com/setup", Path::new("out.bin"), 1024, |_, _| {}).unwrap_err(),
++ "only https"
++ );
++ }
++
++ #[test]
++ fn reads_the_full_size_from_a_content_range() {
++ assert_eq!(range_total("bytes 1048576-38473163/38473164"), Some(38_473_164));
++ assert_eq!(range_total("bytes 0-99/*"), None);
++ assert_eq!(range_total("garbage"), None);
++ }
++
++ #[test]
++ fn parses_redirected_http_status_lines() {
++ let raw =
++ "HTTP/2 302 \r\nlocation: https://objects.githubusercontent.com/x\r\n\r\nHTTP/2 404 \r\n\r\n";
++ assert_eq!(parse_last_http_status(raw), Some(404));
++ assert_eq!(parse_status_line("HTTP/1.1 206 Partial Content"), Some(206));
++ }
++
++ #[test]
++ fn retries_network_trouble_but_not_refusals() {
++ assert!(retryable("curl failed with status exit status: 28"));
++ assert!(retryable("HTTP 503"));
++ assert!(retryable("HTTP 429"));
++ assert!(!retryable("HTTP 404"));
++ assert!(!retryable("too large"));
++ assert!(!retryable("only https"));
+ }
+
+ #[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 --cc desktop/app/src/setup.rs
index d867df2,9928acd..4488994
--- a/desktop/app/src/setup.rs
+++ b/desktop/app/src/setup.rs
@@@ -62,56 -61,18 +62,69 @@@ 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 });
+ }
+ }
++ if let Some(local_data) = dirs::data_local_dir() {
++ let user_dir = local_data.join("nectarlink-app");
++ let exe = user_dir.join(APP_EXE);
++ if exe.is_file() {
++ let version = read_installed_version(&user_dir, &exe).unwrap_or_default();
++ return Some(Installed { dir: user_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(not(any(windows, target_os = "linux")))]
++pub fn installed() -> Option<Installed> {
++ 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
}
}
@@@ -181,10 -120,7 +194,10 @@@ impl Step
match self {
Step::Closing => "Closing NectarLink",
Step::Files => "Copying files",
- #[cfg(windows)]
++ #[cfg(not(target_os = "linux"))]
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",
@@@ -234,15 -170,14 +247,66 @@@ pub enum Outcome
}
/// Installs from `installer` with administrator rights, reporting each step.
++#[cfg(not(target_os = "linux"))]
pub fn install(installer: &Path, on_event: impl FnMut(Event)) -> Outcome {
let progress = progress_file("install");
let params = format!("/S /PROGRESS={}", progress.display());
run_tracked(installer, &params, &progress, Duration::from_secs(600), true, on_event)
}
++#[cfg(target_os = "linux")]
++pub fn install(installer: &Path, mut on_event: impl FnMut(Event)) -> Outcome {
++ let name = installer.file_name().and_then(|s| s.to_str()).unwrap_or_default();
++ if name.ends_with(".deb") {
++ on_event(Event::Step(Step::Closing));
++ on_event(Event::Step(Step::Files));
++ let path_str = installer.to_string_lossy();
++ match crate::win::elevated::run_elevated(
++ Path::new("sh"),
++ &["-e", "-c", "apt-get install -y -- \"$1\" || dpkg -i -- \"$1\"", "sh", &path_str],
++ ) {
++ Ok(0) => {
++ on_event(Event::Step(Step::Shortcuts));
++ on_event(Event::Done);
++ Outcome::Done
++ }
++ Ok(126 | 127) => Outcome::Declined,
++ Ok(code) => Outcome::Failed(tr!("Setup", "Setup stopped with code %1.", code)),
++ Err(e) => Outcome::Failed(tr!("Setup", "Couldn't start setup: %1", e)),
++ }
++ } else if name.ends_with(".tar.gz") {
++ on_event(Event::Step(Step::Closing));
++ on_event(Event::Step(Step::Files));
++ let path_str = installer.to_string_lossy();
++ match crate::win::elevated::run_elevated(
++ Path::new("sh"),
++ &[
++ "-e",
++ "-c",
++ "dir=$(mktemp -d) && trap 'rm -rf \"$dir\"' EXIT && tar -C \"$dir\" -xzf \"$1\" && set -- \"$dir\"/Nectarlink-*/install.sh && [ -x \"$1\" ] && \"$1\"",
++ "sh",
++ &path_str,
++ ],
++ ) {
++ Ok(0) => {
++ on_event(Event::Step(Step::Shortcuts));
++ on_event(Event::Done);
++ Outcome::Done
++ }
++ Ok(126 | 127) => Outcome::Declined,
++ Ok(code) => Outcome::Failed(tr!("Setup", "Setup stopped with code %1.", code)),
++ Err(e) => Outcome::Failed(tr!("Setup", "Couldn't start setup: %1", e)),
++ }
++ } else {
++ let progress = progress_file("install");
++ let params = format!("/S /PROGRESS={}", progress.display());
++ run_tracked(installer, &params, &progress, Duration::from_secs(600), true, on_event)
++ }
++}
++
/// Removes the copy in `installed` with administrator rights, then this
/// user's data.
- #[cfg(windows)]
++#[cfg(not(target_os = "linux"))]
pub fn remove(installed: &Path, mut on_event: impl FnMut(Event)) -> Outcome {
let uninstaller = installed.join("uninstall.exe");
if !uninstaller.is_file() {
@@@ -263,48 -198,6 +327,62 @@@
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));
++ if let Some(local_data) = dirs::data_local_dir() {
++ let user_app_dir = local_data.join("nectarlink-app");
++ if installed == user_app_dir {
++ let _ = std::fs::remove_dir_all(&user_app_dir);
++ if let Some(home) = dirs::home_dir() {
++ let _ = std::fs::remove_file(home.join(".local/bin/nectarlink-desktop"));
++ }
++ let _ = std::fs::remove_file(local_data.join("applications/nectarlink.desktop"));
++ let _ = std::fs::remove_file(local_data.join("metainfo/org.nectarlink.desktop.metainfo.xml"));
++ remove_user_data();
++ on_event(Event::Done);
++ return Outcome::Done;
++ }
++ }
+ 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() {
@@@ -323,11 -215,6 +401,11 @@@ fn user_data_dir() -> Option<PathBuf>
local.is_absolute().then(|| local.join("Nectarlink"))
}
- #[cfg(target_os = "linux")]
++#[cfg(not(windows))]
+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).
@@@ -428,29 -299,21 +506,38 @@@ pub fn open_app(dir: &Path) -> Result<(
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())
+}
+
++#[cfg(not(any(windows, 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("open").arg(&app).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.
@@@ -478,15 -340,7 +565,15 @@@ pub fn hand_over_removal(installed: &Pa
Ok(true)
}
- #[cfg(target_os = "linux")]
++#[cfg(not(windows))]
+pub fn hand_over_removal(_installed: &Path) -> Result<bool, String> {
- // On Linux, open executables can be unlinked while running, and `installed`
++ // On Unix, 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 };
@@@ -497,35 -351,20 +584,35 @@@
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")]
++#[cfg(not(windows))]
+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)? {
diff --cc desktop/app/src/updater.rs
index bab6f15,c894168..a2dba7a
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@@ -218,43 -224,15 +218,96 @@@ fn latest() -> Result<Option<Update>, S
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"]
+};
+
++#[cfg(target_os = "linux")]
++const TARBALL_SUFFIXES: &[&str] = if cfg!(target_arch = "aarch64") {
++ &["-linux-aarch64.tar.gz", "_arm64.deb", "-aarch64.AppImage"]
++} else {
++ &["-linux-x86_64.tar.gz", "_amd64.deb", "-x86_64.AppImage"]
++};
++
++#[cfg(target_os = "linux")]
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++enum LinuxInstallKind {
++ AppImage,
++ Deb,
++ Tarball,
++}
++
++#[cfg(target_os = "linux")]
++fn detect_linux_install_kind() -> LinuxInstallKind {
++ if std::env::var_os("APPIMAGE").is_some() {
++ return LinuxInstallKind::AppImage;
++ }
++ if let Ok(exe) = std::env::current_exe() {
++ let resolved = std::fs::canonicalize(&exe).unwrap_or(exe);
++ if resolved.starts_with("/opt/nectarlink")
++ || resolved.parent().and_then(|p| p.file_name()).is_some_and(|n| n == "nectarlink-app")
++ {
++ return LinuxInstallKind::Tarball;
++ }
++ }
++ if Path::new("/var/lib/dpkg/info/nectarlink.list").is_file()
++ || Path::new("/var/lib/dpkg/status").is_file()
++ {
++ return LinuxInstallKind::Deb;
++ }
++ LinuxInstallKind::Tarball
++}
++
/// 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())
++ newer_release_linux_kind(release, current, detect_linux_install_kind())
++}
++
++#[cfg(not(any(windows, target_os = "linux")))]
++fn newer_release(_release: Release, _current: &str) -> Option<Update> {
++ None
+}
+
+#[cfg(target_os = "linux")]
++#[cfg_attr(not(test), allow(dead_code))]
+fn newer_release_linux(release: Release, current: &str, is_appimage: bool) -> Option<Update> {
- let suffixes = if is_appimage { APPIMAGE_SUFFIXES } else { DEB_SUFFIXES };
++ let kind = if is_appimage { LinuxInstallKind::AppImage } else { LinuxInstallKind::Deb };
++ newer_release_linux_kind(release, current, kind)
++}
++
++#[cfg(target_os = "linux")]
++fn newer_release_linux_kind(release: Release, current: &str, kind: LinuxInstallKind) -> Option<Update> {
++ let suffixes = match kind {
++ LinuxInstallKind::AppImage => APPIMAGE_SUFFIXES,
++ LinuxInstallKind::Deb => DEB_SUFFIXES,
++ LinuxInstallKind::Tarball => TARBALL_SUFFIXES,
++ };
+ for &suffix in suffixes {
+ if let Some(u) = newer_release_for(release.clone(), current, suffix) {
+ return Some(u);
+ }
+ }
+ None
+}
+
++#[cfg_attr(not(any(windows, target_os = "linux", test)), allow(dead_code))]
fn newer_release_for(release: Release, current: &str, suffix: &str) -> Option<Update> {
if release.draft || release.prerelease {
return None;
@@@ -341,20 -317,21 +394,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")]
++#[cfg(not(windows))]
+fn task_registered() -> bool {
+ false
}
/// Installs the update found: downloads it (reporting `progress(done,
@@@ -429,22 -413,6 +482,22 @@@ fn staging_dir() -> PathBuf
.join("updates")
}
- #[cfg(target_os = "linux")]
++#[cfg(not(windows))]
+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")]
++#[cfg(not(windows))]
+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)?;
@@@ -472,24 -440,7 +525,24 @@@ fn sha256_file(path: &Path) -> std::io:
pub fn stage(update: &Update, progress: impl FnMut(u64, u64)) -> Result<PathBuf, StageError> {
let expected = expected_hash(update)?;
let dir = staging_dir();
- #[cfg(unix)]
- std::fs::create_dir_all(&dir).map_err(|e| StageError::Disk(e.to_string()))?;
++ #[cfg(target_os = "linux")]
+ {
+ 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))]
++ #[cfg(not(target_os = "linux"))]
+ {
+ 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.
@@@ -540,51 -501,40 +593,51 @@@ fn install_with_task(shown: bool) -> Re
/// 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}"))
+ // 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());
}
- #[cfg(not(windows))]
- {
- let _ = (exe, version, shown);
- Err("relauncher is not supported on non-Windows".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")]
++#[cfg(not(windows))]
+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}"))
}
- #[cfg_attr(target_os = "linux", allow(dead_code))]
-#[allow(dead_code)]
++#[cfg_attr(not(windows), allow(dead_code))]
fn relauncher_script(exe: &str, version: &str, arguments: &str) -> String {
let start = if arguments.is_empty() {
format!("Start-Process -FilePath '{exe}'")
@@@ -655,11 -605,13 +708,43 @@@ pub fn run_service() -> ExitCode
}
};
// Not waited for: the installer replaces this program, which must not be running.
- let mut cmd = std::process::Command::new(&path);
- cmd.arg("/S");
#[cfg(windows)]
- cmd.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
- match cmd.spawn() {
- let mut cmd = std::process::Command::new(&path);
- #[cfg(windows)]
- cmd.arg("/S").creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
++ let spawned = {
++ let mut cmd = std::process::Command::new(&path);
++ cmd.arg("/S");
++ cmd.creation_flags(CREATE_NO_WINDOW | DETACHED_PROCESS);
++ cmd.spawn()
++ };
+ #[cfg(not(windows))]
- let mut cmd = std::process::Command::new(&path);
- match cmd.spawn() {
++ let spawned = {
++ let name = path.file_name().and_then(|s| s.to_str()).unwrap_or_default();
++ if name.ends_with(".deb") {
++ std::process::Command::new("sh")
++ .args(["-c", "apt-get install -y -- \"$1\" || dpkg -i -- \"$1\"", "sh"])
++ .arg(&path)
++ .stdin(std::process::Stdio::null())
++ .stdout(std::process::Stdio::null())
++ .stderr(std::process::Stdio::null())
++ .spawn()
++ } else if name.ends_with(".tar.gz") {
++ std::process::Command::new("sh")
++ .args([
++ "-e",
++ "-c",
++ "tar -C \"$2\" -xzf \"$1\" && set -- \"$2\"/Nectarlink-*/install.sh && [ -x \"$1\" ] && \"$1\"",
++ "sh",
++ ])
++ .arg(&path)
++ .arg(&dir)
++ .stdin(std::process::Stdio::null())
++ .stdout(std::process::Stdio::null())
++ .stderr(std::process::Stdio::null())
++ .spawn()
++ } else {
++ std::process::Command::new(&path).arg("/S").spawn()
++ }
++ };
++ match spawned {
Ok(_) => {
log(&format!("installing {}", update.version));
ExitCode::SUCCESS
@@@ -708,20 -659,6 +793,20 @@@ fn service_dir() -> std::io::Result<Pat
Ok(dir)
}
- #[cfg(target_os = "linux")]
++#[cfg(not(windows))]
+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.
@@@ -773,76 -710,6 +858,142 @@@ fn install_with_prompt(update: &Update
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";
++apt-get install -y -- \"$dst\" || dpkg -i -- \"$dst\"\n";
++
++#[cfg(target_os = "linux")]
++const PRIVILEGED_TAR_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.tar.gz\"\n\
++install -m 0600 -o 0 -g 0 \"$1\" \"$dst\"\n\
++printf '%s %s\\n' \"$2\" \"$dst\" | sha256sum -c --status -\n\
++tar -C \"$dir\" -xzf \"$dst\"\n\
++set -- \"$dir\"/Nectarlink-*/install.sh\n\
++[ -x \"$1\" ] && \"$1\"\n";
+
+#[cfg(target_os = "linux")]
+fn install_with_prompt(update: &Update, staged: &Path) -> Result<(), String> {
- use std::os::unix::fs::PermissionsExt;
++ use std::os::unix::fs::{DirBuilderExt, 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 staged_name.ends_with(".tar.gz") {
++ let exe = std::env::current_exe().ok();
++ let resolved_exe = exe.as_ref().map(|p| std::fs::canonicalize(p).unwrap_or_else(|_| p.clone()));
++ let needs_root =
++ resolved_exe.as_ref().is_some_and(|p| p.starts_with("/opt/") || p.starts_with("/usr/"));
++
++ if needs_root {
++ let staged_str = staged.to_string_lossy();
++ let code = crate::win::elevated::run_elevated(
++ Path::new("sh"),
++ &["-e", "-c", PRIVILEGED_TAR_INSTALL_SCRIPT, "sh", &staged_str, &expected],
++ )
++ .map_err(failed)?;
++ if code != 0 {
++ return Err(failed(format!("privileged .tar.gz install exited with status {code}")));
++ }
++ } else {
++ let extract_dir = staging_dir().join(format!("extract-{}", std::process::id()));
++ let _ = std::fs::remove_dir_all(&extract_dir);
++ std::fs::DirBuilder::new()
++ .recursive(true)
++ .mode(0o700)
++ .create(&extract_dir)
++ .map_err(|e| failed(e.to_string()))?;
++ let status = std::process::Command::new("sh")
++ .args([
++ "-e",
++ "-c",
++ "tar -C \"$2\" -xzf \"$1\" && set -- \"$2\"/Nectarlink-*/install.sh && [ -x \"$1\" ] && \"$1\"",
++ "sh",
++ ])
++ .arg(staged)
++ .arg(&extract_dir)
++ .stdin(std::process::Stdio::null())
++ .status()
++ .map_err(|e| failed(e.to_string()))?;
++ let _ = std::fs::remove_dir_all(&extract_dir);
++ if !status.success() {
++ return Err(failed(format!("user .tar.gz install exited with status {status}")));
++ }
++ }
++ if let Some(exe) = 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(())
+}
+
++#[cfg(not(any(windows, target_os = "linux")))]
++fn install_with_prompt(_update: &Update, _staged: &Path) -> Result<(), String> {
++ Err("Updates are not supported on this platform.".into())
++}
++
/// The flag the relauncher passes to the new version.
pub const UPDATED_ARG: &str = "--updated";