diff --git a/Cargo.lock b/Cargo.lock index 19d095c50..4b50fdbb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5003,6 +5003,7 @@ dependencies = [ name = "ide-tools" version = "0.1.54" dependencies = [ + "blake3", "flate2", "hex", "http", diff --git a/crates/ide-ssh/src/session.rs b/crates/ide-ssh/src/session.rs index cba0f00ac..82275479e 100644 --- a/crates/ide-ssh/src/session.rs +++ b/crates/ide-ssh/src/session.rs @@ -340,7 +340,16 @@ impl Session { use std::io::Write as _; let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); gz.write_all(data)?; - let packed = gz.finish()?; + self.put_gzip_with_progress(remote, &gz.finish()?, progress).await + } + + /// Sends an already compressed gzip stream; the remote file contains the decoded bytes. + pub async fn put_gzip_with_progress( + &self, + remote: &str, + packed: &[u8], + progress: &(dyn Fn(f64) + Send + Sync), + ) -> IdeResult<()> { let q = crate::shell::quote; let dir = crate::sftp::parent(remote).unwrap_or("/"); let command = format!("mkdir -p {} && gzip -dc > {}", q(dir), q(remote)); diff --git a/crates/ide-tools/Cargo.toml b/crates/ide-tools/Cargo.toml index a5e83bc31..67eacd2cc 100644 --- a/crates/ide-tools/Cargo.toml +++ b/crates/ide-tools/Cargo.toml @@ -16,6 +16,7 @@ http = "1" hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] } tracing.workspace = true which = "8" +blake3.workspace = true flate2 = "1" tar = "0.4" zip.workspace = true diff --git a/crates/ide-tools/src/server.rs b/crates/ide-tools/src/server.rs index 6c4518c92..7f342d1e2 100644 --- a/crates/ide-tools/src/server.rs +++ b/crates/ide-tools/src/server.rs @@ -5,6 +5,7 @@ use crate::process::Http; use crate::{InstallEvent, fetch_verified, sources}; use ide_core::CancellationToken; use ide_core::{IdeError, IdeResult}; +use std::io::Read; use std::path::{Path, PathBuf}; const RELEASES: &str = "https://github.com/l0ng-ai/openidea/releases/download"; @@ -65,18 +66,42 @@ pub fn fetch( let unpacked = staging.join("openidea-server"); let mut gz = flate2::read::GzDecoder::new(std::fs::File::open(&archive)?); std::io::copy(&mut gz, &mut std::fs::File::create(&unpacked)?)?; + drop(gz); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&unpacked, std::fs::Permissions::from_mode(0o755))?; } std::fs::rename(&unpacked, &dest)?; + // The executable is the cache entry; keeping the archive only optimizes SSH uploads. + let _ = std::fs::rename(archive, dest.with_extension("gz")); Ok(dest.clone()) })(); let _ = std::fs::remove_dir_all(&staging); result } +/// The cached release gzip, if it unpacks to the selected server binary. +pub fn matching_archive(binary: &Path, expected: blake3::Hash) -> Option> { + let archive = binary.with_extension("gz"); + let binary_size = binary.metadata().ok()?.len(); + let meta = archive.metadata().ok()?; + if !meta.is_file() || meta.len() >= binary_size { + return None; + } + let mut packed = Vec::with_capacity(meta.len().try_into().ok()?); + std::fs::File::open(archive).ok()?.take(binary_size).read_to_end(&mut packed).ok()?; + if packed.len() as u64 >= binary_size { + return None; + } + // The receiver decodes every gzip member. Read one byte past the expected size + // so a correct-sized stream still has its trailer and any remaining input checked. + let gzip = flate2::read::MultiGzDecoder::new(packed.as_slice()); + let mut hash = blake3::Hasher::new(); + let decoded_size = std::io::copy(&mut gzip.take(binary_size.checked_add(1)?), &mut hash).ok()?; + (decoded_size == binary_size && hash.finalize() == expected).then_some(packed) +} + fn tempfile_dir(parent: &Path) -> IdeResult { // Unique per call: two windows of this process may download at once. static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -98,6 +123,38 @@ mod tests { assert_eq!(p, Path::new("/data/server/1.2.3/linux-aarch64/openidea-server")); } + #[test] + fn cached_archive_must_decode_to_the_selected_build() { + use std::io::Write as _; + let pack = |bytes: &[u8]| { + let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best()); + gzip.write_all(bytes).unwrap(); + gzip.finish().unwrap() + }; + let tmp = tempfile::tempdir().unwrap(); + let binary = tmp.path().join("openidea-server"); + let archive = binary.with_extension("gz"); + let payload = [b'a'; 4096]; + let expected = blake3::hash(&payload); + std::fs::write(&binary, payload).unwrap(); + assert!(matching_archive(&binary, expected).is_none()); + + let gzip = pack(&payload); + std::fs::write(&archive, &gzip).unwrap(); + assert_eq!(matching_archive(&binary, expected), Some(gzip.clone())); + + let extra_member = pack(b"extra output"); + for invalid in [ + pack(&[b'b'; 4096]), + gzip[..gzip.len() - 1].to_vec(), + [gzip.as_slice(), &extra_member].concat(), + [gzip.as_slice(), b"trailing junk"].concat(), + ] { + std::fs::write(&archive, &invalid).unwrap(); + assert!(matching_archive(&binary, expected).is_none()); + } + } + #[test] fn unsupported_hosts_are_refused_without_downloading() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src-tauri/src/remote_container.rs b/src-tauri/src/remote_container.rs index 0cbfcb6cf..1d58134ac 100644 --- a/src-tauri/src/remote_container.rs +++ b/src-tauri/src/remote_container.rs @@ -134,7 +134,7 @@ async fn ensure_server( } let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? { LocalServer::Installed(bin) => return Ok(bin), - LocalServer::Binary(local, build) => (local, build), + LocalServer::Binary { path, build, .. } => (path, build), }; if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) { return Ok(bin.clone()); diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index bfcfbbbe3..91e1de0bc 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -521,8 +521,8 @@ fn server_path(path: &str) -> bool { /// What [`local_server`] settled on. pub(crate) enum LocalServer { - /// A server binary on this machine and its [`build_id`]. - Binary(std::path::PathBuf, String), + /// A server binary on this machine. Release downloads may have a reusable archive. + Binary { path: std::path::PathBuf, build: String, release_hash: Option }, /// No binary available (offline): this build of the version already on the host. Installed(String), } @@ -538,10 +538,10 @@ pub(crate) async fn local_server( ) -> IdeResult { // This version's server: this build, or the release download (kept per version, so an // upgraded app never reuses an older one). - let local = match local_server_binary(os, arch) { - Some(local) => local, + let (local, release) = match local_server_binary(os, arch) { + Some(local) => (local, false), None => match download_server(state, version, os, arch, progress).await { - Ok(local) => local, + Ok(local) => (local, true), // Offline: any build of this version already on the host will do, then a server put // in the old unversioned place by hand. Err(e) => { @@ -564,7 +564,7 @@ pub(crate) async fn local_server( e.message, local.display() ); - local + (local, false) } None => { return Err(IdeError::unavailable(format!( @@ -581,13 +581,14 @@ pub(crate) async fn local_server( }, }; // One folder per build, so a rebuilt server of the same version is installed again. - let build = tokio::task::spawn_blocking({ + let hash = tokio::task::spawn_blocking({ let local = local.clone(); - move || build_id(&local) + move || binary_hash(&local) }) .await .map_err(|e| IdeError::internal(e.to_string()))??; - Ok(LocalServer::Binary(local, build)) + let build = hash.to_hex()[..16].to_owned(); + Ok(LocalServer::Binary { path: local, build, release_hash: release.then_some(hash) }) } /// Makes sure this version of the server is installed on the host; returns its path. @@ -604,10 +605,11 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A let mut lines = probe.lines().map(str::trim).filter(|l| !l.is_empty()); let (os, arch) = platform(lines.next().unwrap_or_default()); let installed: Vec = lines.map(str::to_owned).collect(); - let (local, build) = match local_server(state, version, &os, &arch, &installed, progress.clone()).await? { - LocalServer::Installed(bin) => return Ok(bin), - LocalServer::Binary(local, build) => (local, build), - }; + let (local, build, release_hash) = + match local_server(state, version, &os, &arch, &installed, progress.clone()).await? { + LocalServer::Installed(bin) => return Ok(bin), + LocalServer::Binary { path, build, release_hash } => (path, build, release_hash), + }; if let Some(bin) = installed.iter().find(|b| b.ends_with(&format!("/{build}/openidea-server"))) { return Ok(bin.to_string()); } @@ -624,9 +626,20 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A ); let started = std::time::Instant::now(); progress(RemoteStage::Uploading, Some(0.0)); - session - .put_with_progress(&tmp, &tokio::fs::read(&local).await?, &|f| progress(RemoteStage::Uploading, Some(f))) - .await?; + let archive = if let Some(hash) = release_hash { + let local = local.clone(); + tokio::task::spawn_blocking(move || ide_tools::server::matching_archive(&local, hash)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? + } else { + None + }; + let report = |f| progress(RemoteStage::Uploading, Some(f)); + if let Some(archive) = archive { + session.put_gzip_with_progress(&tmp, &archive, &report).await?; + } else { + session.put_with_progress(&tmp, &tokio::fs::read(&local).await?, &report).await?; + } tracing::info!("installed openidea-server on {} in {:?}", session.label(), started.elapsed()); let q = ide_ssh::shell::quote; // Older builds of this version go (a running one keeps its open file). @@ -646,21 +659,21 @@ async fn ensure_server(state: &AppState, session: &ide_ssh::Session, progress: A Ok(remote_bin) } -/// A short content hash of the server binary (cached per path, size and time). -fn build_id(path: &std::path::Path) -> IdeResult { - static CACHE: Mutex> = Mutex::new(None); +/// The content hash of the server binary (cached per path, size and time). +fn binary_hash(path: &std::path::Path) -> IdeResult { + static CACHE: Mutex> = Mutex::new(None); let meta = std::fs::metadata(path)?; let modified = meta.modified()?; - if let Some((p, len, time, id)) = &*CACHE.lock() + if let Some((p, len, time, hash)) = &*CACHE.lock() && p == path && *len == meta.len() && *time == modified { - return Ok(id.clone()); + return Ok(*hash); } - let id = blake3::hash(&std::fs::read(path)?).to_hex()[..16].to_owned(); - *CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, id.clone())); - Ok(id) + let hash = blake3::Hasher::new().update_reader(std::fs::File::open(path)?)?.finalize(); + *CACHE.lock() = Some((path.to_path_buf(), meta.len(), modified, hash)); + Ok(hash) } /// File › Remote Development: opens `path` on `target` (an SSH host, a WSL distribution, or a diff --git a/src-tauri/src/remote_wsl.rs b/src-tauri/src/remote_wsl.rs index 5e4c485cd..3cc87299a 100644 --- a/src-tauri/src/remote_wsl.rs +++ b/src-tauri/src/remote_wsl.rs @@ -230,7 +230,7 @@ pub(crate) async fn ensure_server( } let (local, build) = match local_server(state, version, &os, &arch, &probe.installed, progress.clone()).await? { LocalServer::Installed(bin) => return Ok(bin), - LocalServer::Binary(local, build) => (local, build), + LocalServer::Binary { path, build, .. } => (path, build), }; if let Some(bin) = probe.installed.iter().find(|b| b.ends_with(&format!("/{build}/{SERVER_BIN}"))) { return Ok(bin.clone());