Skip to main content

agentmux_srv_core/backend/update/
unpack.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Unpacking the Windows portable release's `.7z` in srv itself
5//! (`docs/specs/SPEC_UPDATE_UNPACK_7Z_IN_RUST_2026_10_19.md`).
6//!
7//! The release is packed LZMA2 with the BCJ2 filter (`scripts/package-portable.sh`
8//! runs `7z a -t7z -m0=lzma2 -mx=9`, and 7-Zip adds BCJ2 for executables).
9//! Windows 10's own `tar.exe` is libarchive built without liblzma, so it can't
10//! read one ("LZMA codec is unsupported"); `sevenz-rust2` decodes it here, on
11//! any Windows. Every entry is written under the destination or refused: an
12//! absolute path, a drive or root, or a `..` never reaches the disk.
13
14use std::io::{Read, Write};
15use std::path::{Component, Path, PathBuf};
16use std::sync::atomic::{AtomicBool, Ordering};
17
18/// An entry's data, read until `stop` is set: a timed-out unpack must stop
19/// writing, because its blocking thread can't be cancelled (QTest on #5124).
20struct UntilStopped<'a> {
21    inner: &'a mut dyn Read,
22    stop: &'a AtomicBool,
23}
24
25impl Read for UntilStopped<'_> {
26    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27        if self.stop.load(Ordering::Relaxed) {
28            return Err(std::io::Error::other("unpacking was stopped"));
29        }
30        self.inner.read(buf)
31    }
32}
33
34/// `dest` joined with an archive entry's `name`, or why it may not be
35/// written. Both `/` and `\` separate, so a Windows-authored name is checked
36/// the same on every platform. A `:` is refused too: on Windows `x:y` writes
37/// an NTFS alternate data stream, and no release file has one.
38fn entry_path(dest: &Path, name: &str) -> Result<PathBuf, String> {
39    let normalized = name.replace('\\', "/");
40    let mut path = dest.to_path_buf();
41    let mut named = false;
42    for part in Path::new(&normalized).components() {
43        match part {
44            Component::Normal(p) if p.to_string_lossy().contains(':') => {
45                return Err(format!("refused an entry with a ':' in its name: {name}"));
46            }
47            Component::Normal(p) => {
48                path.push(p);
49                named = true;
50            }
51            Component::CurDir => {}
52            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
53                return Err(format!("refused an entry outside the folder: {name}"));
54            }
55        }
56    }
57    if !named {
58        return Err(format!("refused an entry with no name: {name:?}"));
59    }
60    Ok(path)
61}
62
63/// Unpacks the `.7z` at `archive` into `dest`, which exists. Blocking: run it
64/// off the async runtime. Stops at the first entry it refuses or can't write,
65/// or as soon as `stop` is set, leaving what it wrote for the caller's
66/// staging folder to discard.
67pub(crate) fn unpack_7z(archive: &Path, dest: &Path, stop: &AtomicBool) -> Result<(), String> {
68    let file = std::fs::File::open(archive).map_err(|e| format!("can't open {}: {e}", archive.display()))?;
69    let mut reader = sevenz_rust2::ArchiveReader::new(std::io::BufReader::new(file), sevenz_rust2::Password::empty())
70        .map_err(|e| format!("can't decode the archive: {e}"))?;
71    // The callback can only return the crate's error; keep ours to report.
72    let mut refused: Option<String> = None;
73    let walked = reader.for_each_entries(|entry, data| {
74        if stop.load(Ordering::Relaxed) {
75            refused = Some("unpacking was stopped".to_string());
76            return Err(sevenz_rust2::Error::Other("unpacking was stopped".into()));
77        }
78        let path = match entry_path(dest, entry.name()) {
79            Ok(path) => path,
80            Err(why) => {
81                refused = Some(why.clone());
82                return Err(sevenz_rust2::Error::Other(why.into()));
83            }
84        };
85        if entry.is_directory() {
86            std::fs::create_dir_all(&path)?;
87            return Ok(true);
88        }
89        if let Some(parent) = path.parent() {
90            std::fs::create_dir_all(parent)?;
91        }
92        // Always read the entry through: in a solid archive the next one
93        // decodes from where this one ends.
94        let mut out = std::io::BufWriter::new(std::fs::File::create(&path)?);
95        std::io::copy(&mut UntilStopped { inner: data, stop }, &mut out)?;
96        out.flush()?;
97        Ok(true)
98    });
99    match (walked, refused) {
100        (_, Some(why)) => Err(why),
101        (Err(e), None) => Err(format!("can't decode the archive: {e}")),
102        (Ok(()), None) => Ok(()),
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    /// A portable-shaped folder packed with the release's own flags
111    /// (`7z a -t7z -m0=lzma2 -mx=9 -ms=on`) plus `-mf=BCJ2`: 7-Zip only picks
112    /// BCJ2 itself for a real PE, and these `.exe` files are small fakes. So the
113    /// coder chain is the release's (`7z l -slt`: `LZMA2:14 LZMA:14 BCJ2`). The
114    /// zip that used to stand in for the release hid that Windows' tar.exe
115    /// can't read LZMA.
116    const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/src/backend/testdata/update-portable-0.59.27.7z");
117
118    #[test]
119    fn the_release_codecs_unpack_into_a_staged_portable() {
120        let dest = tempfile::tempdir().unwrap();
121        unpack_7z(Path::new(FIXTURE), dest.path(), &go()).unwrap();
122        assert!(dest.path().join("agentmux.exe").is_file());
123        assert!(dest.path().join("runtime/agentmux-portable.marker").is_file());
124        assert!(dest.path().join("runtime/agentmux-0.59.27.exe").is_file());
125        // The contents survive BCJ2 + LZMA2, not just the names.
126        let exe = std::fs::read(dest.path().join("agentmux.exe")).unwrap();
127        assert_eq!(&exe[..2], b"MZ");
128        assert_eq!(std::fs::read_to_string(dest.path().join("runtime/README.txt")).unwrap().trim(), "AgentMux portable");
129    }
130
131    /// Not stopped.
132    fn go() -> AtomicBool {
133        AtomicBool::new(false)
134    }
135
136    // A timed-out unpack is told to stop, and writes nothing more (QTest on #5124).
137    #[test]
138    fn a_stopped_unpack_writes_nothing_more_and_says_so() {
139        let dest = tempfile::tempdir().unwrap();
140        let err = unpack_7z(Path::new(FIXTURE), dest.path(), &AtomicBool::new(true)).unwrap_err();
141        assert_eq!(err, "unpacking was stopped");
142        assert_eq!(std::fs::read_dir(dest.path()).unwrap().count(), 0);
143    }
144
145    #[test]
146    fn entries_outside_the_folder_are_refused() {
147        let dest = Path::new("/tmp/stage");
148        for name in ["../escape.txt", "a/../../escape.txt", "..\\escape.txt", "/etc/passwd", "\\abs.txt", ""] {
149            assert!(entry_path(dest, name).is_err(), "{name:?} must be refused");
150        }
151        #[cfg(windows)]
152        assert!(entry_path(dest, "C:\\Windows\\x.dll").is_err());
153        // An NTFS alternate data stream on Windows; refused everywhere.
154        assert!(entry_path(dest, "runtime/agentmux.exe:hidden").is_err());
155        assert_eq!(entry_path(dest, "runtime/./agentmux.exe").unwrap(), dest.join("runtime").join("agentmux.exe"));
156        assert_eq!(entry_path(dest, "runtime\\agentmux.exe").unwrap(), dest.join("runtime").join("agentmux.exe"));
157    }
158
159    #[test]
160    fn a_truncated_archive_fails_with_a_reason_not_a_panic() {
161        let dir = tempfile::tempdir().unwrap();
162        let bytes = std::fs::read(FIXTURE).unwrap();
163        let cut = dir.path().join("cut.7z");
164        std::fs::write(&cut, &bytes[..bytes.len() / 2]).unwrap();
165        let err = unpack_7z(&cut, &dir.path().join("out"), &go()).unwrap_err();
166        assert!(err.starts_with("can't decode the archive"), "{err}");
167        let err = unpack_7z(&dir.path().join("missing.7z"), dir.path(), &go()).unwrap_err();
168        assert!(err.starts_with("can't open"), "{err}");
169    }
170
171    /// The real release, by hand: `AGENTMUX_TEST_PORTABLE_7Z=<agentmux-X-x64-portable.7z>
172    /// AGENTMUX_TEST_PORTABLE_VERSION=X cargo test -p agentmux-srv-core real_release -- --ignored`.
173    #[test]
174    #[ignore]
175    fn a_real_release_unpacks_into_a_staged_portable() {
176        let archive = std::env::var("AGENTMUX_TEST_PORTABLE_7Z").expect("AGENTMUX_TEST_PORTABLE_7Z");
177        let version = std::env::var("AGENTMUX_TEST_PORTABLE_VERSION").expect("AGENTMUX_TEST_PORTABLE_VERSION");
178        let dest = tempfile::tempdir().unwrap();
179        let started = std::time::Instant::now();
180        unpack_7z(Path::new(&archive), dest.path(), &go()).unwrap();
181        eprintln!("unpacked in {:?}", started.elapsed());
182        assert!(dest.path().join("agentmux.exe").is_file());
183        assert!(dest.path().join("runtime/agentmux-portable.marker").is_file());
184        assert!(dest.path().join("runtime").join(format!("agentmux-{version}.exe")).is_file());
185        // `AGENTMUX_TEST_PORTABLE_COMPARE=<the same archive unpacked by 7-Zip>`:
186        // every file byte for byte, so BCJ2 + LZMA2 decode exactly.
187        if let Ok(reference) = std::env::var("AGENTMUX_TEST_PORTABLE_COMPARE") {
188            let mut compared = 0;
189            let mut stack = vec![PathBuf::from(&reference)];
190            while let Some(dir) = stack.pop() {
191                for e in std::fs::read_dir(&dir).unwrap() {
192                    let p = e.unwrap().path();
193                    if p.is_dir() {
194                        stack.push(p);
195                        continue;
196                    }
197                    let rel = p.strip_prefix(&reference).unwrap();
198                    assert!(std::fs::read(&p).unwrap() == std::fs::read(dest.path().join(rel)).unwrap(), "{} differs", rel.display());
199                    compared += 1;
200                }
201            }
202            eprintln!("{compared} files identical to 7-Zip's");
203        }
204    }
205}