1use crate::error::{Error, Result};
11use crate::logging::{debug, error, info, warn};
12use crate::upgrade::binary_cache::BinaryCache;
13use crate::upgrade::traffic::{self, UpgradeFetch};
14use crate::upgrade::{signature, UpgradeInfo, UpgradeResult};
15use flate2::read::GzDecoder;
16use semver::Version;
17use std::env;
18use std::fs::{self, File};
19use std::io::Read;
20use std::path::{Path, PathBuf};
21use tar::Archive;
22
23pub(super) const MAX_ARCHIVE_SIZE_BYTES: usize = 200 * 1024 * 1024;
25
26pub const RESTART_EXIT_CODE: i32 = 100;
32
33pub struct AutoApplyUpgrader {
35 current_version: Version,
37 client: reqwest::Client,
39 binary_cache: Option<BinaryCache>,
41 stop_on_upgrade: bool,
43}
44
45impl AutoApplyUpgrader {
46 #[must_use]
48 pub fn new() -> Self {
49 let current_version =
50 Version::parse(env!("CARGO_PKG_VERSION")).unwrap_or_else(|_| Version::new(0, 0, 0));
51
52 Self {
53 current_version,
54 client: reqwest::Client::builder()
55 .user_agent(concat!("ant-node/", env!("CARGO_PKG_VERSION")))
56 .timeout(std::time::Duration::from_mins(5))
57 .build()
58 .unwrap_or_else(|_| reqwest::Client::new()),
59 binary_cache: None,
60 stop_on_upgrade: false,
61 }
62 }
63
64 #[must_use]
69 pub fn with_binary_cache(mut self, cache: BinaryCache) -> Self {
70 self.binary_cache = Some(cache);
71 self
72 }
73
74 #[must_use]
79 pub fn with_stop_on_upgrade(mut self, stop: bool) -> Self {
80 self.stop_on_upgrade = stop;
81 self
82 }
83
84 #[must_use]
86 pub fn current_version(&self) -> &Version {
87 &self.current_version
88 }
89
90 pub fn current_binary_path() -> Result<PathBuf> {
100 let invoked_path = env::args().next().map(PathBuf::from);
103
104 if let Some(ref invoked) = invoked_path {
105 let path_str = invoked.to_string_lossy();
110 let cleaned = if path_str.ends_with(" (deleted)") {
111 let stripped = path_str.trim_end_matches(" (deleted)");
112 debug!("Stripped '(deleted)' suffix from invoked path: {stripped}");
113 PathBuf::from(stripped)
114 } else {
115 invoked.clone()
116 };
117
118 if cleaned.exists() {
119 if let Ok(canonical) = cleaned.canonicalize() {
122 return Ok(canonical);
123 }
124 return Ok(cleaned);
125 }
126 }
127
128 let path = env::current_exe()
130 .map_err(|e| Error::Upgrade(format!("Cannot determine binary path: {e}")))?;
131
132 #[cfg(unix)]
133 {
134 let path_str = path.to_string_lossy();
135 if path_str.ends_with(" (deleted)") {
136 let cleaned = path_str.trim_end_matches(" (deleted)");
137 debug!("Stripped '(deleted)' suffix from binary path: {cleaned}");
138 return Ok(PathBuf::from(cleaned));
139 }
140 }
141
142 Ok(path)
143 }
144
145 pub async fn apply_upgrade(&self, info: &UpgradeInfo) -> Result<UpgradeResult> {
160 info!(
161 "Starting auto-apply upgrade from {} to {}",
162 self.current_version, info.version
163 );
164
165 if info.version <= self.current_version {
167 warn!(
168 "Ignoring downgrade attempt: {} -> {}",
169 self.current_version, info.version
170 );
171 return Ok(UpgradeResult::NoUpgrade);
172 }
173
174 let current_binary = Self::current_binary_path()?;
176 let binary_dir = current_binary
177 .parent()
178 .ok_or_else(|| Error::Upgrade("Cannot determine binary directory".to_string()))?;
179
180 let mut tempdir_builder = tempfile::Builder::new();
191 tempdir_builder.prefix("ant-upgrade-");
192 #[cfg(unix)]
193 {
194 use std::os::unix::fs::PermissionsExt;
195 tempdir_builder.permissions(std::fs::Permissions::from_mode(0o700));
196 }
197 let temp_dir = tempdir_builder
198 .tempdir_in(binary_dir)
199 .map_err(|e| Error::Upgrade(format!("Failed to create temp dir: {e}")))?;
200
201 let version_str = info.version.to_string();
202
203 let extracted_binary = match self
206 .resolve_upgrade_binary(info, temp_dir.path(), &version_str)
207 .await
208 {
209 Ok(path) => path,
210 Err(e) => {
211 warn!("Download/verify/extract failed: {e}");
212 return Ok(UpgradeResult::RolledBack {
213 reason: format!("{e}"),
214 });
215 }
216 };
217
218 if let Some(disk_version) = on_disk_version(¤t_binary).await {
221 if disk_version == info.version {
222 info!(
223 "Binary already upgraded to {} by another service, skipping replacement",
224 info.version
225 );
226 let exit_code = self.prepare_restart(¤t_binary)?;
227 return Ok(UpgradeResult::Success {
228 version: info.version.clone(),
229 exit_code,
230 });
231 }
232 }
233
234 let backup_path = binary_dir.join(format!(
236 "{}.backup",
237 current_binary
238 .file_name()
239 .map_or_else(|| "ant-node".into(), |s| s.to_string_lossy())
240 ));
241 info!("Creating backup at {}...", backup_path.display());
242 if let Err(e) = fs::copy(¤t_binary, &backup_path) {
243 warn!("Backup creation failed: {e}");
244 return Ok(UpgradeResult::RolledBack {
245 reason: format!("Backup failed: {e}"),
246 });
247 }
248
249 info!("Replacing binary...");
252 let new_bin = extracted_binary.clone();
253 let target_bin = current_binary.clone();
254 let replace_result =
255 tokio::task::spawn_blocking(move || Self::replace_binary(&new_bin, &target_bin))
256 .await
257 .map_err(|e| Error::Upgrade(format!("Binary replacement task panicked: {e}")))?;
258 if let Err(e) = replace_result {
259 warn!("Binary replacement failed: {e}");
260 if let Err(restore_err) = fs::copy(&backup_path, ¤t_binary) {
262 error!("CRITICAL: Replacement failed ({e}) AND rollback failed ({restore_err})");
263 return Err(Error::Upgrade(format!(
264 "Critical: replacement failed ({e}) AND rollback failed ({restore_err})"
265 )));
266 }
267 return Ok(UpgradeResult::RolledBack {
268 reason: format!("Replacement failed: {e}"),
269 });
270 }
271
272 info!(
273 "Successfully upgraded to version {}! Restarting...",
274 info.version
275 );
276
277 let exit_code = self.prepare_restart(¤t_binary)?;
279
280 Ok(UpgradeResult::Success {
281 version: info.version.clone(),
282 exit_code,
283 })
284 }
285
286 async fn download(&self, url: &str, dest: &Path, kind: UpgradeFetch) -> Result<()> {
288 debug!("Downloading: {}", url);
289
290 let bytes = match self.fetch_body(url).await {
293 Ok(bytes) => bytes,
294 Err(e) => {
295 traffic::record_error(kind);
296 return Err(e);
297 }
298 };
299 traffic::record_rx(kind, bytes.len());
300
301 if bytes.len() > MAX_ARCHIVE_SIZE_BYTES {
302 return Err(Error::Upgrade(format!(
303 "Downloaded file too large: {} bytes (max {})",
304 bytes.len(),
305 MAX_ARCHIVE_SIZE_BYTES
306 )));
307 }
308
309 fs::write(dest, &bytes)?;
310 debug!("Downloaded {} bytes to {}", bytes.len(), dest.display());
311 Ok(())
312 }
313
314 async fn fetch_body(&self, url: &str) -> Result<bytes::Bytes> {
316 let response = self
317 .client
318 .get(url)
319 .send()
320 .await
321 .map_err(|e| Error::Network(format!("Download failed: {e}")))?;
322
323 if !response.status().is_success() {
324 return Err(Error::Network(format!(
325 "Download returned status: {}",
326 response.status()
327 )));
328 }
329
330 response
331 .bytes()
332 .await
333 .map_err(|e| Error::Network(format!("Failed to read response: {e}")))
334 }
335
336 async fn resolve_upgrade_binary(
344 &self,
345 info: &UpgradeInfo,
346 dest_dir: &Path,
347 version_str: &str,
348 ) -> Result<PathBuf> {
349 if let Some(ref cache) = self.binary_cache {
350 if let Some(verified_archive) = cache.get_verified_archive(version_str, dest_dir) {
358 match Self::extract_binary(&verified_archive, dest_dir) {
359 Ok(binary) => {
360 info!("Reused signature-verified cached archive for {version_str}");
361 return Ok(binary);
362 }
363 Err(e) => {
364 warn!("Failed to extract from cached archive, will re-download: {e}");
365 return self
366 .download_verify_extract(info, dest_dir, Some(cache))
367 .await;
368 }
369 }
370 }
371
372 let cache_clone = cache.clone();
375 let lock_guard =
379 tokio::task::spawn_blocking(move || cache_clone.acquire_download_lock())
380 .await
381 .map_err(|e| Error::Upgrade(format!("Lock task failed: {e}")))??;
382
383 if let Some(verified_archive) = cache.get_verified_archive(version_str, dest_dir) {
386 if let Ok(binary) = Self::extract_binary(&verified_archive, dest_dir) {
387 info!(
388 "Signature-verified cached archive became available under lock for {version_str}"
389 );
390 return Ok(binary);
391 }
392 }
393
394 let result = self
396 .download_verify_extract(info, dest_dir, Some(cache))
397 .await;
398 drop(lock_guard);
399 result
400 } else {
401 self.download_verify_extract(info, dest_dir, None).await
402 }
403 }
404
405 async fn download_verify_extract(
413 &self,
414 info: &UpgradeInfo,
415 dest_dir: &Path,
416 cache: Option<&BinaryCache>,
417 ) -> Result<PathBuf> {
418 let archive_path = dest_dir.join("archive");
419 let sig_path = dest_dir.join("signature");
420
421 info!("Downloading ant-node binary...");
423 self.download(&info.download_url, &archive_path, UpgradeFetch::Archive)
424 .await?;
425
426 info!("Downloading signature...");
428 self.download(&info.signature_url, &sig_path, UpgradeFetch::Signature)
429 .await?;
430
431 info!("Verifying ML-DSA signature on archive...");
433 signature::verify_from_file(&archive_path, &sig_path)?;
434 info!("Archive signature verified successfully");
435
436 info!("Extracting binary from archive...");
438 let extracted_binary = Self::extract_binary(&archive_path, dest_dir)?;
439
440 if let Some(c) = cache {
449 let version_str = info.version.to_string();
450 if let Err(e) = c.store_archive(&version_str, &archive_path, &sig_path) {
451 warn!("Failed to store verified archive in cache: {e}");
452 }
453 }
454
455 Ok(extracted_binary)
456 }
457
458 fn extract_binary(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
464 let mut file = File::open(archive_path)?;
465 let mut magic = [0u8; 2];
466 file.read_exact(&mut magic)
467 .map_err(|e| Error::Upgrade(format!("Failed to read archive header: {e}")))?;
468 drop(file);
469
470 match magic {
471 [0x1f, 0x8b] => Self::extract_from_tar_gz(archive_path, dest_dir),
472 [0x50, 0x4b] => Self::extract_from_zip(archive_path, dest_dir),
473 _ => Err(Error::Upgrade(format!(
474 "Unknown archive format (magic bytes: {:02x} {:02x})",
475 magic[0], magic[1]
476 ))),
477 }
478 }
479
480 fn extract_from_tar_gz(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
482 let file = File::open(archive_path)?;
483 let decoder = GzDecoder::new(file);
484 let mut archive = Archive::new(decoder);
485
486 let binary_name = if cfg!(windows) {
487 "ant-node.exe"
488 } else {
489 "ant-node"
490 };
491 let extracted_binary = dest_dir.join(binary_name);
492
493 for entry in archive
494 .entries()
495 .map_err(|e| Error::Upgrade(format!("Failed to read archive: {e}")))?
496 {
497 let mut entry =
498 entry.map_err(|e| Error::Upgrade(format!("Failed to read entry: {e}")))?;
499 let path = entry
500 .path()
501 .map_err(|e| Error::Upgrade(format!("Invalid path in archive: {e}")))?;
502
503 if let Some(name) = path.file_name() {
505 let name_str = name.to_string_lossy();
506 if name_str == "ant-node" || name_str == "ant-node.exe" {
507 debug!("Found binary in tar.gz archive: {}", path.display());
508
509 let mut out = File::create(&extracted_binary)?;
511 std::io::copy(&mut entry, &mut out)
512 .map_err(|e| Error::Upgrade(format!("Failed to write binary: {e}")))?;
513
514 #[cfg(unix)]
516 {
517 use std::os::unix::fs::PermissionsExt;
518 let mut perms = fs::metadata(&extracted_binary)?.permissions();
519 perms.set_mode(0o755);
520 fs::set_permissions(&extracted_binary, perms)?;
521 }
522
523 return Ok(extracted_binary);
524 }
525 }
526 }
527
528 Err(Error::Upgrade(
529 "ant-node binary not found in tar.gz archive".to_string(),
530 ))
531 }
532
533 fn extract_from_zip(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
535 let file = File::open(archive_path)?;
536 let mut archive = zip::ZipArchive::new(file)
537 .map_err(|e| Error::Upgrade(format!("Failed to open zip archive: {e}")))?;
538
539 let binary_name = if cfg!(windows) {
540 "ant-node.exe"
541 } else {
542 "ant-node"
543 };
544 let extracted_binary = dest_dir.join(binary_name);
545
546 for i in 0..archive.len() {
547 let mut entry = archive
548 .by_index(i)
549 .map_err(|e| Error::Upgrade(format!("Failed to read zip entry: {e}")))?;
550
551 let path = match entry.enclosed_name() {
552 Some(p) => p.clone(),
553 None => continue,
554 };
555
556 if let Some(name) = path.file_name() {
557 let name_str = name.to_string_lossy();
558 if name_str == "ant-node" || name_str == "ant-node.exe" {
559 debug!("Found binary in zip archive: {}", path.display());
560
561 let mut out = File::create(&extracted_binary)?;
563 std::io::copy(&mut entry, &mut out)
564 .map_err(|e| Error::Upgrade(format!("Failed to write binary: {e}")))?;
565
566 #[cfg(unix)]
568 {
569 use std::os::unix::fs::PermissionsExt;
570 let mut perms = fs::metadata(&extracted_binary)?.permissions();
571 perms.set_mode(0o755);
572 fs::set_permissions(&extracted_binary, perms)?;
573 }
574
575 return Ok(extracted_binary);
576 }
577 }
578 }
579
580 Err(Error::Upgrade(
581 "ant-node binary not found in zip archive".to_string(),
582 ))
583 }
584
585 fn replace_binary(new_binary: &Path, target: &Path) -> Result<()> {
590 #[cfg(unix)]
591 {
592 if let Ok(meta) = fs::metadata(target) {
594 let perms = meta.permissions();
595 fs::set_permissions(new_binary, perms)?;
596 }
597 fs::rename(new_binary, target)?;
599 }
600
601 #[cfg(windows)]
602 {
603 let _ = target; let delays = [500u64, 1000, 2000];
606 let mut last_err = None;
607 for (attempt, delay_ms) in delays.iter().enumerate() {
608 match self_replace::self_replace(new_binary) {
609 Ok(()) => {
610 last_err = None;
611 break;
612 }
613 Err(e) => {
614 warn!(
615 "self_replace attempt {} failed: {e}, retrying in {delay_ms}ms",
616 attempt + 1
617 );
618 last_err = Some(e);
619 std::thread::sleep(std::time::Duration::from_millis(*delay_ms));
620 }
621 }
622 }
623 if let Some(e) = last_err {
624 return Err(Error::Upgrade(format!(
625 "self_replace failed after retries: {e}"
626 )));
627 }
628 }
629
630 debug!("Binary replacement complete");
631 Ok(())
632 }
633
634 fn prepare_restart(&self, binary_path: &Path) -> Result<i32> {
649 if self.stop_on_upgrade {
650 let exit_code;
651
652 #[cfg(unix)]
653 {
654 info!("Service manager mode: will exit with code 0 after graceful shutdown");
655 exit_code = 0;
656 }
657
658 #[cfg(windows)]
659 {
660 let _ = binary_path;
661 info!(
662 "Service manager mode: will exit with code {} after graceful shutdown",
663 RESTART_EXIT_CODE
664 );
665 exit_code = RESTART_EXIT_CODE;
666 }
667
668 #[cfg(not(any(unix, windows)))]
669 {
670 let _ = binary_path;
671 warn!("Auto-restart not supported on this platform. Please restart manually.");
672 exit_code = 0;
673 }
674
675 Ok(exit_code)
676 } else {
677 let args: Vec<String> = env::args().skip(1).collect();
679
680 info!("Spawning new process: {} {:?}", binary_path.display(), args);
681
682 std::process::Command::new(binary_path)
683 .args(&args)
684 .stdin(std::process::Stdio::null())
685 .stdout(std::process::Stdio::inherit())
686 .stderr(std::process::Stdio::inherit())
687 .spawn()
688 .map_err(|e| Error::Upgrade(format!("Failed to spawn new binary: {e}")))?;
689
690 info!("New process spawned, will exit after graceful shutdown");
691 Ok(0)
692 }
693 }
694}
695
696async fn on_disk_version(binary_path: &Path) -> Option<Version> {
704 let output = tokio::time::timeout(
705 std::time::Duration::from_secs(5),
706 tokio::process::Command::new(binary_path)
707 .arg("--version")
708 .output(),
709 )
710 .await
711 .ok()?
712 .ok()?;
713 let stdout = String::from_utf8_lossy(&output.stdout);
714 let version_str = stdout.trim().strip_prefix("ant-node ")?;
715 Version::parse(version_str).ok()
716}
717
718impl Default for AutoApplyUpgrader {
719 fn default() -> Self {
720 Self::new()
721 }
722}
723
724#[cfg(test)]
725#[allow(clippy::unwrap_used, clippy::expect_used)]
726mod tests {
727 use super::*;
728
729 #[test]
730 fn test_auto_apply_upgrader_creation() {
731 let upgrader = AutoApplyUpgrader::new();
732 assert!(!upgrader.current_version().to_string().is_empty());
733 }
734
735 #[test]
736 fn test_current_binary_path() {
737 let result = AutoApplyUpgrader::current_binary_path();
738 assert!(result.is_ok());
739 let path = result.unwrap();
740 assert!(path.exists() || path.to_string_lossy().contains("test"));
741 }
742
743 #[test]
744 fn test_default_impl() {
745 let upgrader = AutoApplyUpgrader::default();
746 assert!(!upgrader.current_version().to_string().is_empty());
747 }
748
749 fn create_tar_gz_archive(dir: &Path, binary_name: &str, content: &[u8]) -> PathBuf {
751 use flate2::write::GzEncoder;
752 use flate2::Compression;
753
754 let archive_path = dir.join("test.tar.gz");
755 let file = File::create(&archive_path).unwrap();
756 let encoder = GzEncoder::new(file, Compression::default());
757 let mut builder = tar::Builder::new(encoder);
758
759 let mut header = tar::Header::new_gnu();
760 header.set_size(content.len() as u64);
761 header.set_mode(0o755);
762 header.set_cksum();
763 builder
764 .append_data(&mut header, binary_name, content)
765 .unwrap();
766 builder.finish().unwrap();
767
768 archive_path
769 }
770
771 fn create_zip_archive(dir: &Path, binary_name: &str, content: &[u8]) -> PathBuf {
773 use std::io::Write;
774
775 let archive_path = dir.join("test.zip");
776 let file = File::create(&archive_path).unwrap();
777 let mut zip_writer = zip::ZipWriter::new(file);
778 let options = zip::write::SimpleFileOptions::default()
779 .compression_method(zip::CompressionMethod::Stored);
780 zip_writer.start_file(binary_name, options).unwrap();
781 zip_writer.write_all(content).unwrap();
782 zip_writer.finish().unwrap();
783
784 archive_path
785 }
786
787 #[test]
788 fn test_extract_binary_from_tar_gz() {
789 let dir = tempfile::tempdir().unwrap();
790 let content = b"fake-binary-content";
791 let archive = create_tar_gz_archive(dir.path(), "ant-node", content);
792
793 let dest = tempfile::tempdir().unwrap();
794 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
795 assert!(result.is_ok());
796
797 let extracted = result.unwrap();
798 assert!(extracted.exists());
799 assert_eq!(fs::read(&extracted).unwrap(), content);
800 }
801
802 #[test]
803 fn test_extract_binary_from_zip() {
804 let dir = tempfile::tempdir().unwrap();
805 let content = b"fake-binary-content";
806 let archive = create_zip_archive(dir.path(), "ant-node", content);
807
808 let dest = tempfile::tempdir().unwrap();
809 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
810 assert!(result.is_ok());
811
812 let extracted = result.unwrap();
813 assert!(extracted.exists());
814 assert_eq!(fs::read(&extracted).unwrap(), content);
815 }
816
817 #[test]
818 fn test_extract_binary_from_zip_with_exe() {
819 let dir = tempfile::tempdir().unwrap();
820 let content = b"fake-windows-binary";
821 let archive = create_zip_archive(dir.path(), "ant-node.exe", content);
822
823 let dest = tempfile::tempdir().unwrap();
824 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
825 assert!(result.is_ok());
826
827 let extracted = result.unwrap();
828 assert!(extracted.exists());
829 assert_eq!(fs::read(&extracted).unwrap(), content);
830 }
831
832 #[test]
833 fn test_extract_binary_from_tar_gz_nested_path() {
834 let dir = tempfile::tempdir().unwrap();
835 let content = b"nested-binary";
836 let archive = create_tar_gz_archive(dir.path(), "some/nested/path/ant-node", content);
837
838 let dest = tempfile::tempdir().unwrap();
839 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
840 assert!(result.is_ok());
841
842 let extracted = result.unwrap();
843 assert!(extracted.exists());
844 assert_eq!(fs::read(&extracted).unwrap(), content);
845 }
846
847 #[test]
848 fn test_extract_binary_unknown_format() {
849 let dir = tempfile::tempdir().unwrap();
850 let archive_path = dir.path().join("bad_archive");
851 fs::write(&archive_path, b"XX not a real archive").unwrap();
852
853 let dest = tempfile::tempdir().unwrap();
854 let result = AutoApplyUpgrader::extract_binary(&archive_path, dest.path());
855 assert!(result.is_err());
856
857 let err = result.unwrap_err().to_string();
858 assert!(err.contains("Unknown archive format"));
859 }
860
861 #[test]
862 fn test_extract_binary_missing_binary_in_tar_gz() {
863 let dir = tempfile::tempdir().unwrap();
864 let content = b"not-the-binary";
865 let archive = create_tar_gz_archive(dir.path(), "other-file", content);
866
867 let dest = tempfile::tempdir().unwrap();
868 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
869 assert!(result.is_err());
870
871 let err = result.unwrap_err().to_string();
872 assert!(err.contains("not found in tar.gz archive"));
873 }
874
875 #[test]
876 fn test_extract_binary_missing_binary_in_zip() {
877 let dir = tempfile::tempdir().unwrap();
878 let content = b"not-the-binary";
879 let archive = create_zip_archive(dir.path(), "other-file", content);
880
881 let dest = tempfile::tempdir().unwrap();
882 let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
883 assert!(result.is_err());
884
885 let err = result.unwrap_err().to_string();
886 assert!(err.contains("not found in zip archive"));
887 }
888
889 #[test]
890 fn test_extract_binary_empty_file() {
891 let dir = tempfile::tempdir().unwrap();
892 let archive_path = dir.path().join("empty");
893 fs::write(&archive_path, b"").unwrap();
894
895 let dest = tempfile::tempdir().unwrap();
896 let result = AutoApplyUpgrader::extract_binary(&archive_path, dest.path());
897 assert!(result.is_err());
898 }
899}