pull/2624/head
Krzysztof Andrelczyk 5 months ago
parent 8aa131a11d
commit 6ae53cfeae

@ -34,6 +34,31 @@ use crate::{
const UPDATER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),); const UPDATER_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
#[derive(Clone)]
pub enum Installer {
AppImage,
Deb,
Rpm,
App,
Msi,
Nsis,
}
impl Installer{
fn suffix(self) -> &'static str {
match self {
Self::AppImage => "appimage",
Self::Deb => "deb",
Self::Rpm => "rpm",
Self::App => "app",
Self::Msi => "msi",
Self::Nsis => "nsis",
}
}
}
#[derive(Debug, Deserialize, Serialize, Clone)] #[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ReleaseManifestPlatform { pub struct ReleaseManifestPlatform {
/// Download URL for the platform /// Download URL for the platform
@ -68,28 +93,32 @@ pub struct RemoteRelease {
impl RemoteRelease { impl RemoteRelease {
/// The release's download URL for the given target. /// The release's download URL for the given target.
pub fn download_url(&self, target: &str, fallback_target: &Option<String>) -> Result<&Url> { pub fn download_url(&self, target: &str, installer: Option<Installer>) -> Result<&Url> {
let fallback_target = installer.map(|installer| format!("{target}-{}", installer.suffix()));
match self.data { match self.data {
RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.url), RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.url),
RemoteReleaseInner::Static { ref platforms } => platforms RemoteReleaseInner::Static { ref platforms } => platforms
.get(target) .get(target)
.map_or_else( .map_or_else(
|| match fallback_target { || match fallback_target {
Some(fallback) => platforms.get(fallback).map_or(Err(Error::TargetsNotFound(target.to_string(), fallback.to_string())), |p| Ok(&p.url)), Some(fallback) => platforms.get(&fallback).map_or(Err(Error::TargetsNotFound(target.to_string(), fallback)), |p| Ok(&p.url)),
None => Err(Error::TargetNotFound(target.to_string())) None => Err(Error::TargetNotFound(target.to_string()))
}, |p| { Ok(&p.url) }) }, |p| { Ok(&p.url) })
} }
} }
/// The release's signature for the given target. /// The release's signature for the given target.
pub fn signature(&self, target: &str, fallback_target: &Option<String>) -> Result<&String> { pub fn signature(&self, target: &str, installer: Option<Installer>) -> Result<&String> {
let fallback_target = installer.map(|installer| format!("{target}-{}", installer.suffix()));
match self.data { match self.data {
RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.signature), RemoteReleaseInner::Dynamic(ref platform) => Ok(&platform.signature),
RemoteReleaseInner::Static { ref platforms } => platforms RemoteReleaseInner::Static { ref platforms } => platforms
.get(target) .get(target)
.map_or_else( .map_or_else(
|| match fallback_target { || match fallback_target {
Some(fallback) => platforms.get(fallback).map_or(Err(Error::TargetsNotFound(target.to_string(), fallback.to_string())), |p| Ok(&p.signature)), Some(fallback) => platforms.get(&fallback).map_or(Err(Error::TargetsNotFound(target.to_string(), fallback)), |p| Ok(&p.signature)),
None => Err(Error::TargetNotFound(target.to_string())) None => Err(Error::TargetNotFound(target.to_string()))
}, |p| { Ok(&p.signature) }) }, |p| { Ok(&p.signature) })
} }
@ -246,16 +275,12 @@ impl UpdaterBuilder {
}; };
let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?; let arch = get_updater_arch().ok_or(Error::UnsupportedArch)?;
let (target, json_target, fallback_target) = if let Some(target) = self.target { let (target, json_target) = if let Some(target) = self.target {
(target.clone(), target, None) (target.clone(), target )
} else { } else {
let target = get_updater_target().ok_or(Error::UnsupportedOs)?; let target = get_updater_target().ok_or(Error::UnsupportedOs)?;
let installer = get_updater_installer()?;
let json_target = format!("{target}-{arch}"); let json_target = format!("{target}-{arch}");
match installer { (target.to_owned(), json_target)
Some(installer) => (target.to_owned(), format!("{json_target}-{installer}"), Some(json_target)),
None => (target.to_owned(), json_target, None)
}
}; };
let executable_path = self.executable_path.clone().unwrap_or(current_exe()?); let executable_path = self.executable_path.clone().unwrap_or(current_exe()?);
@ -280,7 +305,6 @@ impl UpdaterBuilder {
arch, arch,
target, target,
json_target, json_target,
fallback_target,
headers: self.headers, headers: self.headers,
extract_path, extract_path,
on_before_exit: self.on_before_exit, on_before_exit: self.on_before_exit,
@ -313,8 +337,6 @@ pub struct Updater {
target: String, target: String,
// The value we search if the updater server returns a JSON with the `platforms` object // The value we search if the updater server returns a JSON with the `platforms` object
json_target: String, json_target: String,
// If target doesn't exist in the JSON check for this one
fallback_target: Option<String>,
headers: HeaderMap, headers: HeaderMap,
extract_path: PathBuf, extract_path: PathBuf,
on_before_exit: Option<OnBeforeExit>, on_before_exit: Option<OnBeforeExit>,
@ -325,6 +347,7 @@ pub struct Updater {
} }
impl Updater { impl Updater {
pub async fn check(&self) -> Result<Option<Update>> { pub async fn check(&self) -> Result<Option<Update>> {
// we want JSON only // we want JSON only
let mut headers = self.headers.clone(); let mut headers = self.headers.clone();
@ -421,6 +444,8 @@ impl Updater {
None => release.version > self.current_version, None => release.version > self.current_version,
}; };
let installer = get_updater_installer(&self.extract_path)?;
let update = if should_update { let update = if should_update {
Some(Update { Some(Update {
config: self.config.clone(), config: self.config.clone(),
@ -431,9 +456,10 @@ impl Updater {
extract_path: self.extract_path.clone(), extract_path: self.extract_path.clone(),
version: release.version.to_string(), version: release.version.to_string(),
date: release.pub_date, date: release.pub_date,
download_url: release.download_url(&self.json_target, &self.fallback_target)?.to_owned(), download_url: release.download_url(&self.json_target, installer.clone())?.to_owned(),
body: release.notes.clone(), body: release.notes.clone(),
signature: release.signature(&self.json_target, &self.fallback_target)?.to_owned(), signature: release.signature(&self.json_target, installer.clone())?.to_owned(),
installer,
raw_json: raw_json.unwrap(), raw_json: raw_json.unwrap(),
timeout: self.timeout, timeout: self.timeout,
proxy: self.proxy.clone(), proxy: self.proxy.clone(),
@ -464,6 +490,8 @@ pub struct Update {
pub date: Option<OffsetDateTime>, pub date: Option<OffsetDateTime>,
/// Target /// Target
pub target: String, pub target: String,
/// Current installer
pub installer: Option<Installer>,
/// Download URL announced /// Download URL announced
pub download_url: Url, pub download_url: Url,
/// Signature announced /// Signature announced
@ -791,11 +819,9 @@ impl Update {
/// └── ... /// └── ...
/// ///
fn install_inner(&self, bytes: &[u8]) -> Result<()> { fn install_inner(&self, bytes: &[u8]) -> Result<()> {
if self.is_deb_package() { match self.installer {
self.install_deb(bytes) Some(Installer::Deb) => self.install_deb(bytes),
} else { _ =>self.install_appimage(bytes)
// Handle AppImage or other formats
self.install_appimage(bytes)
} }
} }
@ -870,38 +896,6 @@ impl Update {
Err(Error::TempDirNotOnSameMountPoint) Err(Error::TempDirNotOnSameMountPoint)
} }
fn is_deb_package(&self) -> bool {
// First check if we're in a typical Debian installation path
let in_system_path = self
.extract_path
.to_str()
.map(|p| p.starts_with("/usr"))
.unwrap_or(false);
if !in_system_path {
return false;
}
// Then verify it's actually a Debian-based system by checking for dpkg
let dpkg_exists = std::path::Path::new("/var/lib/dpkg").exists();
let apt_exists = std::path::Path::new("/etc/apt").exists();
// Additional check for the package in dpkg database
let package_in_dpkg = if let Ok(output) = std::process::Command::new("dpkg")
.args(["-S", &self.extract_path.to_string_lossy()])
.output()
{
output.status.success()
} else {
false
};
// Consider it a deb package only if:
// 1. We're in a system path AND
// 2. We have Debian package management tools AND
// 3. The binary is tracked by dpkg
dpkg_exists && apt_exists && package_in_dpkg
}
fn install_deb(&self, bytes: &[u8]) -> Result<()> { fn install_deb(&self, bytes: &[u8]) -> Result<()> {
// First verify the bytes are actually a .deb package // First verify the bytes are actually a .deb package
@ -1125,11 +1119,49 @@ pub(crate) fn get_updater_arch() -> Option<&'static str> {
} }
} }
pub(crate) fn get_updater_installer() -> Result<Option<&'static str>> { fn is_deb_package(extract_path: &PathBuf) -> bool {
// First check if we're in a typical Debian installation path
let in_system_path = extract_path
.to_str()
.map(|p| p.starts_with("/usr"))
.unwrap_or(false);
if !in_system_path {
return false;
}
// Then verify it's actually a Debian-based system by checking for dpkg
let dpkg_exists = std::path::Path::new("/var/lib/dpkg").exists();
let apt_exists = std::path::Path::new("/etc/apt").exists();
// Additional check for the package in dpkg database
let package_in_dpkg = if let Ok(output) = std::process::Command::new("dpkg")
.args(["-S", &extract_path.to_string_lossy()])
.output()
{
output.status.success()
} else {
false
};
// Consider it a deb package only if:
// 1. We're in a system path AND
// 2. We have Debian package management tools AND
// 3. The binary is tracked by dpkg
dpkg_exists && apt_exists && package_in_dpkg
}
pub(crate) fn get_updater_installer(extract_path: &PathBuf) -> Result<Option<Installer>> {
if cfg!(target_os = "linux") { if cfg!(target_os = "linux") {
Ok(Some("deb")) if std::env::var_os("APPIMAGE").is_some() {
Ok(Some(Installer::AppImage))
} else if is_deb_package(extract_path) {
Ok(Some(Installer::Deb))
} else {
Err(Error::UnknownInstaller)
}
} else if cfg!(target_os = "windows") { } else if cfg!(target_os = "windows") {
Ok(Some("wix")) Ok(Some(Installer::Msi))
} else if cfg!(target_os = "macos") { } else if cfg!(target_os = "macos") {
Ok(None) Ok(None)
} else { } else {

@ -71,7 +71,6 @@ fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, targets: Vec<Bun
#[cfg(windows)] #[cfg(windows)]
command.args([target.name()]); command.args([target.name()]);
} }
let status = command let status = command
.status() .status()
.expect("failed to run Tauri CLI to bundle app"); .expect("failed to run Tauri CLI to bundle app");
@ -111,72 +110,74 @@ impl BundleTarget {
#[cfg(any(target_os = "macos", target_os = "ios"))] #[cfg(any(target_os = "macos", target_os = "ios"))]
return vec![Self::App]; return vec![Self::App];
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
return vec![Self::AppImage, Self::Deb, Self::Rpm]; return vec![Self::AppImage];
#[cfg(windows)] #[cfg(windows)]
return vec![Self::Nsis]; return vec![Self::Nsis];
} }
} }
fn insert_plaforms( fn target_to_platforms(
bundle_target: BundleTarget, update_platform: Option<String>,
platforms: &mut HashMap<String, PlatformUpdate>,
target: String,
signature: String, signature: String,
) { ) -> HashMap<String, PlatformUpdate> {
match bundle_target { let mut platforms = HashMap::new();
// Should use deb, no fallback if let Some(platform) = update_platform {
BundleTarget::Deb => { platforms.insert(
platforms.insert( platform,
format!("{target}-deb"), PlatformUpdate {
PlatformUpdate { signature,
signature, url: "http://localhost:3007/download",
url: "http://localhost:3007/download", with_elevated_task: false,
with_elevated_task: false, },
}, );
);
}
// Should fail
BundleTarget::Rpm => {}
// AppImage should use fallback
_ => {
platforms.insert(
target,
PlatformUpdate {
signature,
url: "http://localhost:3007/download",
with_elevated_task: false,
},
);
}
} }
platforms
} }
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> { fn test_cases(
root_dir: &Path,
version: &str,
target: String,
) -> Vec<(BundleTarget, PathBuf, Option<String>, Vec<i32>)> {
vec![ vec![
// update using fallback
( (
BundleTarget::AppImage, BundleTarget::AppImage,
root_dir.join(format!( root_dir.join(format!(
"target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage" "target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)), )),
Some(target.clone()),
vec![UPDATED_EXIT_CODE, UP_TO_DATE_EXIT_CODE],
), ),
// update using full name
( (
BundleTarget::Deb, BundleTarget::AppImage,
root_dir.join(format!( root_dir.join(format!(
"target/debug/bundle/deb/app-updater_{version}_amd64.deb" "target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)), )),
Some(format!("{target}-{}", BundleTarget::AppImage.name())),
vec![UPDATED_EXIT_CODE, UP_TO_DATE_EXIT_CODE],
), ),
// no update
( (
BundleTarget::Rpm, BundleTarget::AppImage,
root_dir.join(format!( root_dir.join(format!(
"target/debug/bundle/rpm/app-updater_{version}_amd64.rpm" "target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)), )),
None,
vec![ERROR_EXIT_CODE],
), ),
] ]
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> { fn bundle_paths(
root_dir: &Path,
_version: &str,
v1compatible: bool,
) -> Vec<(BundleTarget, PathBuf)> {
vec![( vec![(
BundleTarget::App, BundleTarget::App,
root_dir.join("target/debug/bundle/macos/app-updater.app"), root_dir.join("target/debug/bundle/macos/app-updater.app"),
@ -184,7 +185,11 @@ fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)>
} }
#[cfg(target_os = "ios")] #[cfg(target_os = "ios")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> { fn bundle_paths(
root_dir: &Path,
_version: &str,
v1compatible: bool,
) -> Vec<(BundleTarget, PathBuf)> {
vec![( vec![(
BundleTarget::App, BundleTarget::App,
root_dir.join("target/debug/bundle/ios/app-updater.ipa"), root_dir.join("target/debug/bundle/ios/app-updater.ipa"),
@ -192,12 +197,16 @@ fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)>
} }
#[cfg(target_os = "android")] #[cfg(target_os = "android")]
fn bundle_path(root_dir: &Path, _version: &str) -> PathBuf { fn bundle_path(root_dir: &Path, _version: &str, v1compatible: bool) -> PathBuf {
root_dir.join("target/debug/bundle/android/app-updater.apk") root_dir.join("target/debug/bundle/android/app-updater.apk")
} }
#[cfg(windows)] #[cfg(windows)]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> { fn bundle_paths(
root_dir: &Path,
version: &str,
v1compatible: bool,
) -> Vec<(BundleTarget, PathBuf)> {
vec![ vec![
( (
BundleTarget::Nsis, BundleTarget::Nsis,
@ -240,8 +249,6 @@ fn update_app() {
Updater::String(V1Compatible::V1Compatible) Updater::String(V1Compatible::V1Compatible)
); );
// bundle app update
build_app(&manifest_dir, &config, true, BundleTarget::get_targets());
let updater_zip_ext = if v1_compatible { let updater_zip_ext = if v1_compatible {
if cfg!(windows) { if cfg!(windows) {
@ -255,7 +262,13 @@ fn update_app() {
None None
}; };
for (bundle_target, out_bundle_path) in bundle_paths(&root_dir, "1.0.0") { for (bundle_target, out_bundle_path, update_platform, status_checks) in
test_cases(&root_dir, "1.0.0", target.clone())
{
// bundle app update
config.version = "1.0.0";
build_app(&manifest_dir, &config, true, BundleTarget::get_targets());
let bundle_updater_ext = if v1_compatible { let bundle_updater_ext = if v1_compatible {
out_bundle_path out_bundle_path
.extension() .extension()
@ -288,8 +301,6 @@ fn update_app() {
)); ));
std::fs::rename(&out_updater_path, &updater_path).expect("failed to rename bundle"); std::fs::rename(&out_updater_path, &updater_path).expect("failed to rename bundle");
let target = target.clone();
// start the updater server // start the updater server
let server = Arc::new( let server = Arc::new(
tiny_http::Server::http("localhost:3007").expect("failed to start updater server"), tiny_http::Server::http("localhost:3007").expect("failed to start updater server"),
@ -300,14 +311,8 @@ fn update_app() {
for request in server_.incoming_requests() { for request in server_.incoming_requests() {
match request.url() { match request.url() {
"/" => { "/" => {
let mut platforms = HashMap::new(); let platforms =
target_to_platforms(update_platform.clone(), signature.clone());
insert_plaforms(
bundle_target,
&mut platforms,
target.clone(),
signature.clone(),
);
let body = serde_json::to_vec(&Update { let body = serde_json::to_vec(&Update {
version: "1.0.0", version: "1.0.0",
@ -347,21 +352,12 @@ fn update_app() {
// bundle initial app version // bundle initial app version
build_app(&manifest_dir, &config, false, vec![bundle_target]); build_app(&manifest_dir, &config, false, vec![bundle_target]);
let status_checks = if matches!(bundle_target, BundleTarget::Msi) {
// for msi we can't really check if the app was updated, because we can't change the install path
vec![UPDATED_EXIT_CODE]
} else if matches!(bundle_target, BundleTarget::Rpm) {
vec![ERROR_EXIT_CODE]
} else {
vec![UPDATED_EXIT_CODE, UP_TO_DATE_EXIT_CODE]
};
for expected_exit_code in status_checks { for expected_exit_code in status_checks {
let mut binary_cmd = if cfg!(windows) { let mut binary_cmd = if cfg!(windows) {
Command::new(root_dir.join("target/debug/app-updater.exe")) Command::new(root_dir.join("target/debug/app-updater.exe"))
} else if cfg!(target_os = "macos") { } else if cfg!(target_os = "macos") {
Command::new( Command::new(
bundle_paths(&root_dir, "0.1.0") test_cases(&root_dir, "0.1.0", target.clone())
.first() .first()
.unwrap() .unwrap()
.1 .1
@ -369,11 +365,22 @@ fn update_app() {
) )
} else if std::env::var("CI").map(|v| v == "true").unwrap_or_default() { } else if std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let mut c = Command::new("xvfb-run"); let mut c = Command::new("xvfb-run");
c.arg("--auto-servernum") c.arg("--auto-servernum").arg(
.arg(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1); &test_cases(&root_dir, "0.1.0", target.clone())
.first()
.unwrap()
.1,
);
c c
} else if matches!(bundle_target, BundleTarget::AppImage) {
Command::new(
&test_cases(&root_dir, "0.1.0", target.clone())
.first()
.unwrap()
.1,
)
} else { } else {
Command::new(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1) Command::new(root_dir.join("target/debug/app-updater"))
}; };
binary_cmd.env("TARGET", bundle_target.name()); binary_cmd.env("TARGET", bundle_target.name());
@ -383,7 +390,7 @@ fn update_app() {
if code != expected_exit_code { if code != expected_exit_code {
panic!( panic!(
"failed to run app, expected exit code {expected_exit_code}, got {code}" "failed to run app bundled as {}, expected exit code {expected_exit_code}, got {code}", bundle_target.name()
); );
} }
#[cfg(windows)] #[cfg(windows)]

Loading…
Cancel
Save