diff --git a/CHANGELOG.md b/CHANGELOG.md index a76ba77..026de63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ Each release's installer and full notes are on [GitHub Releases](https://github.com/Xarishark/Director/releases). +## Unreleased + +- **Updates**: Director checks GitHub for a newer version when the window opens and offers **Install update**, which downloads setup, verifies its SHA-256 checksum and starts it. Turn the check off or check by hand in **Options → About**; `director update [--install]` does the same from a terminal. + ## 0.13.0 (2026-11-08) - Director is open source under the **MIT License**. The installer adds `LICENSE.txt` and the third-party notices beside the app. diff --git a/README.md b/README.md index 0f490d1..dfa350c 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ Director talks to Windows, the NVIDIA driver, RTSS and your TV directly, from on ## Install -Director needs **Windows 11, version 24H2 or newer** (x64), because switching HDR per screen uses display APIs that Windows added in 24H2. Download **Director-x64-setup.exe** with the button above and run it. Setup installs the Windows App Runtime if it's missing and adds `director` to PATH. See [Install](docs/INSTALL.md) for quiet installs, updates and uninstalling. +Director needs **Windows 11, version 24H2 or newer** (x64), because switching HDR per screen uses display APIs that Windows added in 24H2. Download **Director-x64-setup.exe** with the button above and run it. Setup installs the Windows App Runtime if it's missing and adds `director` to PATH. Director tells you when a new version is out and installs it in a click. See [Install](docs/INSTALL.md) for quiet installs, updates and uninstalling. ## Quick start diff --git a/SECURITY.md b/SECURITY.md index fc334dd..68b71f0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,6 +16,7 @@ Director runs locally and controls devices on your home network. Areas where a b - **TV connections**: the TLS connection and certificate checks for Android TV Remote v2, certificate pinning for LG and Samsung, and parsing anything a device on the network sends back. - **Local data**: settings, backups and reports written to disk, and what crash reports and the **Report on GitHub** link include. - **The installer**: `setup.exe` downloads the Windows App Runtime from Microsoft and checks its SHA-512 hash before running it. +- **Updates**: Director downloads setup only from this repository's GitHub releases, over HTTPS, and runs it only if its SHA-256 matches the digest GitHub reports for the release asset. - **The `director-run:` link handler** that the installer registers. Director's own design assumes a trusted home network. Problems that need an attacker who already controls the PC or the Windows account are out of scope. diff --git a/docs/INSTALL.md b/docs/INSTALL.md index f206ea5..5b7a8e7 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -31,7 +31,13 @@ From an elevated terminal: ## Update -Download and run the newer setup. It replaces the installed version and keeps your settings. `director --version` or **Options → About** shows the installed version. +When you open the window, Director asks GitHub for the latest release. If there's a newer one, a bar at the bottom of the Scenes page offers **Install update**. Director downloads setup with a progress bar, checks it against the SHA-256 checksum GitHub publishes for the release, starts it and closes so setup can replace the files. Confirm the Windows prompt; setup shows only its progress, with nothing to click, and Director reopens when it's done. Your settings and desktop shortcut stay as they are. If you cancel the prompt or setup fails, Director stays closed and offers the update again next time. Nothing is downloaded or installed until you choose it. + +- **Options → About** has **Check for updates** and the switch for the check at startup. With the switch off, Director contacts GitHub only when you ask. +- From a terminal: `director update` says whether a newer version exists; `director update --install` downloads, verifies and starts setup (it doesn't reopen the window). Commands never check on their own, so shortcuts and Stream Deck buttons stay offline. +- You can still download and run the newer setup yourself. `director --version` or **Options → About** shows the installed version. + +A copy that isn't the installed one (for example a build from source) offers **Download** instead, which opens the release page. ## Uninstall diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f078c03..4dbf8e2 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -42,6 +42,10 @@ FPS director fps status director fps set +Updates + director update Check GitHub for a newer version + director update --install Download it, verify its checksum and start setup + director --version Without arguments, opens the window. Leaving out the device in an audio command means the @@ -108,6 +112,9 @@ pub fn run(args: &[String]) -> i32 { if args.first().is_some_and(|area| area == "fps") { return crate::fps::windows_fps::cli(&args[1..]); } + if args.first().is_some_and(|area| area == "update") { + return crate::update::cli(&args[1..]); + } if args.first().is_some_and(|area| area == "audio") { return crate::audio::audio_cli::run(&args[1..]); } diff --git a/src/gui/mod.rs b/src/gui/mod.rs index 95ee7e6..f169258 100644 --- a/src/gui/mod.rs +++ b/src/gui/mod.rs @@ -26,3 +26,4 @@ pub(crate) mod tv_power_state; pub(crate) mod tv_tip_ui; pub(crate) mod tv_ui; pub(crate) mod ui; +pub(crate) mod update_ui; diff --git a/src/gui/options_ui.rs b/src/gui/options_ui.rs index 536a30d..4d1feab 100644 --- a/src/gui/options_ui.rs +++ b/src/gui/options_ui.rs @@ -436,13 +436,16 @@ impl DirectorApp { "About", "", None, - StackPanel::new().spacing(2.0).children(( - ui::label(concat!("Director ", env!("CARGO_PKG_VERSION"))), - ui::note(env!("CARGO_PKG_DESCRIPTION")), - ui::caption(concat!( - env!("CARGO_PKG_AUTHORS"), - " · Requires Windows 11, version 24H2 or newer." + StackPanel::new().spacing(ui::GAP_L).children(( + StackPanel::new().spacing(2.0).children(( + ui::label(concat!("Director ", env!("CARGO_PKG_VERSION"))), + ui::note(env!("CARGO_PKG_DESCRIPTION")), + ui::caption(concat!( + env!("CARGO_PKG_AUTHORS"), + " · Requires Windows 11, version 24H2 or newer." + )), )), + self.update_settings(cx, editable), )), ); ui::page( diff --git a/src/gui/status_ui.rs b/src/gui/status_ui.rs index 64e40f4..b8fd68d 100644 --- a/src/gui/status_ui.rs +++ b/src/gui/status_ui.rs @@ -118,8 +118,11 @@ impl DirectorApp { TextBlock::new() .text(self.status.clone()) .opacity(0.72) - .text_trimming(TextTrimming::CharacterEllipsis), - ProgressBar::new().is_indeterminate(true), + .text_wrapping(TextWrapping::Wrap), + match self.update_progress() { + Some(done) => ProgressBar::new().maximum(1.0).value(done), + None => ProgressBar::new().is_indeterminate(true), + }, )); } match &self.notices.notice { diff --git a/src/gui/tv_tip_ui.rs b/src/gui/tv_tip_ui.rs index 38a1117..6da6e6c 100644 --- a/src/gui/tv_tip_ui.rs +++ b/src/gui/tv_tip_ui.rs @@ -24,6 +24,7 @@ pub(crate) enum TipMessage { KeepCompleted(bool), DeviceWait(Option), InputGuard(Option), + CheckUpdates(bool), /// Hide the Scenes page's "make your next scene" tip for good. HideNextSceneTip, Saved(Result), @@ -64,6 +65,7 @@ impl DirectorApp { message @ (TipMessage::Show(_) | TipMessage::NotifySceneFailures(_) | TipMessage::KeepCompleted(_) + | TipMessage::CheckUpdates(_) | TipMessage::HideNextSceneTip | TipMessage::DeviceWait(Some(_)) | TipMessage::InputGuard(Some(_))) @@ -82,6 +84,7 @@ impl DirectorApp { next.notify_scene_failures = enabled } TipMessage::KeepCompleted(keep) => next.keep_completed_changes = keep, + TipMessage::CheckUpdates(on) => next.check_for_updates = on, TipMessage::HideNextSceneTip => next.hide_next_scene_tip = true, TipMessage::DeviceWait(Some(seconds)) => { next.device_wait_seconds = seconds.round().clamp(1.0, 120.0) as u16 diff --git a/src/gui/update_ui.rs b/src/gui/update_ui.rs new file mode 100644 index 0000000..9de9812 --- /dev/null +++ b/src/gui/update_ui.rs @@ -0,0 +1,306 @@ +//! Updates in the window: the startup check, the "new version" banner, and Options' About +//! controls. Installing downloads setup, verifies it, starts it and closes Director so +//! setup can replace the files. +use crate::{DirectorApp, Message, Page, work}; +use director::update::{self, Release}; +use std::sync::{ + Arc, + atomic::{AtomicU64, Ordering}, +}; +use windows_reactor::*; + +#[derive(Default)] +pub(crate) struct UpdateState { + /// A newer release found by the last check. + pub available: Option, + /// The banner was closed for this session. + pub dismissed: bool, + pub checking: bool, + /// While setup downloads: bytes so far (shared with the worker), the expected size, and + /// the count last shown. + download: Option<(Arc, u64, u64)>, + /// What the last check from Options found, shown under its button. + pub result: Option>, +} + +#[derive(Clone)] +pub(crate) enum UpdateMessage { + /// Ask GitHub; `true` when the user asked from Options. + Check(bool), + Checked(bool, Result, String>), + Install, + Started(Result<(), String>), + ReleaseNotes, + /// Redraw the download progress. + Tick, + Dismiss, +} + +fn msg(message: UpdateMessage) -> Message { + Message::Update(message) +} + +/// The startup check, unless Options turned it off. +#[cfg(not(test))] +pub(crate) fn startup() -> Message { + let result = if director::preferences::current().check_for_updates { + update::check() + } else { + Ok(None) + }; + msg(UpdateMessage::Checked(false, result)) +} + +impl DirectorApp { + pub(crate) fn update_update(&mut self, message: UpdateMessage, cx: &ComponentContext) { + match message { + UpdateMessage::Check(manual) if !self.update.checking => { + self.update.checking = true; + self.update.result = None; + work(cx, move || { + msg(UpdateMessage::Checked(manual, update::check())) + }); + } + UpdateMessage::Checked(manual, result) => { + self.update.checking = false; + // The startup check stays quiet unless it finds something; its errors are + // only logged. + let result = match result { + Ok(Some(release)) => { + let text = format!("Director {} is available.", release.version); + if manual { + self.update.dismissed = false; + } + self.update.available = Some(release); + Ok(text) + } + Ok(None) => { + self.update.available = None; + Ok(format!( + "Director {} is up to date.", + update::Version::current() + )) + } + Err(e) => Err(e), + }; + self.update.result = manual.then_some(result); + } + UpdateMessage::ReleaseNotes => { + let page = self.update.available.as_ref().map_or( + "https://github.com/Xarishark/Director/releases/latest", + |r| r.page.as_str(), + ); + if let Err(e) = director::crash::open(page) { + self.failure(e); + } + } + UpdateMessage::Install if self.ready() => { + let Some(release) = self.update.available.clone() else { + return; + }; + if !update::installed() { + // A copy outside Program Files: setup would install beside it, so let the + // user decide from the release page. + self.update_update(UpdateMessage::ReleaseNotes, cx); + return; + } + if self.now.dirty() + || [Page::Displays, Page::Tvs, Page::Scenes] + .into_iter() + .any(|p| self.draft_changed(p)) + { + self.failure("Apply or discard your changes before updating Director.".into()); + return; + } + self.begin(format!( + "Downloading Director {}. When it’s ready, confirm the Windows prompt; Director closes and reopens after the update.", + release.version + )); + let received = Arc::new(AtomicU64::new(0)); + self.update.download = Some((received.clone(), release.size, 0)); + work(cx, move || { + let reopen = update::installed_exe(); + msg(UpdateMessage::Started( + update::download(&release, Some(&received)) + .and_then(|setup| update::launch(&setup, reopen.as_deref())), + )) + }); + tick(cx); + } + UpdateMessage::Tick => { + if let Some((received, _, shown)) = &mut self.update.download { + *shown = received.load(Ordering::Relaxed); + tick(cx); + } + } + UpdateMessage::Started(result) => { + self.update.download = None; + self.end(); + match result { + Ok(()) => { + self.status = + "Setup started. Director reopens when the update is done.".into(); + director::diagnostics::flush(); + if let Ok(window) = crate::gui::close_guard::window() { + use windows::Win32::{ + Foundation::{LPARAM, WPARAM}, + UI::WindowsAndMessaging::{PostMessageW, WM_CLOSE}, + }; + let _ = unsafe { + PostMessageW(Some(window), WM_CLOSE, WPARAM(0), LPARAM(0)) + }; + } + } + Err(e) => self.failure(e), + } + } + UpdateMessage::Dismiss => self.update.dismissed = true, + _ => {} + } + } + + /// Download progress from 0 to 1, while setup downloads. + pub(crate) fn update_progress(&self) -> Option { + self.update + .download + .as_ref() + .map(|(_, total, shown)| (*shown as f64 / (*total).max(1) as f64).min(1.0)) + } + + fn install_label(&self) -> &'static str { + if update::installed() { + "Install update" + } else { + "Download" + } + } + + /// A bar at the bottom of the Scenes page while a newer version is available, until closed. + pub(crate) fn update_banner(&self, cx: &ViewContext) -> View { + use crate::gui::ui; + let Some(release) = &self.update.available else { + return View::empty(); + }; + if self.update.dismissed { + return View::empty(); + } + Border::new() + .padding(Thickness::xy(12.0, 6.0)) + .border_thickness(Thickness::uniform(1.0)) + .border_brush(ui::card_stroke()) + .background(ui::card_fill()) + .corner_radius(ui::RADIUS_L) + .automation_name("Update available") + .content( + Grid::new() + .columns([ + GridLength::Auto, + GridLength::Star(1.0), + GridLength::Auto, + GridLength::Auto, + ]) + .column_spacing(ui::GAP_M) + .children(( + FontIcon::new() + .glyph("\u{e896}") + .vertical_alignment(VerticalAlignment::Center), + StackPanel::new() + .grid_column(1) + .vertical_alignment(VerticalAlignment::Center) + .children(( + ui::label(format!("Director {} is available", release.version)), + ui::caption(format!( + "You have {}. Setup replaces it and keeps your settings.", + update::Version::current() + )), + )), + StackPanel::new() + .grid_column(2) + .orientation(Orientation::Horizontal) + .spacing(ui::GAP_S) + .vertical_alignment(VerticalAlignment::Center) + .children(( + Button::new() + .style(ButtonStyle::Accent) + .is_enabled(self.ready()) + .on_click(cx.message(msg(UpdateMessage::Install))) + .content(self.install_label()), + Button::new() + .on_click(cx.message(msg(UpdateMessage::ReleaseNotes))) + .content("What’s new"), + )), + Button::new() + .grid_column(3) + .style(ButtonStyle::Subtle) + .automation_name("Close update notice") + .vertical_alignment(VerticalAlignment::Center) + .on_click(cx.message(msg(UpdateMessage::Dismiss))) + .content(FontIcon::new().glyph("\u{e711}")), + )), + ) + } + + /// Options → About: the automatic check, a manual check and its result. + pub(crate) fn update_settings(&self, cx: &ViewContext, editable: bool) -> View { + use crate::gui::ui; + let prefs = self.tip.pending.as_ref().or(self.tip.preferences.as_ref()); + let result: View = match &self.update.result { + _ if self.update.checking => ui::caption("Checking GitHub…"), + Some(Ok(text)) => ui::caption(text.clone()), + Some(Err(e)) => TextBlock::new() + .text(e.clone()) + .foreground(ui::critical()) + .text_wrapping(TextWrapping::Wrap) + .into(), + None => View::empty(), + }; + StackPanel::new() + .spacing(ui::GAP_S) + .children(( + ui::setting( + "Check for updates when Director opens", + "Asks GitHub for the latest release. Nothing is installed until you choose Install update.", + ToggleSwitch::new() + .automation_name("Check for updates when Director opens") + .is_on(prefs.is_some_and(|p| p.check_for_updates)) + .is_enabled(editable) + .on_toggled(cx.callback(|on| { + Message::Tip(crate::gui::tv_tip_ui::TipMessage::CheckUpdates(on)) + })), + ), + StackPanel::new() + .orientation(Orientation::Horizontal) + .spacing(ui::GAP_S) + .children(( + Button::new() + .is_enabled(!self.update.checking && !self.busy) + .on_click(cx.message(msg(UpdateMessage::Check(true)))) + .content("Check for updates"), + if self.update.available.is_some() { + Button::new() + .style(ButtonStyle::Accent) + .is_enabled(self.ready()) + .on_click(cx.message(msg(UpdateMessage::Install))) + .content(self.install_label()) + } else { + View::empty() + }, + if self.update.available.is_some() { + Button::new() + .on_click(cx.message(msg(UpdateMessage::ReleaseNotes))) + .content("What’s new") + } else { + View::empty() + }, + )), + result, + )) + } +} + +fn tick(cx: &ComponentContext) { + work(cx, || { + std::thread::sleep(std::time::Duration::from_millis(250)); + msg(UpdateMessage::Tick) + }); +} diff --git a/src/lib.rs b/src/lib.rs index 4080a70..aa36a98 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,5 +13,6 @@ pub mod preferences; pub mod scene; pub mod storage; pub mod tv; +pub mod update; #[cfg(windows)] pub mod windows_close; diff --git a/src/main.rs b/src/main.rs index ed3f201..2e3b594 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ mod gui; use display_ui::{DisplayMessage, DisplayState}; use gui::{ audio_relink_ui, close_guard, command_ui, crash_ui, display_setup_ui, display_ui, editor_flow, - fps_ui, nav_guard, now_ui, options_ui, scene_ui, status_ui, tv_tip_ui, tv_ui, + fps_ui, nav_guard, now_ui, options_ui, scene_ui, status_ui, tv_tip_ui, tv_ui, update_ui, }; #[cfg(test)] use gui::{preset_cards_preview, tv_controls_ui}; @@ -37,6 +37,7 @@ enum Message { AudioRelink(audio_relink_ui::RelinkMessage), OpenLogs, Options(options_ui::OptionsMessage), + Update(update_ui::UpdateMessage), LogsOpened(Result), GuardReady(Result<(), String>), Pane(bool), @@ -58,6 +59,7 @@ struct DirectorApp { crash: Option, notices: status_ui::StatusState, tip: tv_tip_ui::TipState, + update: update_ui::UpdateState, /// Windows audio devices, for TV audio links and relinking. outputs: Vec, inputs: Vec, @@ -226,6 +228,9 @@ impl Component for DirectorApp { .send(Message::Scene(scene_ui::SceneMessage::Load)); } work(context, tv_tip_ui::load); + // Tests and preview fixtures never contact GitHub. + #[cfg(not(test))] + work(context, update_ui::startup); let app = Self { page: if NOTIFIED_RUN.get().is_some() { Page::Options @@ -243,6 +248,7 @@ impl Component for DirectorApp { crash: director::crash::pending(), notices: status_ui::StatusState::default(), tip: tv_tip_ui::TipState::default(), + update: update_ui::UpdateState::default(), outputs: vec![], inputs: vec![], window_width: 1000.0, @@ -289,6 +295,7 @@ impl Component for DirectorApp { Message::AudioRelink(message) => self.update_audio_relink(message, context), Message::OpenLogs => self.open_logs(context), Message::Options(message) => self.update_options(message, context), + Message::Update(message) => self.update_update(message, context), Message::LogsOpened(result) => { director::diagnostics::result("app.logs.open", &result); match result { @@ -405,6 +412,13 @@ impl Component for DirectorApp { content, )]); let status = self.status_view(cx); + // The update bar sits under the status area on the Scenes start page (Options → About + // has the same controls), and steps aside while work runs (its own download shows + // progress in the status area instead). + let banner = self.page == Page::Scenes + && self.update.available.is_some() + && !self.update.dismissed + && !self.busy; let body = Border::new() .padding(Thickness::new( crate::gui::ui::PAGE_PADDING_X, @@ -414,8 +428,7 @@ impl Component for DirectorApp { )) .content( Grid::new() - .rows([GridLength::Star(1.0), GridLength::Auto]) - .row_spacing(if self.status_visible() { 16.0 } else { 0.0 }) + .rows([GridLength::Star(1.0), GridLength::Auto, GridLength::Auto]) .children(( Border::new().grid_row(0).content(content), // Only while something needs attention: an empty ScrollViewer still @@ -423,10 +436,19 @@ impl Component for DirectorApp { if self.status_visible() { Border::new() .grid_row(1) + .margin(Thickness::new(0.0, 16.0, 0.0, 0.0)) .content(ScrollViewer::new().max_height(160.0).content(status)) } else { View::empty() }, + if banner { + Border::new() + .grid_row(2) + .margin(Thickness::new(0.0, 16.0, 0.0, 0.0)) + .content(self.update_banner(cx)) + } else { + View::empty() + }, )), ); // The window's TitleBar carries the app name and the pane toggle, as in Windows 11 diff --git a/src/preferences.rs b/src/preferences.rs index 8501502..9cc7b9d 100644 --- a/src/preferences.rs +++ b/src/preferences.rs @@ -22,6 +22,12 @@ pub struct Preferences { /// their input. #[serde(default = "default_input_guard")] pub tv_input_guard_seconds: u16, + /// Ask GitHub for a newer Director version when the window opens. + #[serde(default = "default_true")] + pub check_for_updates: bool, +} +fn default_true() -> bool { + true } fn default_wait() -> u16 { 30 @@ -38,6 +44,7 @@ impl Default for Preferences { device_wait_seconds: default_wait(), hide_next_scene_tip: false, tv_input_guard_seconds: default_input_guard(), + check_for_updates: true, } } } @@ -120,6 +127,7 @@ mod tests { assert_eq!(initial.device_wait_seconds, 30); assert!(!initial.hide_next_scene_tip); assert_eq!(initial.tv_input_guard_seconds, 10); + assert!(initial.check_for_updates); assert_eq!(initial.audio_policy(), crate::audio::FailurePolicy::Revert); let hidden = Preferences { hide_tv_setup_tip: true, @@ -128,6 +136,7 @@ mod tests { device_wait_seconds: 45, hide_next_scene_tip: true, tv_input_guard_seconds: 0, + check_for_updates: false, }; save(&path, &initial, &hidden).unwrap(); assert_eq!(load(&path).unwrap(), hidden); diff --git a/src/update.rs b/src/update.rs new file mode 100644 index 0000000..5468be4 --- /dev/null +++ b/src/update.rs @@ -0,0 +1,592 @@ +//! Updates from GitHub Releases: find the latest version, download its setup, check the +//! file against the SHA-256 digest GitHub reports, and start it. Nothing runs unless the +//! window checks at startup (Options can turn that off) or the user asks. +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +const LATEST: &str = "https://api.github.com/repos/Xarishark/Director/releases/latest"; +/// Setup's fixed release asset name (see the release job in the Windows build workflow). +const ASSET: &str = "Director-x64-setup.exe"; +/// Downloads must come from this repository's releases; GitHub then redirects to its CDN. +const DOWNLOADS: &str = "https://github.com/Xarishark/Director/releases/download/"; +const PAGES: &str = "https://github.com/Xarishark/Director/releases/"; +/// Setup is a few MB; refuse anything far larger. +const MAX_SETUP: u64 = 128 * 1024 * 1024; +const MAX_JSON: u64 = 4 * 1024 * 1024; + +/// A three-part version, as Cargo.toml and the release tags use. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Version(pub u32, pub u32, pub u32); + +impl Version { + /// `0.13.0` or `v0.13.0`; anything else (pre-release suffixes included) is refused. + pub fn parse(text: &str) -> Option { + let text = text.strip_prefix('v').unwrap_or(text); + let mut parts = text.split('.').map(|p| { + if p.is_empty() || p.len() > 9 || !p.bytes().all(|b| b.is_ascii_digit()) { + None + } else { + p.parse().ok() + } + }); + let version = Self(parts.next()??, parts.next()??, parts.next()??); + parts.next().is_none().then_some(version) + } + pub fn current() -> Self { + Self::parse(env!("CARGO_PKG_VERSION")).expect("Cargo.toml has a three-part version") + } +} + +impl std::fmt::Display for Version { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}.{}.{}", self.0, self.1, self.2) + } +} + +/// The newest published release and its setup. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + pub version: Version, + /// The release page with its notes. + pub page: String, + pub download: String, + pub size: u64, + pub sha256: [u8; 32], +} + +impl Release { + pub fn is_newer(&self) -> bool { + self.version > Version::current() + } +} + +#[derive(serde::Deserialize)] +struct ReleaseJson { + tag_name: String, + html_url: String, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + #[serde(default)] + assets: Vec, +} + +#[derive(serde::Deserialize)] +struct AssetJson { + name: String, + browser_download_url: String, + size: u64, + #[serde(default)] + digest: Option, +} + +/// Read GitHub's "latest release" answer. +pub fn parse_release(json: &[u8]) -> Result { + let release: ReleaseJson = serde_json::from_slice(json) + .map_err(|_| "GitHub's release information could not be read.".to_string())?; + if release.draft || release.prerelease { + return Err("GitHub's latest release isn't a final release.".into()); + } + let version = Version::parse(&release.tag_name).ok_or_else(|| { + format!( + "The latest release has an unexpected tag ({}).", + release.tag_name + ) + })?; + if !release.html_url.starts_with(PAGES) { + return Err("The latest release points to an unexpected page.".into()); + } + let asset = release + .assets + .iter() + .find(|a| a.name == ASSET) + .ok_or_else(|| { + format!("Director {version} has no {ASSET} yet. Try again in a few minutes.") + })?; + if !asset.browser_download_url.starts_with(DOWNLOADS) { + return Err("The setup download points to an unexpected address.".into()); + } + if asset.size == 0 || asset.size > MAX_SETUP { + return Err("The setup download has an unexpected size.".into()); + } + let sha256 = asset + .digest + .as_deref() + .and_then(|d| d.strip_prefix("sha256:")) + .and_then(hex32) + .ok_or("GitHub didn't report a checksum for setup, so Director can't verify it. Download it from the release page instead.")?; + Ok(Release { + version, + page: release.html_url, + download: asset.browser_download_url.clone(), + size: asset.size, + sha256, + }) +} + +fn hex32(text: &str) -> Option<[u8; 32]> { + if text.len() != 64 { + return None; + } + let mut out = [0u8; 32]; + for (i, byte) in out.iter_mut().enumerate() { + *byte = u8::from_str_radix(text.get(i * 2..i * 2 + 2)?, 16).ok()?; + } + Some(out) +} + +/// The latest release, whether or not it's newer than this version. +#[cfg(windows)] +pub fn latest() -> Result { + let _operation = crate::diagnostics::Operation::start("update.check", None); + let body = http::get(LATEST, "application/vnd.github+json", MAX_JSON, None)?; + let release = parse_release(&body); + crate::diagnostics::event( + "update.check", + if release.is_ok() { "ok" } else { "error" }, + &match &release { + Ok(r) => r.version.to_string(), + Err(e) => e.clone(), + }, + ); + release +} + +/// A newer release, if there is one. +#[cfg(windows)] +pub fn check() -> Result, String> { + latest().map(|r| r.is_newer().then_some(r)) +} + +/// Where downloaded setups go. Older downloads are removed before the next one. +fn download_folder() -> PathBuf { + std::env::temp_dir().join("Director-update") +} + +/// Download the release's setup and check its size and SHA-256 digest. `received` counts +/// the bytes downloaded so far, for a progress bar. +#[cfg(windows)] +pub fn download(release: &Release, received: Option<&AtomicU64>) -> Result { + let _operation = crate::diagnostics::Operation::start("update.download", None); + let folder = download_folder(); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder) + .map_err(|e| format!("Could not create a folder for the download: {e}"))?; + let body = http::get( + &release.download, + "application/octet-stream", + MAX_SETUP, + received, + )?; + verify(release, &body)?; + let path = folder.join(format!("Director-{}-x64-setup.exe", release.version)); + std::fs::write(&path, &body).map_err(|e| format!("Could not save the download: {e}"))?; + crate::diagnostics::event("update.download", "ok", &release.version.to_string()); + Ok(path) +} + +fn verify(release: &Release, body: &[u8]) -> Result<(), String> { + if body.len() as u64 != release.size { + return Err("The download was incomplete. Try again.".into()); + } + if Sha256::digest(body).as_slice() != release.sha256 { + return Err("The download doesn't match GitHub's checksum, so Director didn't run it. Try again, or download setup from the release page.".into()); + } + Ok(()) +} + +/// Whether this copy runs from the installed location, so setup replaces it. +#[cfg(windows)] +pub fn installed() -> bool { + static INSTALLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *INSTALLED.get_or_init(runs_from_program_files) +} + +#[cfg(windows)] +fn runs_from_program_files() -> bool { + let Some(expected) = installed_exe() else { + return false; + }; + std::env::current_exe().is_ok_and(|exe| { + exe.to_string_lossy() + .eq_ignore_ascii_case(&expected.to_string_lossy()) + }) +} + +/// Where setup installs director.exe. +#[cfg(windows)] +pub fn installed_exe() -> Option { + let programs = std::env::var_os("ProgramW6432").or_else(|| std::env::var_os("ProgramFiles"))?; + Some(Path::new(&programs).join("Director").join("director.exe")) +} + +/// Start the downloaded setup with only its progress window (`/passive`): no pages to click +/// through, just the Windows permission prompt. It keeps the desktop shortcut as it is now. +/// A hidden `cmd` waits for setup and, when `reopen` is given and setup succeeded, starts +/// that program again as the normal user. A cancelled prompt, a failure or a pending restart +/// leaves it closed. +#[cfg(windows)] +pub fn launch(setup: &Path, reopen: Option<&Path>) -> Result<(), String> { + use std::os::windows::process::CommandExt; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let line = waiter_command(setup, desktop_shortcut(), reopen)?; + let system = std::env::var_os("SystemRoot") + .map(PathBuf::from) + .ok_or("Windows didn't report its folder, so setup couldn't start.")?; + std::process::Command::new(system.join("System32").join("cmd.exe")) + .raw_arg(&line) + .creation_flags(CREATE_NO_WINDOW) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| { + format!( + "Windows couldn't start setup ({e}). It's saved at {}.", + setup.display() + ) + })?; + crate::diagnostics::event("update.setup", "started", &setup.to_string_lossy()); + Ok(()) +} + +/// The `cmd.exe` arguments that run setup and, if it succeeds, reopen Director. `start +/// /wait` sets ERRORLEVEL to setup's exit code. +fn waiter_command(setup: &Path, shortcut: bool, reopen: Option<&Path>) -> Result { + let quoted = |path: &Path| { + let text = path.to_string_lossy(); + if text.is_empty() || text.contains(['"', '%', '\r', '\n']) { + Err(format!("Setup can't start from {}.", path.display())) + } else { + Ok(format!("\"{text}\"")) + } + }; + let mut line = format!( + "start \"\" /wait {} /passive DesktopShortcut={}", + quoted(setup)?, + u8::from(shortcut) + ); + if let Some(app) = reopen { + line.push_str(&format!( + " & if not errorlevel 1 start \"\" {}", + quoted(app)? + )); + } + // /s: cmd removes only the outer quotes and runs the rest as written. + Ok(format!("/d /s /c \"{line}\"")) +} + +/// The installer records the desktop shortcut choice in HKLM\Software\Director\Installer. +#[cfg(windows)] +fn desktop_shortcut() -> bool { + use windows::{ + Win32::System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD, RegGetValueW}, + core::w, + }; + let mut value = 0u32; + let mut size = std::mem::size_of::() as u32; + let result = unsafe { + RegGetValueW( + HKEY_LOCAL_MACHINE, + w!("Software\\Director\\Installer"), + w!("DesktopShortcut"), + RRF_RT_REG_DWORD, + None, + Some((&mut value as *mut u32).cast()), + Some(&mut size), + ) + }; + result.is_ok() && value == 1 +} + +#[cfg(windows)] +mod http { + use std::{ffi::c_void, ptr}; + use windows::{ + Win32::Networking::WinHttp::*, + core::{PCWSTR, w}, + }; + + struct Handle(*mut c_void); + impl Handle { + fn new(raw: *mut c_void) -> Result { + if raw.is_null() { + Err(offline(windows::core::Error::from_thread())) + } else { + Ok(Self(raw)) + } + } + } + impl Drop for Handle { + fn drop(&mut self) { + let _ = unsafe { WinHttpCloseHandle(self.0) }; + } + } + fn offline(error: windows::core::Error) -> String { + format!( + "Couldn't reach GitHub. Check your internet connection and try again. ({})", + error.code() + ) + } + + /// An HTTPS GET that follows redirects (never to plain HTTP) and reads at most `limit` + /// bytes. Uses the system's proxy settings. + pub(super) fn get( + url: &str, + accept: &str, + limit: u64, + received: Option<&super::AtomicU64>, + ) -> Result, String> { + let rest = url + .strip_prefix("https://") + .ok_or("Updates only use HTTPS.")?; + let (host, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); + let path = if path.is_empty() { "/" } else { path }; + let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::>(); + let agent = wide(concat!("Director/", env!("CARGO_PKG_VERSION"))); + let session = Handle::new(unsafe { + WinHttpOpen( + PCWSTR(agent.as_ptr()), + WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + PCWSTR::null(), + PCWSTR::null(), + 0, + ) + })?; + unsafe { WinHttpSetTimeouts(session.0, 10_000, 10_000, 15_000, 30_000) } + .map_err(offline)?; + let host = wide(host); + let connection = Handle::new(unsafe { + WinHttpConnect( + session.0, + PCWSTR(host.as_ptr()), + INTERNET_DEFAULT_HTTPS_PORT, + 0, + ) + })?; + let path = wide(path); + let request = Handle::new(unsafe { + WinHttpOpenRequest( + connection.0, + w!("GET"), + PCWSTR(path.as_ptr()), + PCWSTR::null(), + PCWSTR::null(), + ptr::null(), + WINHTTP_FLAG_SECURE, + ) + })?; + let headers = wide(&format!( + "Accept: {accept}\r\nX-GitHub-Api-Version: 2022-11-28\r\n" + )); + unsafe { + WinHttpSendRequest( + request.0, + Some(&headers[..headers.len() - 1]), + None, + 0, + 0, + 0, + ) + } + .map_err(offline)?; + unsafe { WinHttpReceiveResponse(request.0, ptr::null_mut()) }.map_err(offline)?; + let mut status = 0u32; + let mut size = std::mem::size_of::() as u32; + unsafe { + WinHttpQueryHeaders( + request.0, + WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, + PCWSTR::null(), + Some((&mut status as *mut u32).cast()), + &mut size, + ptr::null_mut(), + ) + } + .map_err(offline)?; + match status { + 200 => {} + 403 | 429 => { + return Err( + "GitHub is limiting update checks from this network. Try again later.".into(), + ); + } + 404 => return Err("No Director release was found on GitHub.".into()), + _ => { + return Err(format!( + "GitHub answered with an error ({status}). Try again later." + )); + } + } + let mut body = Vec::new(); + let mut chunk = vec![0u8; 64 * 1024]; + loop { + let mut read = 0u32; + unsafe { + WinHttpReadData( + request.0, + chunk.as_mut_ptr().cast(), + chunk.len() as u32, + &mut read, + ) + } + .map_err(offline)?; + if read == 0 { + return Ok(body); + } + body.extend_from_slice(&chunk[..read as usize]); + if let Some(received) = received { + received.store(body.len() as u64, super::Ordering::Relaxed); + } + if body.len() as u64 > limit { + return Err("GitHub sent more data than expected.".into()); + } + } + } +} + +/// `director update [--install]`. +#[cfg(windows)] +pub fn cli(args: &[String]) -> Result { + let install = match args { + [] => false, + [flag] if flag == "--install" => true, + _ => return Err("Use director update or director update --install.".into()), + }; + let current = Version::current(); + let Some(release) = check()? else { + println!("Director {current} is up to date."); + return Ok(0); + }; + println!( + "Director {} is available (you have {current}).", + release.version + ); + println!("Release notes: {}", release.page); + if !install { + println!("Run director update --install to download and start setup."); + return Ok(0); + } + println!("Downloading setup…"); + let setup = download(&release, None)?; + println!("Checksum verified. Starting setup; confirm the Windows prompt to install."); + launch(&setup, None)?; + Ok(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn json(tag: &str, digest: Option<&str>) -> Vec { + serde_json::json!({ + "tag_name": tag, + "html_url": format!("https://github.com/Xarishark/Director/releases/tag/{tag}"), + "draft": false, + "prerelease": false, + "assets": [ + {"name": "notes.txt", "browser_download_url": "https://example.com/x", "size": 3}, + { + "name": ASSET, + "browser_download_url": format!("https://github.com/Xarishark/Director/releases/download/{tag}/{ASSET}"), + "size": 3, + "digest": digest, + } + ] + }) + .to_string() + .into_bytes() + } + // SHA-256 of "abc". + const ABC: &str = "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + /// Contacts GitHub and downloads the latest setup; never starts it. + #[test] + #[ignore = "network"] + #[cfg(windows)] + fn downloads_and_verifies_the_latest_setup() { + let release = latest().unwrap(); + let path = download(&release, None).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().len(), release.size); + std::fs::remove_dir_all(download_folder()).unwrap(); + } + + #[test] + fn setup_waits_then_reopens_only_after_success() { + let line = waiter_command( + Path::new(r"C:\Temp\Director-update\Director-1.0.0-x64-setup.exe"), + true, + Some(Path::new(r"C:\Program Files\Director\director.exe")), + ) + .unwrap(); + assert_eq!( + line, + r#"/d /s /c "start "" /wait "C:\Temp\Director-update\Director-1.0.0-x64-setup.exe" /passive DesktopShortcut=1 & if not errorlevel 1 start "" "C:\Program Files\Director\director.exe"""# + ); + let cli = waiter_command(Path::new(r"C:\a b\s.exe"), false, None).unwrap(); + assert_eq!( + cli, + r#"/d /s /c "start "" /wait "C:\a b\s.exe" /passive DesktopShortcut=0""# + ); + assert!(waiter_command(Path::new(r"C:\%TEMP%\s.exe"), true, None).is_err()); + } + + #[test] + fn versions_parse_and_order() { + assert_eq!(Version::parse("v0.13.0"), Some(Version(0, 13, 0))); + assert_eq!(Version::parse("1.2.10"), Some(Version(1, 2, 10))); + for bad in [ + "", + "1.2", + "1.2.3.4", + "1.2.x", + "v1.2.3-beta", + "1..2", + "+1.2.3", + ] { + assert_eq!(Version::parse(bad), None, "{bad}"); + } + assert!(Version(0, 13, 1) > Version(0, 13, 0)); + assert!(Version(0, 14, 0) > Version(0, 13, 9)); + assert!(Version(1, 0, 0) > Version(0, 99, 99)); + assert_eq!(Version::current().to_string(), env!("CARGO_PKG_VERSION")); + } + + #[test] + fn reads_the_setup_asset_and_checks_the_download() { + let release = parse_release(&json("v99.0.0", Some(ABC))).unwrap(); + assert_eq!(release.version, Version(99, 0, 0)); + assert!(release.is_newer()); + assert!( + release + .download + .ends_with("/v99.0.0/Director-x64-setup.exe") + ); + assert!(verify(&release, b"abc").is_ok()); + assert!(verify(&release, b"abd").is_err()); + assert!(verify(&release, b"abcd").is_err()); + let old = parse_release(&json("v0.0.1", Some(ABC))).unwrap(); + assert!(!old.is_newer()); + } + + #[test] + fn refuses_releases_it_cannot_verify() { + assert!(parse_release(&json("v99.0.0", None)).is_err()); + assert!(parse_release(&json("v99.0.0", Some("sha1:abc"))).is_err()); + assert!(parse_release(&json("nightly", Some(ABC))).is_err()); + assert!(parse_release(b"not json").is_err()); + let moved = String::from_utf8(json("v99.0.0", Some(ABC))) + .unwrap() + .replace( + "https://github.com/Xarishark/Director/releases/download", + "https://example.com", + ); + assert!(parse_release(moved.as_bytes()).is_err()); + let pre = String::from_utf8(json("v99.0.0", Some(ABC))) + .unwrap() + .replace("\"prerelease\":false", "\"prerelease\":true"); + assert!(parse_release(pre.as_bytes()).is_err()); + } +}