Skip to content

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

Windows updates: download in the app with progress and resume, then install

Beeb35c860cded4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9f634ce..fcb52d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,36 @@ All notable changes to Nectarlink. Versions follow
[semantic versioning](https://semver.org); before 1.0, a minor version may
change things that need a step from you, and its notes say so.
+## 0.1.3 (2026-10-15)
+
+Updating the Windows app works on slow or unsteady connections, and shows
+how far it is.
+
+### Downloads
+
+| Download | For | Needs |
+|---|---|---|
+| [Nectarlink-0.1.3-x64-setup.exe](https://github.com/thtbee/nectarlink/releases/download/v0.1.3/Nectarlink-0.1.3-x64-setup.exe) | Windows | Windows 11, 64-bit |
+| [Nectarlink-0.1.3-android.apk](https://github.com/thtbee/nectarlink/releases/download/v0.1.3/Nectarlink-0.1.3-android.apk) | Android | Android 8.0 or newer |
+
+Both are listed with their SHA-256 hashes in [SHA256SUMS.txt](https://github.com/thtbee/nectarlink/releases/download/v0.1.3/SHA256SUMS.txt).
+Installed copies update themselves. If **Update** in 0.1.2 or earlier closes
+Nectarlink and nothing happens, install this version from the link above
+once; updates after it work from the app.
+
+### Fixed
+
+- **Updating the Windows app.** Clicking **Update** closed Nectarlink right
+ away, and the download that followed in the background could time out on a
+ slow connection to GitHub's download server. The update then failed with no
+ sign of it, and Nectarlink reopened only minutes later. Now Nectarlink stays
+ open while it downloads, shows the progress in **Settings › Connection &
+ About**, resumes a download that was cut off, and closes only once the
+ update is downloaded and checked. If an update doesn't install, Nectarlink
+ reopens and says so.
+- Slow responses from GitHub no longer fail update checks or downloads: the
+ Windows app waits longer and tries again.
+
## 0.1.2 (2026-10-15)
A smoother update on both devices, and the phone reconnects on its own after
diff --git a/Cargo.lock b/Cargo.lock
index 3ea8597..579f150 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2318,7 +2318,7 @@ dependencies = [
[[package]]
name = "nectarlink-adb"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"thiserror 2.0.21",
"tokio",
@@ -2328,7 +2328,7 @@ dependencies = [
[[package]]
name = "nectarlink-cli"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"anyhow",
"clap",
@@ -2347,7 +2347,7 @@ dependencies = [
[[package]]
name = "nectarlink-core"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"blake3",
"bytes",
@@ -2380,7 +2380,7 @@ dependencies = [
[[package]]
name = "nectarlink-desktop"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"anyhow",
"blake3",
@@ -2409,7 +2409,7 @@ dependencies = [
[[package]]
name = "nectarlink-ffi"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"nectarlink-core",
"paranoid-android",
@@ -2422,7 +2422,7 @@ dependencies = [
[[package]]
name = "nectarlink-protocol"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"ciborium",
"data-encoding",
@@ -2437,7 +2437,7 @@ dependencies = [
[[package]]
name = "nectarlink-vcam"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"ab_glyph",
"embed-resource",
@@ -5064,7 +5064,7 @@ dependencies = [
[[package]]
name = "xtask"
-version = "0.1.2"
+version = "0.1.3"
dependencies = [
"anyhow",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index 9dcda5a..81bf2cc 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
-version = "0.1.2"
+version = "0.1.3"
edition = "2024"
rust-version = "1.97"
authors = ["The Nectarlink contributors"]
@@ -25,10 +25,10 @@ repository = "https://github.com/thtbee/nectarlink"
name = "Pollen"
[workspace.dependencies]
-nectarlink-adb = { path = "core/nectarlink-adb", version = "0.1.2" }
-nectarlink-protocol = { path = "core/nectarlink-protocol", version = "0.1.2" }
-nectarlink-core = { path = "core/nectarlink-core", version = "0.1.2" }
-nectarlink-vcam = { path = "desktop/vcam", version = "0.1.2" }
+nectarlink-adb = { path = "core/nectarlink-adb", version = "0.1.3" }
+nectarlink-protocol = { path = "core/nectarlink-protocol", version = "0.1.3" }
+nectarlink-core = { path = "core/nectarlink-core", version = "0.1.3" }
+nectarlink-vcam = { path = "desktop/vcam", version = "0.1.3" }
anyhow = "1"
ciborium = "0.2"
diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qml
index ccd2ff8..8b8f30a 100644
--- a/desktop/app/qml/pages/SettingsPage.qml
+++ b/desktop/app/qml/pages/SettingsPage.qml
@@ -2962,10 +2962,33 @@ Item {
width: parent.width
iconPath: Icons.desktop
title: qsTr("Nectarlink %1").arg(AppController.version)
- description: qsTr("This PC: %1").arg(AppController.deviceName)
+ description: AppController.updateStatus.length > 0
+ ? AppController.updateStatus
+ : qsTr("This PC: %1").arg(AppController.deviceName)
Row {
spacing: 8
- Spinner { anchors.verticalCenter: parent.verticalCenter; visible: AppController.updateBusy }
+ // The download's progress, or a spinner while its size isn't known.
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: AppController.updateBusy && AppController.updateProgress >= 0
+ width: 120
+ height: 4
+ radius: 2
+ color: Theme.surfaceContainerHighest
+ Accessible.role: Accessible.ProgressBar
+ Accessible.name: qsTr("Update download")
+ Rectangle {
+ height: parent.height
+ radius: parent.radius
+ width: parent.width * Math.max(0, Math.min(1, AppController.updateProgress))
+ color: Theme.primary
+ Behavior on width { enabled: !Theme.reduceMotion; NumberAnimation { duration: 180 } }
+ }
+ }
+ Spinner {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: AppController.updateBusy && AppController.updateProgress < 0
+ }
Button {
visible: AppController.canUpdate
anchors.verticalCenter: parent.verticalCenter
diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rs
index 9392ffd..0c150ab 100644
--- a/desktop/app/src/bridge/app.rs
+++ b/desktop/app/src/bridge/app.rs
@@ -75,6 +75,11 @@ pub mod qobject {
#[qproperty(QString, update_version)]
/// Checking for or installing an update.
#[qproperty(bool, update_busy)]
+ /// How far the update's download is, 0 to 1 (-1: not downloading,
+ /// or the size isn't known yet).
+ #[qproperty(f64, update_progress)]
+ /// What the update is doing, for Settings ("" when idle).
+ #[qproperty(QString, update_status)]
/// Device ID and name of a phone asking to control this PC for the
/// first time while `remote_input` is off ("" when none).
#[qproperty(QString, remote_prompt_device_id)]
@@ -412,6 +417,8 @@ pub struct AppControllerRust {
can_update: bool,
update_version: QString,
update_busy: bool,
+ update_progress: f64,
+ update_status: QString,
remote_prompt_device_id: QString,
remote_prompt_device_name: QString,
pc_mirror_prompt_device_id: QString,
@@ -487,7 +494,9 @@ pub fn toggle_shelf_from_anywhere() {
}
}
-/// Downloads and starts the update (from the app or its notification).
+/// Downloads and starts the update (from the app or its notification),
+/// showing how far the download is. The app quits for the installer only
+/// once the download is checked; until then it keeps working.
pub fn install_update_in_background() {
let Some(qt) = controller() else { return };
let started = qt.queue(|mut object| {
@@ -495,13 +504,34 @@ pub fn install_update_in_background() {
return;
}
object.as_mut().set_update_busy(true);
- object.as_mut().toast(QString::from("Downloading the update…"));
+ object.as_mut().set_update_progress(-1.0);
+ object.as_mut().set_update_status(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 {
+ let progress_qt = qt.clone();
+ let result = crate::updater::install(move |done, total| {
+ let fraction = if total > 0 { (done as f64 / total as f64).clamp(0.0, 1.0) } else { -1.0 };
+ let text = if total > 0 {
+ format!("Downloading the update · {} of {}", megabytes(done), megabytes(total))
+ } else {
+ "Downloading the update…".to_owned()
+ };
+ let _ = progress_qt.queue(move |mut object| {
+ object.as_mut().set_update_progress(fraction);
+ object.as_mut().set_update_status(QString::from(&text));
+ });
+ });
+ let _ = qt.queue(move |mut object| match result {
+ Ok(()) => {
+ object.as_mut().set_update_progress(-1.0);
+ object
+ .as_mut()
+ .set_update_status(QString::from("Installing. Nectarlink reopens by itself."));
+ }
+ Err(message) => {
+ object.as_mut().set_update_busy(false);
+ object.as_mut().set_update_progress(-1.0);
+ object.as_mut().set_update_status(QString::default());
object.toast(QString::from(&message));
}
});
@@ -512,6 +542,11 @@ pub fn install_update_in_background() {
}
}
+/// `12.3 MB`, for download progress.
+fn megabytes(bytes: u64) -> String {
+ format!("{:.1} MB", bytes as f64 / 1_000_000.0)
+}
+
/// 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>) {
@@ -676,6 +711,8 @@ impl cxx_qt::Initialize for qobject::AppController {
self.as_mut().set_version(QString::from(env!("CARGO_PKG_VERSION")));
self.as_mut().set_current_page(QString::from("home"));
self.as_mut().set_can_update(crate::updater::can_update());
+ // Nothing downloading yet (0 would show an empty bar).
+ self.as_mut().set_update_progress(-1.0);
self.as_mut().set_clipboard_history(QString::from(&crate::clipboard::history_json()));
self.as_mut().set_timeline_preview(QString::from(&super::timeline::preview_json()));
self.as_mut().set_command_palette_results(QString::from("[]"));
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index 404569f..2b617a1 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -551,9 +551,11 @@ fn main() -> ExitCode {
updater::set_auto(settings.auto_update);
updater::set_auto_install(settings.install_updates);
updater::start();
- let previous = updater::note_running_version(&data_dir);
- if previous.is_some() || options.updated {
- updater::announce_update(previous, !options.minimized);
+ match (updater::note_running_version(&data_dir), options.updated) {
+ (Some(previous), _) => updater::announce_update(previous, !options.minimized),
+ // Reopened by the relauncher, still on this version.
+ (None, true) => updater::announce_update_failed(!options.minimized),
+ (None, false) => {}
}
}
// Requests left while no instance was running, then this launch's own.
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index e9ee23c..4112b29 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -13,9 +13,16 @@
//! away. Without the task (a copy installed before it existed), "Update"
//! runs the installer with the usual administrator prompt.
//!
-//! The installer replaces the running app, so the app starts a small hidden
-//! relauncher first and quits; the relauncher opens the new version once the
-//! installer is done.
+//! The app downloads the installer first, as the user, showing progress and
+//! resuming after a dropped connection ([`stage`]), into a shared folder.
+//! The task takes that file only when it matches the release's sums, which
+//! it fetches itself, and copies it somewhere only SYSTEM can write before
+//! checking and running it; otherwise it downloads the installer itself.
+//!
+//! The installer replaces the running app, so once the download is ready the
+//! app starts a small hidden relauncher and quits; the relauncher opens the
+//! new version once the installer is done, or the old one again if the
+//! update didn't go through.
use std::{
os::windows::process::CommandExt,
@@ -40,7 +47,7 @@ use crate::{
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;
+const MAX_INSTALLER: u64 = 400 * 1024 * 1024;
/// The toast "device" for update notices.
pub const TOAST_GROUP: &str = "update";
pub const ACTION_UPDATE: &str = "update";
@@ -116,7 +123,10 @@ pub fn start() {
&& task_registered()
{
tracing::info!("installing the update at a quiet moment");
- if let Err(e) = install_with_task(false) {
+ let staged = available().map(|update| stage(&update, |_, _| {}));
+ if let Some(Err(e)) = staged {
+ tracing::info!(error = %e, "the automatic update couldn't be downloaded yet");
+ } else if let Err(e) = install_with_task(false) {
tracing::warn!(error = e, "the automatic update didn't start");
}
}
@@ -303,11 +313,17 @@ fn task_registered() -> bool {
.is_ok_and(|s| s.success())
}
-/// Installs the update found: with [`TASK`] when it's there (no prompt),
+/// Installs the update found: downloads it (reporting `progress(done,
+/// total)`), then installs with [`TASK`] when it's there (no prompt),
/// otherwise by running the installer, which asks for administrator rights.
-/// Blocking. Returns what went wrong, in words for the user.
-pub fn install() -> Result<(), String> {
- available().ok_or("There's no update to install.")?;
+/// 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> {
+ 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(()),
@@ -316,7 +332,107 @@ pub fn install() -> Result<(), String> {
}
}
}
- install_with_prompt()
+ install_with_prompt(&update, &staged)
+}
+
+/// Why a download didn't produce a checked installer.
+#[derive(Debug)]
+pub enum StageError {
+ Network(String),
+ Damaged,
+ Disk(String),
+}
+
+impl StageError {
+ fn for_user(&self) -> String {
+ match self {
+ StageError::Network(_) => {
+ "The update couldn't be downloaded. Check your internet connection and try again.".into()
+ }
+ StageError::Damaged => "The download was damaged, so it wasn't installed. Try again.".into(),
+ StageError::Disk(_) => {
+ "The update couldn't be saved. Check that there's free space and try again.".into()
+ }
+ }
+ }
+}
+
+impl std::fmt::Display for StageError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ StageError::Network(e) => write!(f, "network: {e}"),
+ StageError::Damaged => f.write_str("checksum mismatch"),
+ StageError::Disk(e) => write!(f, "disk: {e}"),
+ }
+ }
+}
+
+/// 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.
+fn staging_dir() -> PathBuf {
+ std::env::var_os("ProgramData")
+ .map(PathBuf::from)
+ .filter(|p| p.is_absolute())
+ .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
+ .join("Nectarlink")
+ .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)?;
+ listed_hash(&String::from_utf8_lossy(&sums), &update.installer_name).ok_or(StageError::Damaged)
+}
+
+fn sha256_file(path: &Path) -> std::io::Result<String> {
+ use std::io::Read;
+ let mut file = std::fs::File::open(path)?;
+ let mut hasher = Sha256::new();
+ let mut buffer = vec![0u8; 256 * 1024];
+ loop {
+ let read = file.read(&mut buffer)?;
+ if read == 0 {
+ break;
+ }
+ hasher.update(&buffer[..read]);
+ }
+ Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
+}
+
+/// Downloads the installer into the staging folder (continuing a download
+/// cut short before), checks it, and returns its path. Reuses one already
+/// downloaded and checked.
+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()))?;
+ let path = dir.join(&update.installer_name);
+ let part = dir.join(format!("{}.part", update.installer_name));
+ // Older versions' files.
+ if let Ok(entries) = std::fs::read_dir(&dir) {
+ for entry in entries.flatten() {
+ let p = entry.path();
+ if p != path && p != part {
+ let _ = std::fs::remove_file(p);
+ }
+ }
+ }
+ if sha256_file(&path).is_ok_and(|h| h == expected) {
+ return Ok(path);
+ }
+ let _ = std::fs::remove_file(&path);
+ http::download(&update.installer_url, &part, MAX_INSTALLER, progress).map_err(StageError::Network)?;
+ match sha256_file(&part) {
+ Ok(actual) if actual == expected => {}
+ Ok(_) => {
+ let _ = std::fs::remove_file(&part);
+ return Err(StageError::Damaged);
+ }
+ Err(e) => return Err(StageError::Disk(e.to_string())),
+ }
+ std::fs::rename(&part, &path).map_err(|e| StageError::Disk(e.to_string()))?;
+ Ok(path)
}
/// Starts [`TASK`], and quits so the installer can replace this copy; a
@@ -375,12 +491,19 @@ fn relauncher_script(exe: &str, version: &str, arguments: &str) -> String {
};
format!(
"$key = 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Nectarlink'\n\
- $deadline = (Get-Date).AddMinutes(10)\n\
- Start-Sleep -Seconds 5\n\
+ $log = Join-Path (Split-Path -Parent '{exe}') 'update.log'\n\
+ $since = Get-Date\n\
+ $deadline = $since.AddMinutes(10)\n\
+ Start-Sleep -Seconds 3\n\
while ((Get-Date) -lt $deadline) {{\n\
$installed = (Get-ItemProperty -Path $key -Name DisplayVersion -ErrorAction SilentlyContinue).DisplayVersion\n\
$running = Get-Process -ErrorAction SilentlyContinue | Where-Object {{ $_.Name -like 'Nectarlink-*-setup' }}\n\
if ($installed -eq '{version}' -and -not $running) {{ break }}\n\
+ $logged = Get-Item -LiteralPath $log -ErrorAction SilentlyContinue\n\
+ if ($logged -and $logged.LastWriteTime -gt $since -and -not $running) {{\n\
+ $last = Get-Content -LiteralPath $log -Tail 1 -ErrorAction SilentlyContinue\n\
+ if ($last -and $last -notmatch 'installing') {{ break }}\n\
+ }}\n\
Start-Sleep -Seconds 2\n\
}}\n\
{start}\n"
@@ -482,62 +605,50 @@ fn service_dir() -> std::io::Result<PathBuf> {
Ok(dir)
}
-/// Downloads the installer and its sums into `dir`, checks it, and returns
-/// its path. Errors are for the log.
+/// 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.
fn download_verified(update: &Update, dir: &Path) -> Result<PathBuf, String> {
- let sums = http::get(&update.sums_url, 64 * 1024)?;
- let expected = listed_hash(&String::from_utf8_lossy(&sums), &update.installer_name)
- .ok_or("the checksum is missing from the release")?;
- let installer = http::get(&update.installer_url, MAX_INSTALLER)?;
- let actual = Sha256::digest(&installer).iter().map(|b| format!("{b:02x}")).collect::<String>();
- if actual != expected {
- return Err("checksum mismatch".into());
- }
+ let expected = expected_hash(update).map_err(|e| e.to_string())?;
let path = dir.join(&update.installer_name);
- {
- use std::io::Write;
- let mut file = std::fs::OpenOptions::new()
- .write(true)
- .create_new(true)
- .open(&path)
- .map_err(|e| e.to_string())?;
- file.write_all(&installer).and_then(|()| file.sync_all()).map_err(|e| e.to_string())?;
+ // Copied first and checked after, so what's checked is what runs.
+ let staged = staging_dir().join(&update.installer_name);
+ if staged.is_file() && std::fs::copy(&staged, &path).is_ok() {
+ if sha256_file(&path).is_ok_and(|h| h == expected) {
+ return Ok(path);
+ }
+ let _ = std::fs::remove_file(&path);
+ }
+ http::download(&update.installer_url, &path, MAX_INSTALLER, |_, _| {})?;
+ if sha256_file(&path).map_err(|e| e.to_string())? != expected {
+ let _ = std::fs::remove_file(&path);
+ return Err("checksum mismatch".into());
}
Ok(path)
}
-/// The installer with Windows' administrator prompt (no update task).
-fn install_with_prompt() -> Result<(), String> {
- let update = available().ok_or("There's no update to install.")?;
+/// 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.
+fn install_with_prompt(update: &Update, staged: &Path) -> Result<(), String> {
let failed = |e: String| {
tracing::warn!(error = e, "update failed");
- "The update couldn't be downloaded. Try again later.".to_owned()
+ "The update couldn't be started. Try again.".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 expected = expected_hash(update).map_err(|e| e.for_user())?;
let dir = std::env::temp_dir().join("Nectarlink update");
let path: PathBuf = dir.join(&update.installer_name);
- // A fresh file each time (an older copy is removed first), written in one go and run
- // straight after, so what runs is what was checked.
std::fs::create_dir_all(&dir)
.and_then(|()| match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
})
- .and_then(|()| {
- use std::io::Write;
- let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path)?;
- file.write_all(&installer)?;
- file.sync_all()
- })
+ .and_then(|()| std::fs::copy(staged, &path).map(|_| ()))
.map_err(|e| failed(e.to_string()))?;
+ if sha256_file(&path).map_err(|e| failed(e.to_string()))? != expected {
+ let _ = std::fs::remove_file(&path);
+ return Err(StageError::Damaged.for_user());
+ }
// 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)?;
@@ -568,9 +679,28 @@ pub fn note_running_version(data_dir: &Path) -> Option<String> {
/// Just updated: says so, and when the window was asked for, brings it to
/// the front. Started from the background, Windows would otherwise leave
/// the new window behind whatever the user has open.
-pub fn announce_update(previous: Option<String>, shown: bool) {
+pub fn announce_update(previous: String, shown: bool) {
let current = env!("CARGO_PKG_VERSION");
- tracing::info!(from = previous.as_deref().unwrap_or("?"), to = current, "updated");
+ tracing::info!(from = previous, to = current, "updated");
+ after_start(
+ shown,
+ format!("Nectarlink is updated to {current}"),
+ "Your phone reconnects on its own.".into(),
+ );
+}
+
+/// The relauncher opened this version again because the update didn't
+/// install (`update.log` says why).
+pub fn announce_update_failed(shown: bool) {
+ tracing::warn!("the update didn't install");
+ after_start(
+ shown,
+ "The update didn't install".into(),
+ "Nectarlink is still on the version you had. Try again from Settings.".into(),
+ );
+}
+
+fn after_start(shown: bool, title: String, body: String) {
std::thread::spawn(move || {
// Once the window exists.
std::thread::sleep(Duration::from_millis(1500));
@@ -580,8 +710,8 @@ pub fn announce_update(previous: Option<String>, shown: bool) {
toast::show(toast::Toast {
device: TOAST_GROUP.into(),
key: "updated".into(),
- title: format!("Nectarlink is updated to {current}"),
- body: "Your phone reconnects on its own.".into(),
+ title,
+ body,
attribution: "Nectarlink".into(),
icon: None,
image: None,
diff --git a/desktop/app/src/win/http.rs b/desktop/app/src/win/http.rs
index e482951..b0184f5 100644
--- a/desktop/app/src/win/http.rs
+++ b/desktop/app/src/win/http.rs
@@ -3,15 +3,38 @@
//! proxy settings and certificates, and no extra dependencies. Used to
//! check for updates and download them.
+use std::{
+ io::Write,
+ path::Path,
+ time::{Duration, Instant},
+};
+
use windows::{
Win32::Networking::WinHttp::{
- WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_FLAG_SECURE, WINHTTP_QUERY_FLAG_NUMBER,
+ WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_FLAG_SECURE, WINHTTP_QUERY_CONTENT_LENGTH,
+ WINHTTP_QUERY_CUSTOM, WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_QUERY_FLAG_NUMBER64,
WINHTTP_QUERY_STATUS_CODE, WinHttpCloseHandle, WinHttpConnect, WinHttpOpen, WinHttpOpenRequest,
WinHttpQueryHeaders, WinHttpReadData, WinHttpReceiveResponse, WinHttpSendRequest, WinHttpSetTimeouts,
},
core::{HSTRING, PCWSTR, w},
};
+/// Resolve, connect, send and receive limits (ms). GitHub's download host
+/// can take well over ten seconds to answer on a slow or busy link.
+const TIMEOUTS: (i32, i32, i32, i32) = (30_000, 30_000, 30_000, 60_000);
+
+/// 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),
+];
+
/// A handle closed when dropped.
struct Handle(*mut core::ffi::c_void);
@@ -30,14 +53,71 @@ 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> {
+/// An open response: its status and, for reading, the handles behind it
+/// (declared children first, so they close before their parents).
+struct Response {
+ request: Handle,
+ _connection: Handle,
+ _session: Handle,
+ status: u32,
+}
+
+impl Response {
+ /// The body's length when the server said, or the full size from a
+ /// `Content-Range` (`bytes 100-199/200`).
+ fn length(&self) -> Option<u64> {
+ let mut value: u64 = 0;
+ let mut size = std::mem::size_of::<u64>() as u32;
+ // SAFETY: a valid request handle and an output buffer of the stated size.
+ let ok = unsafe {
+ WinHttpQueryHeaders(
+ self.request.0,
+ WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER64,
+ PCWSTR::null(),
+ Some((&raw mut value).cast()),
+ &mut size,
+ std::ptr::null_mut(),
+ )
+ };
+ ok.is_ok().then_some(value)
+ }
+
+ fn header(&self, name: &str) -> Option<String> {
+ let name = HSTRING::from(name);
+ let mut buffer = [0u16; 256];
+ let mut size = std::mem::size_of_val(&buffer) as u32;
+ // SAFETY: a valid request handle and an output buffer of the stated size.
+ let ok = unsafe {
+ WinHttpQueryHeaders(
+ self.request.0,
+ WINHTTP_QUERY_CUSTOM,
+ &name,
+ Some(buffer.as_mut_ptr().cast()),
+ &mut size,
+ std::ptr::null_mut(),
+ )
+ };
+ ok.is_ok().then(|| String::from_utf16_lossy(&buffer[..size as usize / 2]))
+ }
+
+ /// The next chunk of the body; empty at the end.
+ fn read<'a>(&self, chunk: &'a mut [u8]) -> Result<&'a [u8], String> {
+ let mut read = 0u32;
+ // SAFETY: a valid request handle and a buffer of the stated size.
+ unsafe { WinHttpReadData(self.request.0, chunk.as_mut_ptr().cast(), chunk.len() as u32, &mut read) }
+ .map_err(|e| format!("read: {e}"))?;
+ Ok(&chunk[..read as usize])
+ }
+}
+
+/// Sends a GET for an `https://` URL (following redirects), asking for the
+/// bytes from `from` on when that's past 0.
+fn open(url: &str, from: u64) -> Result<Response, 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).
+ // `Handle`.
unsafe {
let session = Handle(WinHttpOpen(
&agent,
@@ -49,8 +129,8 @@ pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
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 (resolve, connect, send, receive) = TIMEOUTS;
+ let _ = WinHttpSetTimeouts(session.0, resolve, connect, send, receive);
let connection = Handle(WinHttpConnect(session.0, &HSTRING::from(host), 443, 0));
if connection.0.is_null() {
return Err(last_error("WinHttpConnect"));
@@ -67,9 +147,12 @@ pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
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();
+ // GitHub's API wants the Accept header; it's harmless elsewhere.
+ let mut headers = "Accept: application/vnd.github+json, application/octet-stream\r\n".to_owned();
+ if from > 0 {
+ headers.push_str(&format!("Range: bytes={from}-\r\n"));
+ }
+ let headers: Vec<u16> = headers.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;
@@ -83,31 +166,166 @@ pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
std::ptr::null_mut(),
)
.map_err(|e| format!("status: {e}"))?;
- if status != 200 {
- return Err(format!("HTTP {status}"));
+ Ok(Response { request, _connection: connection, _session: session, status })
+ }
+}
+
+/// Fetches an `https://` URL (following redirects), up to `limit` bytes.
+pub fn get(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ let response = open(url, 0)?;
+ if response.status != 200 {
+ return Err(format!("HTTP {}", response.status));
+ }
+ let mut body = Vec::new();
+ let mut chunk = vec![0u8; 64 * 1024];
+ loop {
+ let data = response.read(&mut chunk)?;
+ if data.is_empty() {
+ break;
+ }
+ body.extend_from_slice(data);
+ if body.len() > limit {
+ return Err("too large".into());
}
- 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;
+ }
+ Ok(body)
+}
+
+/// Like [`get`], retrying network errors a few times.
+pub fn get_retrying(url: &str, limit: usize) -> Result<Vec<u8>, String> {
+ let mut attempt = 0;
+ loop {
+ match get(url, limit) {
+ 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;
}
- body.extend_from_slice(&chunk[..read as usize]);
- if body.len() > limit {
- return Err("too large".into());
+ Err(e) => return Err(e),
+ }
+ }
+}
+
+/// 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"),
+ }
+}
+
+/// 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,
+ mut progress: impl FnMut(u64, u64),
+) -> Result<(), 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),
}
- Ok(body)
}
}
+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 response = open(url, have)?;
+ let (append, total) = match response.status {
+ 206 => {
+ let total = response.header("Content-Range").and_then(|r| range_total(&r));
+ (true, total.or_else(|| response.length().map(|l| have + l)).unwrap_or(0))
+ }
+ 200 => (false, response.length().unwrap_or(0)),
+ // Asked for bytes past the end: it's all here already.
+ 416 if have > 0 => return Ok(()),
+ status => return Err(format!("HTTP {status}")),
+ };
+ if total > limit {
+ return Err("too large".into());
+ }
+ let mut output = std::fs::OpenOptions::new()
+ .create(true)
+ .write(true)
+ .append(append)
+ .truncate(!append)
+ .open(file)
+ .map_err(|e| format!("write: {e}"))?;
+ let mut done = if append { have } else { 0 };
+ progress(done, total);
+ let mut chunk = vec![0u8; 256 * 1024];
+ let mut reported = Instant::now();
+ loop {
+ let data = response.read(&mut chunk)?;
+ if data.is_empty() {
+ break;
+ }
+ done += data.len() as u64;
+ if done > limit {
+ return Err("too large".into());
+ }
+ output.write_all(data).map_err(|e| format!("write: {e}"))?;
+ if reported.elapsed() >= Duration::from_millis(200) {
+ reported = Instant::now();
+ progress(done, total);
+ }
+ }
+ output.sync_all().map_err(|e| format!("write: {e}"))?;
+ progress(done, total);
+ if total > 0 && done < total {
+ return Err("the download ended early".into());
+ }
+ 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)
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[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 retries_network_trouble_but_not_refusals() {
+ assert!(retryable("receive: The operation timed out (0x80072EE2)"));
+ assert!(retryable("HTTP 503"));
+ assert!(retryable("HTTP 429"));
+ assert!(!retryable("HTTP 404"));
+ assert!(!retryable("too large"));
+ assert!(!retryable("only https"));
+ }
+
/// Needs the internet: `cargo test -- --ignored`.
#[test]
#[ignore]
@@ -117,4 +335,39 @@ mod tests {
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");
}
+
+ /// Needs the internet: resumes a download from the middle.
+ #[test]
+ #[ignore]
+ fn resumes_a_download() {
+ let url = "https://github.com/thtbee/nectarlink/releases/download/v0.1.0/SHA256SUMS.txt";
+ let dir = tempfile::tempdir().unwrap();
+ let whole = dir.path().join("whole");
+ download(url, &whole, 1 << 20, |_, _| {}).unwrap();
+ let full = std::fs::read(&whole).unwrap();
+ let part = dir.path().join("part");
+ std::fs::write(&part, &full[..50]).unwrap();
+ download(url, &part, 1 << 20, |_, _| {}).unwrap();
+ assert_eq!(std::fs::read(&part).unwrap(), full);
+ }
+}
+
+#[cfg(test)]
+mod release_download {
+ /// Needs the internet: the real installer, as an update downloads it.
+ #[test]
+ #[ignore]
+ fn downloads_a_release_installer() {
+ let url =
+ "https://github.com/thtbee/nectarlink/releases/download/v0.1.2/Nectarlink-0.1.2-x64-setup.exe";
+ let dir = tempfile::tempdir().unwrap();
+ let file = dir.path().join("setup.exe.part");
+ let started = std::time::Instant::now();
+ let mut reports = 0;
+ super::download(url, &file, 400 << 20, |_, _| reports += 1).unwrap();
+ let len = std::fs::metadata(&file).unwrap().len();
+ println!("{len} bytes in {:?}, {reports} progress reports", started.elapsed());
+ assert_eq!(len, 38_473_164);
+ assert!(reports > 5);
+ }
}
diff --git a/docs/technical/security-model.md b/docs/technical/security-model.md
index 41d6fe9..565490c 100644
--- a/docs/technical/security-model.md
+++ b/docs/technical/security-model.md
@@ -121,7 +121,7 @@ Implemented in `desktop/app/src/updater.rs` (`win/http.rs`), `desktop/installer/
- **Endpoint**: Both apps query `https://api.github.com/repos/thtbee/nectarlink/releases/latest` over HTTPS with the OS TLS stack (`WinHTTP`, `HttpURLConnection`). Only `https://` URLs are fetched, redirects stay on HTTPS, and responses are size-capped while they are read. No device identifiers or telemetry are sent.
- **What is accepted**: a published release (not a draft or pre-release) whose version is newer than the running one, with an installer named `Nectarlink-*-x64-setup.exe` (Windows, a plain file name) or `*-android.apk`, and a `SHA256SUMS.txt` that lists it. The download is rejected unless its SHA-256 matches. Android additionally refuses an APK not signed with the app's own key.
-- **Windows, installing without a prompt**: the app is installed per machine, so installing needs administrator rights. The installer registers the scheduled task **Nectarlink Update**, which runs `nectarlink-desktop.exe --update-service` as SYSTEM. Its security descriptor gives SYSTEM and Administrators full control and authenticated users read and execute only, so a signed-in user can start it but not change what it runs. The task takes no arguments or input from the user: it fetches the latest release itself and applies the checks above. It downloads into a new randomly named folder in `C:\Windows\SystemTemp` (writable only by SYSTEM and administrators), runs the installer with `/S`, and logs to `update.log` in the install folder. The worst a user can do by starting it is install the latest official release early.
+- **Windows, installing without a prompt**: the app is installed per machine, so installing needs administrator rights. The installer registers the scheduled task **Nectarlink Update**, which runs `nectarlink-desktop.exe --update-service` as SYSTEM. Its security descriptor gives SYSTEM and Administrators full control and authenticated users read and execute only, so a signed-in user can start it but not change what it runs. The task takes no arguments or input from the user: it fetches the latest release itself and applies the checks above. When the user clicks **Update**, the app first downloads the installer itself (resumable, with progress) into `%ProgramData%\Nectarlink\updates` and checks it against the sums. The task copies that file into a new randomly named folder in `C:\Windows\SystemTemp` (writable only by SYSTEM and administrators) and checks the copy against the sums it fetched itself, so a file planted in the shared folder can only ever be the official installer. When there is no matching file, it downloads the installer into that folder itself. It then runs the installer with `/S` and logs to `update.log` in the install folder. The worst a user can do by starting it is install the latest official release early.
- **Windows, when**: with **Install updates automatically** on, the app starts the task once nobody has used the PC for 10 minutes and nothing would be interrupted (mirroring, an app window, a transfer, a call, screen sharing, the webcam). It first starts a hidden relauncher, which reopens the app once the new version's `DisplayVersion` is in the uninstall key and the installer has exited, then quits. Without the task (copies installed before it existed) **Update** runs the installer with the usual UAC prompt.
- **Android**: with **Install updates automatically** on, the connection service checks in the background at most once a day and installs through `PackageInstaller` with `USER_ACTION_NOT_REQUIRED` (Android 12+, `UPDATE_PACKAGES_WITHOUT_USER_ACTION`). Android skips the prompt only when Nectarlink installed the current version itself; otherwise the user confirms from a notification.
- **Opt-out**: **Check for updates** and **Install updates automatically** in Settings on both apps. With checks off, nothing is fetched.