Skip to content

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

Desktop: updates itself from GitHub releases

Bee636da6fe4673
diff --git a/Cargo.lock b/Cargo.lock
index 07ca185..c892b12 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2353,6 +2353,7 @@ dependencies = [
"qrcode",
"serde",
"serde_json",
+ "sha2",
"tempfile",
"tokio",
"tracing",
diff --git a/README.md b/README.md
index 947d1f8..267bbc0 100644
--- a/README.md
+++ b/README.md
@@ -70,12 +70,15 @@ place and tested; the user-facing features of Phase 1 come next.
power level.
- **Find my device** in both directions. The phone rings on the alarm stream,
even in silent mode.
+- **Lock or sleep the PC** from the phone, and **links** both ways: share a
+ link from any phone app to open it on the PC, or send a copied link from the
+ PC's tray to the phone.
- **Notifications** from the phone on the PC, as Windows notifications and in
a feed in the app, with the app's icon. Reply inline, run their actions
(such as "Mark as read") or dismiss them from the PC; what's cleared on one
- side is cleared on the other. Per app, choose whether they pop up, show
- only in the app, or stay hidden, and find the last day's notifications in
- History.
+ side is cleared on the other. Photos in messages and big pictures come
+ along. Per app, choose whether they pop up, show only in the app, or stay
+ hidden, and find the last day's notifications in History.
- **Clipboard**: text and images you copy on the PC are ready to paste on the
phone. From the phone, send them with the Quick Settings tile, the share
sheet or a button in the app (Android lets only the app in front read the
@@ -99,13 +102,17 @@ place and tested; the user-facing features of Phase 1 come next.
uses about 10 MB of memory (as shown in Task Manager).
- **Android app**: pairing, home and settings, Material You colors, a background
connection service, and an identity key protected by the Android Keystore.
+- **Connection Doctor** on the PC: finds what keeps the phone from
+ connecting (firewall, a public network, a VPN) and fixes what it can.
- **Windows installer**: installs for everyone on the PC, allows the app
through Windows Firewall, starts it with Windows, and uninstalls cleanly.
- Each `v*` tag drafts a GitHub release with the installer.
+ Each `v*` tag drafts a GitHub release with the installer. Installed copies
+ update themselves from GitHub releases (checked with SHA-256).
- **Command-line client** for development and testing (`nectarlink`).
-**Next**: Phase 1 is complete. Mirroring, messages, calls and the other
-features in the plan follow in later phases.
+**Next**: the Android app updating itself (it needs signed release builds
+first). Then Phase 2: mirroring, messages, calls and the other features in
+the plan.
## Screenshots
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index 68b487a..b64d856 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -26,6 +26,7 @@ nectarlink-core.workspace = true
qrcode.workspace = true
serde.workspace = true
serde_json.workspace = true
+sha2.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
@@ -60,6 +61,7 @@ windows = { workspace = true, features = [
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_WindowsFirewall",
"Win32_Networking_NetworkListManager",
+ "Win32_Networking_WinHttp",
"Win32_System_Ole",
"Win32_System_Variant",
"Win32_Networking_WinSock",
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index 2b0aaa6..aaa8cc1 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -374,6 +374,42 @@ Item {
font.pixelSize: 12
Accessible.name: qsTr("Device ID")
}
+ // Updates (installed copies only).
+ Row {
+ visible: AppController.canUpdate
+ spacing: 10
+ Button {
+ size: "sm"
+ variant: AppController.updateVersion.length > 0 ? "fill" : "tonal"
+ iconPath: Icons.refresh
+ enabled: !AppController.updateBusy
+ text: AppController.updateVersion.length > 0
+ ? qsTr("Update to %1").arg(AppController.updateVersion)
+ : qsTr("Check for updates")
+ onClicked: AppController.updateVersion.length > 0
+ ? AppController.installUpdate() : AppController.checkForUpdates()
+ }
+ Spinner { anchors.verticalCenter: parent.verticalCenter; visible: AppController.updateBusy }
+ }
+ Item {
+ width: parent.width
+ height: autoUpdate.implicitHeight
+ visible: AppController.canUpdate
+ Txt {
+ anchors.left: parent.left
+ anchors.right: autoUpdate.left
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Check for updates automatically")
+ role: "body"
+ }
+ Toggle {
+ id: autoUpdate
+ anchors.right: parent.right
+ label: qsTr("Check for updates automatically")
+ checked: Preferences.autoUpdate
+ onToggled: (on) => Preferences.autoUpdate = on
+ }
+ }
Button {
variant: "outline"
size: "sm"
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index b34fda1..803dab7 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -65,6 +65,12 @@ pub mod qobject {
#[qproperty(QString, doctor_checks)]
/// Checking, or fixing.
#[qproperty(bool, doctor_busy)]
+ /// This copy updates itself (it's installed).
+ #[qproperty(bool, can_update)]
+ /// A newer version that's available ("" when none).
+ #[qproperty(QString, update_version)]
+ /// Checking for or installing an update.
+ #[qproperty(bool, update_busy)]
type AppController = super::AppControllerRust;
/// Asks a paired device to ring (or stop).
@@ -109,6 +115,13 @@ pub mod qobject {
#[qinvokable]
fn doctor_fix(self: Pin<&mut AppController>, fix: &QString);
+ /// Checks for an update now and says what it found.
+ #[qinvokable]
+ fn check_for_updates(self: Pin<&mut AppController>);
+ /// Downloads and installs the update found.
+ #[qinvokable]
+ fn install_update(self: Pin<&mut AppController>);
+
/// The folder with the app's logs, as a file URL.
#[qinvokable]
fn logs_url(self: &AppController) -> QString;
@@ -148,6 +161,9 @@ pub struct AppControllerRust {
version: QString,
doctor_checks: QString,
doctor_busy: bool,
+ can_update: bool,
+ update_version: QString,
+ update_busy: bool,
tray: Option<tray::Tray>,
}
@@ -155,6 +171,31 @@ pub struct AppControllerRust {
/// reach it.
static CONTROLLER: OnceLock<Mutex<Option<CxxQtThread<qobject::AppController>>>> = OnceLock::new();
+/// Downloads and starts the update (from the app or its notification).
+pub fn install_update_in_background() {
+ let Some(qt) = controller() else { return };
+ let started = qt.queue(|mut object| {
+ if object.update_busy {
+ return;
+ }
+ object.as_mut().set_update_busy(true);
+ object.as_mut().toast(QString::from("Downloading the update…"));
+ let qt = object.qt_thread();
+ std::thread::spawn(move || {
+ let result = crate::updater::install();
+ let _ = qt.queue(move |mut object| {
+ object.as_mut().set_update_busy(false);
+ if let Err(message) = result {
+ object.toast(QString::from(&message));
+ }
+ });
+ });
+ });
+ if started.is_err() {
+ tracing::warn!("can't start the update");
+ }
+}
+
/// Runs a Doctor fix (if any), then the checks, off the UI thread; the
/// findings land in `doctor_checks`.
fn diagnose_in_background(mut object: Pin<&mut qobject::AppController>, fix: Option<String>) {
@@ -227,6 +268,7 @@ pub(crate) fn describe(error: &Error) -> String {
impl cxx_qt::Initialize for qobject::AppController {
fn initialize(mut self: Pin<&mut Self>) {
self.as_mut().set_version(QString::from(env!("CARGO_PKG_VERSION")));
+ self.as_mut().set_can_update(crate::updater::can_update());
self.as_mut().refresh_appearance();
let qt = self.qt_thread();
*CONTROLLER.get_or_init(Mutex::default).lock().unwrap_or_else(|e| e.into_inner()) = Some(qt.clone());
@@ -235,6 +277,10 @@ impl cxx_qt::Initialize for qobject::AppController {
Changes::STATUS | Changes::DEVICES | Changes::CAPABILITIES | Changes::RINGING,
Self::refresh,
);
+ super::subscribe(qt.clone(), Changes::UPDATE, |object| {
+ let version = crate::updater::available().map(|u| u.version).unwrap_or_default();
+ object.set_update_version(QString::from(&version));
+ });
let labels = tray::MenuLabels {
open: "Open Nectarlink".into(),
@@ -424,6 +470,27 @@ impl qobject::AppController {
self.as_mut().set_toggles_revision(revision);
}
+ pub fn check_for_updates(mut self: Pin<&mut Self>) {
+ if self.update_busy {
+ return;
+ }
+ self.as_mut().set_update_busy(true);
+ let qt = self.qt_thread();
+ std::thread::spawn(move || {
+ let message = crate::updater::check_now(true);
+ let _ = qt.queue(move |mut object| {
+ object.as_mut().set_update_busy(false);
+ if let Some(message) = message {
+ object.toast(QString::from(&message));
+ }
+ });
+ });
+ }
+
+ pub fn install_update(self: Pin<&mut Self>) {
+ install_update_in_background();
+ }
+
pub fn run_doctor(mut self: Pin<&mut Self>) {
self.as_mut().doctor_requested();
diagnose_in_background(self, None);
diff --git a/desktop/app/src/bridge/prefs.rs b/desktop/app/src/bridge/prefs.rs
index 8ad382f..163f5b4 100644
--- a/desktop/app/src/bridge/prefs.rs
+++ b/desktop/app/src/bridge/prefs.rs
@@ -45,6 +45,8 @@ pub mod qobject {
#[qproperty(bool, send_to_menu)]
/// Start when the user signs in.
#[qproperty(bool, start_with_windows)]
+ /// Check for updates on their own.
+ #[qproperty(bool, auto_update)]
type Preferences = super::PreferencesRust;
}
@@ -61,6 +63,7 @@ pub struct PreferencesRust {
auto_clipboard: bool,
send_to_menu: bool,
start_with_windows: bool,
+ auto_update: bool,
/// What the user chose (`start_with_windows` shows the default until then).
start_choice: Option<bool>,
}
@@ -83,6 +86,7 @@ impl cxx_qt::Initialize for qobject::Preferences {
self.as_mut().set_auto_clipboard(settings.auto_clipboard);
crate::clipboard::set_auto_send(settings.auto_clipboard);
self.as_mut().set_send_to_menu(settings.send_to_menu);
+ self.as_mut().set_auto_update(settings.auto_update);
self.as_mut().set_start_with_windows(crate::startup::effective(settings.start_with_windows));
self.as_mut().rust_mut().start_choice = settings.start_with_windows;
@@ -105,6 +109,12 @@ impl cxx_qt::Initialize for qobject::Preferences {
p.save();
})
.release();
+ self.as_mut()
+ .on_auto_update_changed(|p| {
+ crate::updater::set_auto(p.auto_update);
+ p.save();
+ })
+ .release();
self.as_mut()
.on_start_with_windows_changed(|mut p| {
let on = p.start_with_windows;
@@ -131,6 +141,7 @@ impl qobject::Preferences {
close_to_tray: p.close_to_tray,
auto_clipboard: p.auto_clipboard,
send_to_menu: p.send_to_menu,
+ auto_update: p.auto_update,
start_with_windows: p.start_choice,
};
save_in_background(settings);
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index db7b885..5a9a459 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -27,6 +27,7 @@ mod settings;
mod startup;
mod state;
mod transfers;
+mod updater;
mod win;
use std::{
@@ -237,6 +238,8 @@ fn main() -> ExitCode {
if options.data_dir.is_none() {
send_to::start();
startup::start(settings.start_with_windows);
+ updater::set_auto(settings.auto_update);
+ updater::start();
}
// Requests left while no instance was running, then this launch's own.
for waiting in launch::drain(&data_dir) {
diff --git a/desktop/app/src/notifications.rs b/desktop/app/src/notifications.rs
index e63e76f..a4b64a7 100644
--- a/desktop/app/src/notifications.rs
+++ b/desktop/app/src/notifications.rs
@@ -205,6 +205,11 @@ pub fn on_toast(event: ToastEvent) {
return;
}
ToastEvent::Dismissed { device, .. } if device == crate::send_to::TOAST_GROUP => return,
+ // "Update" on the update notice.
+ ToastEvent::Action { device, .. } if device == crate::updater::TOAST_GROUP => {
+ return crate::bridge::app::install_update_in_background();
+ }
+ ToastEvent::Dismissed { device, .. } if device == crate::updater::TOAST_GROUP => return,
_ => {}
}
match event {
diff --git a/desktop/app/src/settings.rs b/desktop/app/src/settings.rs
index ad88309..194ca79 100644
--- a/desktop/app/src/settings.rs
+++ b/desktop/app/src/settings.rs
@@ -45,6 +45,8 @@ pub struct Settings {
pub auto_clipboard: bool,
/// Paired phones in Explorer's "Send to" menu.
pub send_to_menu: bool,
+ /// Check for updates on its own (installed copies).
+ pub auto_update: bool,
/// Start when the user signs in. Unset until the user chooses: then an
/// installed copy starts with Windows and a build run from its folder
/// doesn't.
@@ -62,6 +64,7 @@ impl Default for Settings {
close_to_tray: true,
auto_clipboard: true,
send_to_menu: true,
+ auto_update: true,
start_with_windows: None,
}
}
@@ -124,6 +127,7 @@ mod tests {
close_to_tray: false,
auto_clipboard: false,
send_to_menu: false,
+ auto_update: false,
start_with_windows: Some(true),
};
settings.save(dir.path()).unwrap();
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 74ad92e..b01e0e7 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -34,6 +34,8 @@ impl Changes {
pub const HISTORY: Changes = Changes(1 << 9);
/// Apps that sent notifications, and the user's rules for them.
pub const APPS: Changes = Changes(1 << 10);
+ /// An update was found (see crate::updater).
+ pub const UPDATE: Changes = Changes(1 << 11);
pub fn is_empty(self) -> bool {
self.0 == 0
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
new file mode 100644
index 0000000..1e938e1
--- /dev/null
+++ b/desktop/app/src/updater.rs
@@ -0,0 +1,287 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Updates for an installed copy: the latest GitHub release is checked at
+//! startup and once a day (unless turned off). When it's newer, the user is
+//! told and can update: the installer is downloaded, checked against the
+//! release's SHA-256 sums, and run silently; it closes this copy, installs
+//! and opens the new one.
+
+use std::{
+ path::PathBuf,
+ sync::{
+ Mutex, MutexGuard,
+ atomic::{AtomicBool, Ordering},
+ },
+ time::Duration,
+};
+
+use serde::Deserialize;
+use sha2::{Digest, Sha256};
+
+use crate::{
+ core_host,
+ state::Changes,
+ win::{autostart, http, toast},
+};
+
+const LATEST: &str = "https://api.github.com/repos/thtbee/nectarlink/releases/latest";
+const FIRST_CHECK: Duration = Duration::from_secs(30);
+const EVERY: Duration = Duration::from_secs(24 * 3600);
+const MAX_INSTALLER: usize = 400 * 1024 * 1024;
+/// The toast "device" for update notices.
+pub const TOAST_GROUP: &str = "update";
+pub const ACTION_UPDATE: &str = "update";
+
+/// A newer release.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Update {
+ pub version: String,
+ pub notes_url: String,
+ installer_url: String,
+ installer_name: String,
+ sums_url: String,
+}
+
+static AUTO: AtomicBool = AtomicBool::new(true);
+static CHECKING: AtomicBool = AtomicBool::new(false);
+static FOUND: Mutex<Option<Update>> = Mutex::new(None);
+
+fn found() -> MutexGuard<'static, Option<Update>> {
+ FOUND.lock().unwrap_or_else(|e| e.into_inner())
+}
+
+/// The update found, if any.
+pub fn available() -> Option<Update> {
+ found().clone()
+}
+
+pub fn set_auto(on: bool) {
+ AUTO.store(on, Ordering::Relaxed);
+}
+
+/// Whether this copy updates itself (an installed one, not a build run
+/// from its folder).
+pub fn can_update() -> bool {
+ std::env::current_exe().is_ok_and(|exe| autostart::is_installed(&exe))
+}
+
+/// Checks soon after startup, then daily, while automatic checks are on.
+pub fn start() {
+ if !can_update() {
+ return;
+ }
+ let spawned = std::thread::Builder::new().name("updates".into()).spawn(|| {
+ std::thread::sleep(FIRST_CHECK);
+ loop {
+ if AUTO.load(Ordering::Relaxed) {
+ check_now(false);
+ }
+ std::thread::sleep(EVERY);
+ }
+ });
+ if let Err(e) = spawned {
+ tracing::warn!(error = %e, "won't check for updates");
+ }
+}
+
+/// Checks now (blocking). `told`: the user asked, so say "up to date" too.
+/// Returns what to tell the user.
+pub fn check_now(told: bool) -> Option<String> {
+ if CHECKING.swap(true, Ordering::AcqRel) {
+ return None;
+ }
+ let result = latest();
+ CHECKING.store(false, Ordering::Release);
+ match result {
+ Ok(Some(update)) => {
+ let new = found().as_ref() != Some(&update);
+ *found() = Some(update.clone());
+ core_host::host().hub.update(|_| Changes::UPDATE);
+ if new {
+ announce(&update);
+ }
+ Some(format!("Nectarlink {} is available.", update.version))
+ }
+ Ok(None) => told.then(|| "Nectarlink is up to date.".to_owned()),
+ Err(e) => {
+ tracing::info!(error = %e, "couldn't check for updates");
+ told.then(|| "Couldn't check for updates. Check your internet connection.".to_owned())
+ }
+ }
+}
+
+fn announce(update: &Update) {
+ toast::show(toast::Toast {
+ device: TOAST_GROUP.into(),
+ key: update.version.clone(),
+ title: format!("Nectarlink {} is available", update.version),
+ body: "Update now, or later from Settings.".into(),
+ attribution: "Nectarlink".into(),
+ icon: None,
+ image: None,
+ actions: vec![(ACTION_UPDATE.into(), "Update".into())],
+ reply: None,
+ silent: true,
+ progress: None,
+ });
+}
+
+#[derive(Deserialize)]
+struct Release {
+ tag_name: String,
+ html_url: String,
+ #[serde(default)]
+ draft: bool,
+ #[serde(default)]
+ prerelease: bool,
+ assets: Vec<Asset>,
+}
+
+#[derive(Deserialize)]
+struct Asset {
+ name: String,
+ browser_download_url: String,
+}
+
+fn latest() -> Result<Option<Update>, String> {
+ let body = http::get(LATEST, 1024 * 1024)?;
+ let release: Release = serde_json::from_slice(&body).map_err(|e| e.to_string())?;
+ Ok(newer_release(release, env!("CARGO_PKG_VERSION")))
+}
+
+/// The release as an update, if it's a newer published one with an x64
+/// installer and its sums.
+fn newer_release(release: Release, current: &str) -> Option<Update> {
+ if release.draft || release.prerelease {
+ return None;
+ }
+ let version = release.tag_name.trim_start_matches('v').to_owned();
+ if !is_newer(&version, current) {
+ return None;
+ }
+ let installer = release.assets.iter().find(|a| a.name.ends_with("-x64-setup.exe"))?;
+ let sums = release.assets.iter().find(|a| a.name == "SHA256SUMS.txt")?;
+ Some(Update {
+ version,
+ notes_url: release.html_url,
+ installer_url: installer.browser_download_url.clone(),
+ installer_name: installer.name.clone(),
+ sums_url: sums.browser_download_url.clone(),
+ })
+}
+
+/// A version's numbers, and its pre-release part.
+type Version<'a> = ((u64, u64, u64), Option<&'a str>);
+
+/// `1.2.3` style versions, with an optional `-pre` part (a release is
+/// newer than its pre-releases).
+fn is_newer(candidate: &str, current: &str) -> bool {
+ fn parse(v: &str) -> Option<Version<'_>> {
+ let (numbers, pre) = match v.split_once('-') {
+ Some((n, p)) => (n, Some(p)),
+ None => (v, None),
+ };
+ let mut parts = numbers.split('.').map(str::parse::<u64>);
+ let version = (parts.next()?.ok()?, parts.next()?.ok()?, parts.next().unwrap_or(Ok(0)).ok()?);
+ Some((version, pre))
+ }
+ let (Some((a, a_pre)), Some((b, b_pre))) = (parse(candidate), parse(current)) else { return false };
+ match a.cmp(&b) {
+ std::cmp::Ordering::Greater => true,
+ std::cmp::Ordering::Less => false,
+ std::cmp::Ordering::Equal => match (a_pre, b_pre) {
+ (None, Some(_)) => true,
+ (Some(x), Some(y)) => x > y,
+ _ => false,
+ },
+ }
+}
+
+/// The SHA-256 a sums file lists for `name` (`<hex> <name>` lines).
+fn listed_hash(sums: &str, name: &str) -> Option<String> {
+ sums.lines().find_map(|line| {
+ let (hash, file) = line.split_once(char::is_whitespace)?;
+ (file.trim().trim_start_matches('*') == name && hash.len() == 64).then(|| hash.to_ascii_lowercase())
+ })
+}
+
+/// Downloads, checks and runs the installer (blocking). Returns what went
+/// wrong, in words for the user.
+pub fn install() -> Result<(), String> {
+ let update = available().ok_or("There's no update to install.")?;
+ let failed = |e: String| {
+ tracing::warn!(error = e, "update failed");
+ "The update couldn't be downloaded. Try again later.".to_owned()
+ };
+ let sums = http::get(&update.sums_url, 64 * 1024).map_err(failed)?;
+ let expected = listed_hash(&String::from_utf8_lossy(&sums), &update.installer_name)
+ .ok_or("The update's checksum is missing, so it wasn't installed.")?;
+ let installer = http::get(&update.installer_url, MAX_INSTALLER).map_err(failed)?;
+ let actual = Sha256::digest(&installer).iter().map(|b| format!("{b:02x}")).collect::<String>();
+ if actual != expected {
+ tracing::warn!("update checksum mismatch");
+ return Err("The download was damaged, so it wasn't installed. Try again later.".into());
+ }
+ let dir = std::env::temp_dir().join("Nectarlink update");
+ let path: PathBuf = dir.join(&update.installer_name);
+ std::fs::create_dir_all(&dir)
+ .and_then(|()| std::fs::write(&path, &installer))
+ .map_err(|e| failed(e.to_string()))?;
+ // Silent, then opens the new version (/RUN); Windows asks for
+ // permission first. The installer closes this copy itself.
+ crate::win::shell::run(&path, "/S /RUN").map_err(failed)?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn versions_compare() {
+ assert!(is_newer("0.1.0", "0.0.1"));
+ assert!(is_newer("1.0.0", "0.9.9"));
+ assert!(is_newer("0.2.0", "0.2.0-beta.1"));
+ assert!(is_newer("0.2.0-beta.2", "0.2.0-beta.1"));
+ assert!(!is_newer("0.0.1", "0.0.1"));
+ assert!(!is_newer("0.0.1", "0.1.0"));
+ assert!(!is_newer("garbage", "0.1.0"));
+ }
+
+ fn release(tag: &str) -> Release {
+ Release {
+ tag_name: tag.into(),
+ html_url: "https://github.com/thtbee/nectarlink/releases/tag/v9".into(),
+ draft: false,
+ prerelease: false,
+ assets: vec![
+ Asset {
+ name: "Nectarlink-9.0.0-x64-setup.exe".into(),
+ browser_download_url: "https://x/setup".into(),
+ },
+ Asset { name: "SHA256SUMS.txt".into(), browser_download_url: "https://x/sums".into() },
+ ],
+ }
+ }
+
+ #[test]
+ fn releases_become_updates_when_newer_and_complete() {
+ let update = newer_release(release("v9.0.0"), "0.0.1").unwrap();
+ assert_eq!((update.version.as_str(), update.installer_url.as_str()), ("9.0.0", "https://x/setup"));
+ assert!(newer_release(release("v0.0.1"), "0.0.1").is_none());
+ let mut draft = release("v9.0.0");
+ draft.prerelease = true;
+ assert!(newer_release(draft, "0.0.1").is_none());
+ let mut no_sums = release("v9.0.0");
+ no_sums.assets.pop();
+ assert!(newer_release(no_sums, "0.0.1").is_none());
+ }
+
+ #[test]
+ fn finds_the_installer_hash() {
+ let hash = "a".repeat(64);
+ let sums = format!("{hash} Nectarlink-9.0.0-x64-setup.exe\n{} other.txt\n", "b".repeat(64));
+ assert_eq!(listed_hash(&sums, "Nectarlink-9.0.0-x64-setup.exe"), Some(hash));
+ assert_eq!(listed_hash(&sums, "missing.exe"), None);
+ assert_eq!(listed_hash(&format!("{} *x.exe", "C".repeat(64)), "x.exe"), Some("c".repeat(64)));
+ }
+}
diff --git a/desktop/app/src/win/http.rs b/desktop/app/src/win/http.rs
new file mode 100644
index 0000000..e482951
--- /dev/null
+++ b/desktop/app/src/win/http.rs
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! HTTPS GET with Windows' own HTTP stack (WinHTTP): the system's TLS,
+//! proxy settings and certificates, and no extra dependencies. Used to
+//! check for updates and download them.
+
+use windows::{
+ Win32::Networking::WinHttp::{
+ WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_FLAG_SECURE, WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_QUERY_STATUS_CODE, WinHttpCloseHandle, WinHttpConnect, WinHttpOpen, WinHttpOpenRequest,
+ WinHttpQueryHeaders, WinHttpReadData, WinHttpReceiveResponse, WinHttpSendRequest, WinHttpSetTimeouts,
+ },
+ core::{HSTRING, PCWSTR, w},
+};
+
+/// A handle closed when dropped.
+struct Handle(*mut core::ffi::c_void);
+
+impl Drop for Handle {
+ fn drop(&mut self) {
+ if !self.0.is_null() {
+ // SAFETY: a handle WinHTTP gave us, closed once.
+ unsafe {
+ let _ = WinHttpCloseHandle(self.0);
+ }
+ }
+ }
+}
+
+fn last_error(what: &str) -> String {
+ format!("{what}: {}", windows::core::Error::from_thread())
+}
+
+/// Fetches an `https://` URL (following redirects), up to `limit` bytes.
+pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ let rest = url.strip_prefix("https://").ok_or("only https")?;
+ let (host, path) = rest.split_once('/').map_or((rest, "/".to_owned()), |(h, p)| (h, format!("/{p}")));
+ let agent = HSTRING::from(format!("Nectarlink/{} (Windows)", env!("CARGO_PKG_VERSION")));
+ // SAFETY: WinHTTP calls with valid strings; every handle is closed by
+ // `Handle`, children before parents (declaration order is reversed on
+ // drop).
+ unsafe {
+ let session = Handle(WinHttpOpen(
+ &agent,
+ WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
+ PCWSTR::null(),
+ PCWSTR::null(),
+ 0,
+ ));
+ if session.0.is_null() {
+ return Err(last_error("WinHttpOpen"));
+ }
+ // Resolve, connect, send, receive (ms).
+ let _ = WinHttpSetTimeouts(session.0, 10_000, 10_000, 30_000, 60_000);
+ let connection = Handle(WinHttpConnect(session.0, &HSTRING::from(host), 443, 0));
+ if connection.0.is_null() {
+ return Err(last_error("WinHttpConnect"));
+ }
+ let request = Handle(WinHttpOpenRequest(
+ connection.0,
+ w!("GET"),
+ &HSTRING::from(path),
+ PCWSTR::null(),
+ PCWSTR::null(),
+ std::ptr::null(),
+ WINHTTP_FLAG_SECURE,
+ ));
+ if request.0.is_null() {
+ return Err(last_error("WinHttpOpenRequest"));
+ }
+ // GitHub's API wants this; it's harmless elsewhere.
+ let headers: Vec<u16> =
+ "Accept: application/vnd.github+json, application/octet-stream\r\n".encode_utf16().collect();
+ WinHttpSendRequest(request.0, Some(&headers), None, 0, 0, 0).map_err(|e| format!("send: {e}"))?;
+ WinHttpReceiveResponse(request.0, std::ptr::null_mut()).map_err(|e| format!("receive: {e}"))?;
+ let mut status: u32 = 0;
+ let mut size = std::mem::size_of::<u32>() as u32;
+ WinHttpQueryHeaders(
+ request.0,
+ WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
+ PCWSTR::null(),
+ Some((&raw mut status).cast()),
+ &mut size,
+ std::ptr::null_mut(),
+ )
+ .map_err(|e| format!("status: {e}"))?;
+ if status != 200 {
+ return Err(format!("HTTP {status}"));
+ }
+ let mut body = Vec::new();
+ let mut chunk = vec![0u8; 64 * 1024];
+ loop {
+ let mut read = 0u32;
+ WinHttpReadData(request.0, chunk.as_mut_ptr().cast(), chunk.len() as u32, &mut read)
+ .map_err(|e| format!("read: {e}"))?;
+ if read == 0 {
+ break;
+ }
+ body.extend_from_slice(&chunk[..read as usize]);
+ if body.len() > limit {
+ return Err("too large".into());
+ }
+ }
+ Ok(body)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Needs the internet: `cargo test -- --ignored`.
+ #[test]
+ #[ignore]
+ fn fetches_over_https() {
+ let body = get("https://api.github.com/repos/rust-lang/rust", 1024 * 1024).unwrap();
+ assert!(String::from_utf8_lossy(&body).contains("\"full_name\""));
+ assert_eq!(get("https://api.github.com/does-not-exist-nectarlink", 1024).unwrap_err(), "HTTP 404");
+ assert_eq!(get("http://example.com", 1024).unwrap_err(), "only https");
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index 8e8b20f..bee244c 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -8,6 +8,7 @@
pub mod autostart;
pub mod clipboard;
pub mod doctor;
+pub mod http;
pub mod icon;
pub mod image;
pub mod media_sessions;
diff --git a/desktop/app/src/win/shell.rs b/desktop/app/src/win/shell.rs
index e8517d0..4d59961 100644
--- a/desktop/app/src/win/shell.rs
+++ b/desktop/app/src/win/shell.rs
@@ -18,6 +18,23 @@ pub fn open_url(url: &str) -> Result<(), String> {
if result.0 as isize > 32 { Ok(()) } else { Err(format!("ShellExecute returned {}", result.0 as isize)) }
}
+/// Starts a program with arguments (Windows asks for permission when it
+/// needs administrator rights).
+pub fn run(program: &std::path::Path, arguments: &str) -> Result<(), String> {
+ // SAFETY: as in `open_url`.
+ let result = unsafe {
+ ShellExecuteW(
+ None,
+ w!("open"),
+ &HSTRING::from(program.as_os_str()),
+ &HSTRING::from(arguments),
+ None,
+ SW_SHOWNORMAL,
+ )
+ };
+ if result.0 as isize > 32 { Ok(()) } else { Err(format!("ShellExecute returned {}", result.0 as isize)) }
+}
+
/// Locks the PC (shows the sign-in screen).
pub fn lock() -> Result<(), String> {
// SAFETY: no arguments.
diff --git a/desktop/installer/nectarlink.nsi b/desktop/installer/nectarlink.nsi
index 876ca5a..4a8ae0e 100644
--- a/desktop/installer/nectarlink.nsi
+++ b/desktop/installer/nectarlink.nsi
@@ -136,6 +136,14 @@ Section "Install"
WriteRegDWORD HKLM "${UNINSTALL_KEY}" "NoRepair" 1
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
WriteRegDWORD HKLM "${UNINSTALL_KEY}" "EstimatedSize" $0
+
+ ; /RUN (the app's own updater): open the new version when done.
+ ${GetParameters} $R0
+ ClearErrors
+ ${GetOptions} $R0 "/RUN" $R1
+ ${IfNot} ${Errors}
+ Call OpenApp
+ ${EndIf}
SectionEnd
Section "Uninstall"