team-ljyzipelo

공개
651줄21 KB
1use super::*;
2use std::{io::Read, process::Child, sync::mpsc, time::Duration};
3
4fn private_dir(path: &std::path::Path) {
5 let mut builder = fs::DirBuilder::new();
6 #[cfg(unix)]
7 {
8 use std::os::unix::fs::DirBuilderExt;
9 builder.mode(0o700);
10 }
11 builder.create(path).unwrap();
12}
13struct Case(PathBuf);
14impl Case {
15 fn new() -> Self {
16 let root = std::env::var_os("TMPDIR")
17 .map(PathBuf::from)
18 .unwrap_or_else(|| {
19 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/work/tmp")
20 });
21 fs::create_dir_all(&root).unwrap();
22 let path = root.canonicalize().unwrap().join(format!(
23 "zipelo-7zc-{}-{}",
24 std::process::id(),
25 NEXT.fetch_add(1, Ordering::Relaxed)
26 ));
27 private_dir(&path);
28 private_dir(&path.join("tmp"));
29 Self(path)
30 }
31 fn path(&self, name: &str) -> NativePath {
32 NativePath::from_path(&self.0.join(name))
33 }
34 fn request(&self, names: &[&str]) -> Start {
35 Start {
36 action: Action::CreateSevenZip {
37 sources: names
38 .iter()
39 .map(|name| Source {
40 path: self.path(name),
41 archive_name: (*name).to_owned(),
42 })
43 .collect(),
44 output_file: self.path("result.7z"),
45 method: SevenZipMethod::Lzma2,
46 solid: false,
47 encryption: Encryption::None,
48 },
49 limits: Limits::default(),
50 }
51 }
52 fn command(&self) -> Command {
53 let mut cmd = Command::new(env!("CARGO_BIN_EXE_zipelo-archive-worker"));
54 cmd.env("TMPDIR", self.0.join("tmp"))
55 .env("TMP", self.0.join("tmp"))
56 .env("TEMP", self.0.join("tmp"));
57 cmd
58 }
59 fn run(&self, message: Message) -> Vec<Message> {
60 self.run_with(&mut self.command(), message, |_| Vec::new())
61 }
62 fn run_with(
63 &self,
64 command: &mut Command,
65 message: Message,
66 mut respond: impl FnMut(&Message) -> Vec<Message>,
67 ) -> Vec<Message> {
68 struct Running(Child);
69 impl Drop for Running {
70 fn drop(&mut self) {
71 let _ = self.0.kill();
72 let _ = self.0.wait();
73 }
74 }
75 let mut child = Running(
76 command
77 .stdin(Stdio::piped())
78 .stdout(Stdio::piped())
79 .stderr(Stdio::piped())
80 .spawn()
81 .unwrap(),
82 );
83 let mut writer = Writer::new(child.0.stdin.take().unwrap(), 17);
84 writer.send(&message).unwrap();
85 let stdout = child.0.stdout.take().unwrap();
86 let mut stderr = child.0.stderr.take().unwrap();
87 let diagnostic = std::thread::spawn(move || {
88 let mut bytes = Vec::new();
89 stderr.read_to_end(&mut bytes).unwrap();
90 bytes
91 });
92 let (send, receive) = mpsc::sync_channel(128);
93 let reader = std::thread::spawn(move || {
94 let mut reader = Reader::new(stdout);
95 loop {
96 let frame = reader.read();
97 let end = !matches!(frame, Ok(Some(_)));
98 if send.send(frame).is_err() || end {
99 break;
100 }
101 }
102 });
103 let mut events = Vec::new();
104 while let Some((job, _, event)) = receive
105 .recv_timeout(Duration::from_secs(120))
106 .expect("worker timeout")
107 .unwrap()
108 {
109 assert_eq!(job, 17);
110 for reply in respond(&event) {
111 writer.send(&reply).unwrap();
112 }
113 events.push(event);
114 }
115 drop(writer);
116 reader.join().unwrap();
117 assert!(child.0.wait().unwrap().success());
118 assert!(diagnostic.join().unwrap().is_empty());
119 assert!(matches!(events.last(), Some(Message::Terminal(_))));
120 assert_eq!(
121 events
122 .iter()
123 .filter(|e| matches!(e, Message::Terminal(_)))
124 .count(),
125 1
126 );
127 assert_eq!(fs::read_dir(self.0.join("tmp")).unwrap().count(), 0);
128 events
129 }
130 fn list(&self) -> Vec<Message> {
131 self.run(Message::Start(Start {
132 action: Action::List {
133 archive: self.path("result.7z"),
134 },
135 limits: Limits::default(),
136 }))
137 }
138 fn extract(&self, destination: &str) -> Vec<Message> {
139 private_dir(&self.0.join(destination));
140 self.run(Message::Start(Start {
141 action: Action::Extract {
142 archive: self.path("result.7z"),
143 destination: self.path(destination),
144 selection: Selection::All,
145 list_id: None,
146 gzip_output_name: None,
147 },
148 limits: Limits::default(),
149 }))
150 }
151}
152impl Drop for Case {
153 fn drop(&mut self) {
154 fs::remove_dir_all(&self.0).expect("7z 작성 시험 폴더 정리에 실패함");
155 }
156}
157fn success(events: &[Message]) {
158 let t = terminal(events);
159 assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
160 assert_eq!(t.error, ErrorCode::None);
161 assert!(events.iter().any(|e| matches!(
162 e,
163 Message::Progress {
164 stage: Stage::Commit,
165 ..
166 }
167 )));
168 assert_eq!(t.publication, Publication::Complete);
169 assert_eq!(t.created_count, 1);
170 assert_eq!(t.retained_partial_count, 0);
171 assert_eq!(t.cleanup, Cleanup::Complete);
172 assert_eq!(
173 events
174 .iter()
175 .filter(|e| matches!(e, Message::Output { .. }))
176 .count(),
177 1
178 );
179 assert!(events.iter().any(|e| matches!(e, Message::Output { entry_id: None, relative_name, disposition: Disposition::Created } if relative_name == "result.7z")));
180 assert!(!events.iter().any(|e| matches!(
181 e,
182 Message::PasswordRequired { .. } | Message::ConflictRequired { .. }
183 )));
184}
185fn failure(events: &[Message], error: ErrorCode) {
186 let t = terminal(events);
187 assert_eq!(t.error, error, "{events:?}");
188 assert_eq!(
189 t.outcome,
190 if error == ErrorCode::None {
191 Outcome::Cancelled
192 } else {
193 Outcome::Failed
194 }
195 );
196 assert_eq!(t.publication, Publication::None);
197 assert_eq!(t.created_count, 0);
198 assert_eq!(t.retained_partial_count, 0);
199 assert_eq!(t.cleanup, Cleanup::Complete);
200 assert!(!events.iter().any(|e| matches!(e, Message::Output { .. })));
201}
202fn tree(root: &std::path::Path) -> std::collections::BTreeMap<String, Option<[u8; 32]>> {
203 use sha2::{Digest, Sha256};
204 fn walk(
205 root: &std::path::Path,
206 at: &std::path::Path,
207 result: &mut std::collections::BTreeMap<String, Option<[u8; 32]>>,
208 ) {
209 for entry in fs::read_dir(at).unwrap() {
210 let path = entry.unwrap().path();
211 let name = path
212 .strip_prefix(root)
213 .unwrap()
214 .to_str()
215 .unwrap()
216 .replace('\\', "/");
217 if path.is_dir() {
218 result.insert(name, None);
219 walk(root, &path, result);
220 } else {
221 result.insert(name, Some(Sha256::digest(fs::read(path).unwrap()).into()));
222 }
223 }
224 }
225 let mut result = std::collections::BTreeMap::new();
226 walk(root, root, &mut result);
227 result
228}
229
230#[test]
231fn mixed_unicode_files_and_empty_bitmap_boundaries_round_trip() {
232 for count in [7, 8, 9] {
233 let c = Case::new();
234 fs::create_dir_all(c.0.join("원본/폴더/빈 폴더")).unwrap();
235 fs::write(c.0.join("원본/가.txt"), "한글 자료\n".repeat(1000)).unwrap();
236 fs::write(
237 c.0.join("원본/폴더/z"),
238 (0..131_081)
239 .map(|n| ((n * 73) % 251) as u8)
240 .collect::<Vec<_>>(),
241 )
242 .unwrap();
243 for index in 0..count - 3 {
244 fs::write(c.0.join(format!("원본/빈-{index}")), b"").unwrap();
245 }
246 fs::write(c.0.join("원본/\u{20000}.txt"), b"UTF-16 surrogate pair").unwrap();
247 let mut state = 0x1234_5678u32;
248 let noise: Vec<u8> = (0..131_081)
249 .map(|_| {
250 state ^= state << 13;
251 state ^= state >> 17;
252 state ^= state << 5;
253 state as u8
254 })
255 .collect();
256 fs::write(c.0.join("원본/noise.bin"), noise).unwrap();
257 let expected = tree(&c.0.join("원본"));
258 let events = c.run(Message::Start(c.request(&["원본"])));
259 success(&events);
260 assert!(matches!(
261 events[0],
262 Message::Accepted {
263 action: ActionKind::CreateSevenZip,
264 encryption: false
265 }
266 ));
267 let list = c.list();
268 assert_eq!(terminal(&list).outcome, Outcome::Completed, "{list:?}");
269 let extracted = c.extract("decoded");
270 assert_eq!(
271 terminal(&extracted).outcome,
272 Outcome::Completed,
273 "{extracted:?}"
274 );
275 assert_eq!(tree(&c.0.join("decoded/원본")), expected);
276 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
277 for operation in ["t", "l"] {
278 let output = Command::new(&tool)
279 .args([operation, "-slt"])
280 .arg(c.0.join("result.7z"))
281 .output()
282 .unwrap();
283 assert!(
284 output.status.success(),
285 "{}",
286 String::from_utf8_lossy(&output.stdout)
287 );
288 if operation == "l" {
289 let text = String::from_utf8_lossy(&output.stdout);
290 assert!(text.contains("Method = LZMA2:20"), "{text}");
291 assert!(text.contains("Solid = -"), "{text}");
292 assert!(!text.contains("Encrypted = +"));
293 }
294 }
295 let output = Command::new(tool)
296 .args(["x", "-y"])
297 .arg(c.0.join("result.7z"))
298 .arg(format!("-o{}", c.0.join("independent").display()))
299 .output()
300 .unwrap();
301 assert!(
302 output.status.success(),
303 "{}",
304 String::from_utf8_lossy(&output.stdout)
305 );
306 assert_eq!(tree(&c.0.join("independent/원본")), expected);
307 }
308 }
309}
310
311#[test]
312fn archives_with_only_empty_files_and_directories_are_valid() {
313 for directory in [false, true] {
314 let c = Case::new();
315 if directory {
316 fs::create_dir_all(c.0.join("empty/nested")).unwrap();
317 } else {
318 fs::write(c.0.join("empty"), b"").unwrap();
319 }
320 success(&c.run(Message::Start(c.request(&["empty"]))));
321 let extracted = c.extract("decoded");
322 assert_eq!(
323 terminal(&extracted).outcome,
324 Outcome::Completed,
325 "{extracted:?}"
326 );
327 assert_eq!(c.0.join("decoded/empty").is_dir(), directory);
328 if let Some(tool) = std::env::var_os("ZIPELO_TEST_7ZIP") {
329 assert!(
330 Command::new(tool)
331 .arg("t")
332 .arg(c.0.join("result.7z"))
333 .output()
334 .unwrap()
335 .status
336 .success()
337 );
338 }
339 }
340}
341
342#[test]
343fn existing_output_empty_sources_limits_and_links_are_rejected() {
344 let c = Case::new();
345 fs::write(c.0.join("source"), b"abcdef").unwrap();
346 fs::write(c.0.join("result.7z"), b"preserve").unwrap();
347 failure(
348 &c.run(Message::Start(c.request(&["source"]))),
349 ErrorCode::Conflict,
350 );
351 assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"preserve");
352 fs::remove_file(c.0.join("result.7z")).unwrap();
353 failure(
354 &c.run(Message::Start(c.request(&[]))),
355 ErrorCode::InvalidRequest,
356 );
357 for bytes in [5, 6, 7] {
358 let mut start = c.request(&["source"]);
359 start.limits.input = bytes;
360 start.limits.output = bytes;
361 let events = c.run(Message::Start(start));
362 if bytes == 5 {
363 failure(&events, ErrorCode::Limit);
364 } else {
365 success(&events);
366 fs::remove_file(c.0.join("result.7z")).unwrap();
367 }
368 }
369 #[cfg(unix)]
370 {
371 std::os::unix::fs::symlink(c.0.join("source"), c.0.join("link")).unwrap();
372 failure(
373 &c.run(Message::Start(c.request(&["link"]))),
374 ErrorCode::UnsafePath,
375 );
376 }
377 assert!(!c.0.join("result.7z").exists());
378}
379
380#[test]
381fn guarded_approval_decline_and_cancel_preserve_creation_rules() {
382 let c = Case::new();
383 fs::write(c.0.join("source"), b"abcdef").unwrap();
384 for allow in [false, true] {
385 let mut start = c.request(&["source"]);
386 start.limits.output = 5;
387 let message = Message::StartGuarded(GuardedStart {
388 ceiling: Limits {
389 output: 6,
390 ..start.limits
391 },
392 start,
393 interactive: false,
394 });
395 let mut questions = 0;
396 let events = c.run_with(&mut c.command(), message, |event| {
397 if let Message::ResourceRequired {
398 challenge_id,
399 action,
400 scope,
401 ..
402 } = event
403 {
404 assert_eq!(*action, ActionKind::CreateSevenZip);
405 questions += 1;
406 vec![Message::ResourceReply {
407 challenge_id: *challenge_id,
408 scope: *scope,
409 allow,
410 }]
411 } else {
412 Vec::new()
413 }
414 });
415 assert_eq!(questions, 1);
416 if allow {
417 success(&events);
418 fs::remove_file(c.0.join("result.7z")).unwrap();
419 } else {
420 failure(&events, ErrorCode::None);
421 assert!(!c.0.join("result.7z").exists());
422 }
423 }
424}
425
426#[test]
427fn cancel_during_snapshot_or_encoding_publishes_nothing() {
428 for stage in [Stage::Read, Stage::Write] {
429 let c = Case::new();
430 fs::File::create(c.0.join("source"))
431 .unwrap()
432 .set_len(128 * 1024 * 1024)
433 .unwrap();
434 let mut sent = false;
435 let events = c.run_with(
436 &mut c.command(),
437 Message::Start(c.request(&["source"])),
438 |event| {
439 if !sent
440 && matches!(event, Message::Progress { stage: actual, processed_bytes, .. } if *actual == stage && (stage == Stage::Read || *processed_bytes > 0))
441 {
442 sent = true;
443 vec![Message::Cancel]
444 } else {
445 Vec::new()
446 }
447 },
448 );
449 assert!(sent);
450 failure(&events, ErrorCode::None);
451 assert!(!c.0.join("result.7z").exists());
452 assert!(events.iter().any(|e| matches!(
453 e,
454 Message::CancelAck {
455 status: CancelStatus::Requested,
456 ..
457 }
458 )));
459 }
460}
461
462#[cfg(target_os = "linux")]
463fn shim(c: &Case, file: &str) -> PathBuf {
464 let output = c.0.join("fault.so");
465 let status = Command::new("cc")
466 .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
467 .arg(
468 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
469 .join("../../tests/rust-archive-worker")
470 .join(file),
471 )
472 .args(["-ldl", "-o"])
473 .arg(&output)
474 .status()
475 .unwrap();
476 assert!(status.success());
477 output
478}
479
480#[cfg(target_os = "linux")]
481#[test]
482fn storage_failures_keep_real_publication_and_cleanup_state() {
483 for fault in [
484 "temp-full",
485 "space-stage",
486 "create-full",
487 "create-denied",
488 "full",
489 "write-io",
490 "sync-full",
491 "dir-sync-full",
492 ] {
493 let c = Case::new();
494 fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
495 let mut command = c.command();
496 command
497 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
498 .env("ZIPELO_TEST_FAULT", fault)
499 .env("ZIPELO_TEST_MARKER", c.0.join("marker"));
500 let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
501 Vec::new()
502 });
503 let error = if matches!(fault, "create-denied" | "write-io") {
504 ErrorCode::Io
505 } else {
506 ErrorCode::DiskFull
507 };
508 if fault == "dir-sync-full" {
509 let t = terminal(&events);
510 assert_eq!(t.error, error, "{events:?}");
511 assert_eq!(t.outcome, Outcome::Failed);
512 assert_eq!(t.created_count, 1);
513 assert_eq!(t.durability, Durability::Failed);
514 assert!(c.0.join("result.7z").is_file());
515 } else {
516 failure(&events, error);
517 assert!(!c.0.join("result.7z").exists());
518 }
519 assert!(!fs::read_dir(&c.0).unwrap().any(|entry| {
520 entry
521 .unwrap()
522 .file_name()
523 .to_string_lossy()
524 .starts_with(".zipelo-")
525 }));
526 }
527}
528
529#[cfg(target_os = "linux")]
530#[test]
531fn source_changes_new_destination_and_cancel_before_publication_are_preserved() {
532 for operation in ["source", "destination", "cancel"] {
533 let c = Case::new();
534 fs::write(c.0.join("source"), b"a".repeat(100_000)).unwrap();
535 let marker = c.0.join("marker");
536 let release = c.0.join("release");
537 let mut command = c.command();
538 command
539 .env("LD_PRELOAD", shim(&c, "io_fault.c"))
540 .env("ZIPELO_TEST_FAULT", "pause")
541 .env("ZIPELO_TEST_MARKER", &marker)
542 .env("ZIPELO_TEST_RELEASE", &release);
543 let mut changed = false;
544 let events = c.run_with(
545 &mut command,
546 Message::Start(c.request(&["source"])),
547 |event| {
548 if !changed
549 && matches!(
550 event,
551 Message::Progress {
552 stage: Stage::Write,
553 total_bytes: Some(_),
554 ..
555 }
556 )
557 {
558 let until = std::time::Instant::now() + Duration::from_secs(5);
559 while !marker.exists() {
560 assert!(std::time::Instant::now() < until);
561 std::thread::sleep(Duration::from_millis(2));
562 }
563 match operation {
564 "source" => fs::write(c.0.join("source"), b"changed").unwrap(),
565 "destination" => fs::write(c.0.join("result.7z"), b"user data").unwrap(),
566 _ => {}
567 }
568 changed = true;
569 let replies = if operation == "cancel" {
570 vec![Message::Cancel]
571 } else {
572 Vec::new()
573 };
574 fs::write(&release, b"resume").unwrap();
575 replies
576 } else {
577 Vec::new()
578 }
579 },
580 );
581 assert!(changed);
582 failure(
583 &events,
584 match operation {
585 "source" => ErrorCode::SourceChanged,
586 "destination" => ErrorCode::Conflict,
587 _ => ErrorCode::None,
588 },
589 );
590 if operation == "destination" {
591 assert_eq!(fs::read(c.0.join("result.7z")).unwrap(), b"user data");
592 } else {
593 assert!(!c.0.join("result.7z").exists());
594 }
595 }
596}
597
598#[cfg(target_os = "linux")]
599#[test]
600fn encoder_finish_header_write_seek_and_patch_errors_publish_nothing() {
601 for fault in [
602 "encode-full",
603 "finish-full",
604 "header-write",
605 "header-seek",
606 "header-patch",
607 ] {
608 let c = Case::new();
609 fs::write(
610 c.0.join("source"),
611 b"x".repeat(if fault == "encode-full" {
612 3 * 1024 * 1024
613 } else {
614 123
615 }),
616 )
617 .unwrap();
618 let mut command = c.command();
619 command
620 .env("LD_PRELOAD", shim(&c, "seven_zip_create_fault.c"))
621 .env("ZIPELO_7Z_FAULT", fault);
622 let events = c.run_with(&mut command, Message::Start(c.request(&["source"])), |_| {
623 Vec::new()
624 });
625 failure(
626 &events,
627 if fault.ends_with("full") {
628 ErrorCode::DiskFull
629 } else {
630 ErrorCode::Io
631 },
632 );
633 assert!(!c.0.join("result.7z").exists());
634 }
635}
636
637#[cfg(target_os = "linux")]
638#[test]
639fn gigabyte_creation_stays_below_64_mib_peak_rss() {
640 assert!(
641 Command::new("python3")
642 .arg(
643 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
644 .join("../../tests/rust-archive-worker/seven_zip_create_memory.py")
645 )
646 .arg(env!("CARGO_BIN_EXE_zipelo-archive-worker"))
647 .status()
648 .unwrap()
649 .success()
650 );
651}