agentmux_srv_core/backend/update/
unpack.rs1use std::io::{Read, Write};
15use std::path::{Component, Path, PathBuf};
16use std::sync::atomic::{AtomicBool, Ordering};
17
18struct 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
34fn 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
63pub(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 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 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 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 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 fn go() -> AtomicBool {
133 AtomicBool::new(false)
134 }
135
136 #[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 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 #[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 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}