team-ljyzipelo

공개

Merge pull request #132 from Team-LJY/fix/extract-spool-destination

압축 풀기 임시 파일을 풀 위치 폴더에 만들고 할당량 초과를 공간 부족으로 안내
작성자
LeeJunyoung
작성 시각
커밋
a7cc0f5c59a1c17ee58584009e6d6f1d20b99b76
이 시점의 파일 보기

변경된 파일 13개

+505-34
수정docs/ui-scenario-guide.md+3-0
@@ -66,6 +66,9 @@ cargo +1.99.1 build --locked --manifest-path experiments/rust-ui-memory-app/Carg
6666- create-complete: ZIP 만들기 완료. 압축 해제 완료와 다른 문구를 확인한다.
6767- folder-empty: 빈 하위 폴더. 목록의 빈 폴더 안내를 확인한다.
6868- gzip-conflict: 단일 GZ 이름 충돌. 다른 이름으로 저장 버튼과 안내를 확인한다.
69추가: - extract-disk-full: 압축 해제의 원본 사본 또는 단계 임시 파일을 쓰는 도중 디스크 공간이나 할당량이 부족한 상황입니다. 공간 확보 후 재시도 안내와 "아무 파일도 풀지 않았습니다"를 확인합니다. ZIP 만들기 화면이 아닌 압축 해제 실패 화면이어야 합니다.
70추가: - extract-complete-cleanup-failed: 압축 해제와 파일 저장은 완료됐지만 출력 폴더의 임시 파일 정리에 실패한 상황입니다. "압축을 풀었습니다"와 저장 위치를 유지하면서 임시 파일이 남을 수 있다는 경고가 함께 표시되는지 확인합니다. 해제 실패나 출력 없음으로 안내하지 않아야 합니다.
71추가: - extract-cleanup-failed: 압축 해제 실패 뒤 출력 폴더의 임시 파일 이름을 지우지 못한 상황입니다. 파일 접근 오류와 함께 풀 위치 폴더에 임시 파일이 남을 수 있다는 경고를 확인합니다. 게시된 파일이 없어도 정리 실패를 표시하며, "아무 파일도 풀지 않았습니다"로 잔여 파일이 없다고 단정하지 않아야 합니다.
6972- extract-partial: 일부 추출 후 실패. 이미 풀린 파일이 남는다는 경고를 확인한다.
7073- extract-uncertain: 저장 여부 불확실. 결과 확인을 권하는 경고를 확인한다.
7174- extract-unsynced: 완료 뒤 저장 확인 미완료. 완료 안내를 유지하고 자세히 보기에 경고가 있는지 확인한다.
수정experiments/rust-archive-worker/src/filesystem.rs+32-0
@@ -319,6 +319,34 @@ mod platform {
319319 pub fn create(&self, n: &str) -> std::io::Result<File> {
320320 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
321321 }
322추가: /// 이 폴더 안에 이름 없는 읽기/쓰기 임시 파일을 만듦. 마지막 핸들을 닫으면 제거됨.
323추가: pub(crate) fn temporary(&self) -> Result<File> {
324추가: // O_TMPFILE | O_EXCL: 이름이 생기지 않고 나중에 링크할 수도 없음.
325추가: match open(&self.file, std::ffi::OsStr::new("."), 2 | 0x410000 | 0x80) {
326추가: Ok(file) => return Ok(file),
327추가: Err(e) => {
328추가: if crate::space::io_error(e) == ErrorCode::DiskFull {
329추가: return Err(ErrorCode::DiskFull);
330추가: }
331추가: }
332추가: }
333추가: // O_TMPFILE을 지원하지 않는 파일 시스템은 숨김 이름으로 만든 즉시 이름을 지움.
334추가: let n = format!(".zipelo-{}.tmp", crate::spool::random_name()?);
335추가: let file = open(&self.file, std::ffi::OsStr::new(&n), 2 | 0x40 | 0x80)
336추가: .map_err(crate::space::io_error)?;
337추가: if !self.remove(&n) {
338추가: // 핸들을 닫고 한 번 더 지움. 그래도 남으면 정리 실패로 기록해 결과에 알림.
339추가: drop(file);
340추가: if !self.remove(&n) && !self.absent(&n).unwrap_or(false) {
341추가: crate::spool::note_leftover();
342추가: }
343추가: return Err(ErrorCode::Io);
344추가: }
345추가: if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
346추가: return Err(ErrorCode::Io);
347추가: }
348추가: Ok(file)
349추가: }
322350 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
323351 let a = CString::new(from).unwrap();
324352 let b = CString::new(to).unwrap();
@@ -478,6 +506,10 @@ mod platform {
478506 .custom_flags(0x00200000)
479507 .open(self.path.join(n))
480508 }
509추가: /// 이 폴더 안에 닫으면 지워지는 숨김 임시 파일을 만듦.
510추가: pub(crate) fn temporary(&self) -> Result<File> {
511추가: crate::spool::windows_temporary(&self.path, ".zipelo-", true)
512추가: }
481513 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
482514 std::fs::hard_link(self.path.join(a), self.path.join(b))
483515 }
수정experiments/rust-archive-worker/src/runtime.rs+15-0
@@ -586,6 +586,17 @@ impl<W: Write> Job<W> {
586586 return Err(ErrorCode::InvalidRequest);
587587 }
588588 }
589추가: // 해제의 원본 사본과 단계 임시 파일은 출력 폴더에 둠. 폴더를 열 수 없으면 기존 위치를
590추가: // 쓰고, 오류는 아래의 원래 출력 폴더 확인 지점에서 같은 순서로 보고함.
591추가: let _spool_location = match &start.action {
592추가: Action::Extract { destination, .. } => destination
593추가: .to_path()
594추가: .ok()
595추가: .and_then(|path| Dir::root(&path).ok())
596추가: .map(|root| crate::spool::place_in(&root))
597추가: .transpose()?,
598추가: _ => None,
599추가: };
589600 if let Some(budget) = &self.budget {
590601 let scope = ResourceScope {
591602 output: budget.ceiling.output > budget.soft.output,
@@ -1248,6 +1259,10 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
12481259 Some(ErrorCode::Internal)
12491260 }
12501261 };
1262추가: // 출력 폴더의 임시 파일 이름을 지우지 못했으면 남은 파일이 있다고 알림.
1263추가: if crate::spool::take_leftover() {
1264추가: context.terminal.cleanup = Cleanup::Failed;
1265추가: }
12511266 let mut state = state
12521267 .lock()
12531268 .map_err(|_| std::io::Error::other("worker state poisoned"))?;
수정experiments/rust-archive-worker/src/space.rs+7-3
@@ -123,13 +123,17 @@ pub(crate) fn available(file: &File) -> Result<u128> {
123123 Ok(free as u128)
124124}
125125
126삭제: // 공간 부족만 전용 오류로 변환함.
126추가: // 공간 부족만 전용 오류로 변환함. 사용자 디스크 할당량 초과(EDQUOT, Windows 1295)도
127추가: // 쓸 수 있는 공간이 없다는 뜻이므로 권한 오류가 아니라 공간 부족으로 알림.
127128pub(crate) fn io_error(error: std::io::Error) -> ErrorCode {
128129 #[cfg(windows)]
129삭제: if matches!(error.raw_os_error(), Some(39 | 112)) {
130추가: if matches!(error.raw_os_error(), Some(39 | 112 | 1295)) {
130131 return ErrorCode::DiskFull;
131132 }
132삭제: if error.kind() == std::io::ErrorKind::StorageFull {
133추가: if matches!(
134추가: error.kind(),
135추가: std::io::ErrorKind::StorageFull | std::io::ErrorKind::QuotaExceeded
136추가: ) {
133137 ErrorCode::DiskFull
134138 } else {
135139 ErrorCode::Io
수정experiments/rust-archive-worker/src/spool.rs+87-26
@@ -8,7 +8,71 @@ use std::{
88
99type Result<T> = std::result::Result<T, ErrorCode>;
1010
11추가: thread_local! {
12추가: // 작업 스레드가 지정한 임시 파일 위치. 없으면 시스템 임시 폴더를 사용함.
13추가: static LOCATION: std::cell::RefCell<Option<filesystem::Dir>> =
14추가: const { std::cell::RefCell::new(None) };
15추가: // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함.
16추가: static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
17추가: }
18추가:
19추가: /// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨.
20추가: /// 작업은 한 스레드에서 실행되므로 다른 작업이나 시험에 섞이지 않음.
21추가: pub(crate) struct Location(());
22추가: impl Drop for Location {
23추가: fn drop(&mut self) {
24추가: LOCATION.with(|location| *location.borrow_mut() = None);
25추가: }
26추가: }
27추가: pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
28추가: let dir = dir.duplicate()?;
29추가: LOCATION.with(|location| *location.borrow_mut() = Some(dir));
30추가: LEFTOVER.with(|leftover| leftover.set(false));
31추가: Ok(Location(()))
32추가: }
33추가:
34추가: /// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로
35추가: /// Linux 대체 이름 경로에서만 사용함.
36추가: #[cfg(target_os = "linux")]
37추가: pub(crate) fn note_leftover() {
38추가: LEFTOVER.with(|leftover| leftover.set(true));
39추가: }
40추가:
41추가: /// 작업 중 출력 폴더에 임시 파일이 남았는지 확인하고 기록을 비움.
42추가: pub(crate) fn take_leftover() -> bool {
43추가: LEFTOVER.with(|leftover| leftover.replace(false))
44추가: }
45추가:
46추가: pub(crate) fn random_name() -> Result<String> {
47추가: let mut random = [0; 16];
48추가: crate::crypto::random(&mut random)?;
49추가: Ok(random.iter().map(|b| format!("{b:02x}")).collect())
50추가: }
51추가:
52추가: /// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠.
53추가: /// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음.
54추가: /// 출력 폴더에 만들지 못하면(읽기 전용, 공간 부족 등) 이 작업의 남은 임시 파일은 모두
55추가: /// 기존 시스템 임시 폴더에 둠. 그러면 동작과 오류 우선순위가 이전과 같아지며, 출력 폴더
56추가: /// 문제는 원래의 출력 확인 지점에서 보고됨.
1157pub(crate) fn temporary() -> Result<File> {
58추가: let placed =
59추가: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary));
60추가: let destination_full = matches!(&placed, Some(Err(ErrorCode::DiskFull)));
61추가: match placed {
62추가: Some(Ok(file)) => return Ok(file),
63추가: Some(Err(_)) => LOCATION.with(|location| *location.borrow_mut() = None),
64추가: None => {}
65추가: }
66추가: system_temporary().map_err(|error| {
67추가: if destination_full {
68추가: ErrorCode::DiskFull
69추가: } else {
70추가: error
71추가: }
72추가: })
73추가: }
74추가:
75추가: fn system_temporary() -> Result<File> {
1276 #[cfg(target_os = "linux")]
1377 {
1478 use std::os::unix::fs::OpenOptionsExt;
@@ -21,17 +85,13 @@ pub(crate) fn temporary() -> Result<File> {
2185 .open(std::env::temp_dir())
2286 {
2387 Ok(file) => return Ok(file),
24삭제: Err(ref error) if error.kind() == std::io::ErrorKind::StorageFull => {
25삭제: return Err(ErrorCode::DiskFull);
88추가: Err(error) => {
89추가: if crate::space::io_error(error) == ErrorCode::DiskFull {
90추가: return Err(ErrorCode::DiskFull);
91추가: }
2692 }
27삭제: Err(_) => {}
2893 }
29삭제: let mut random = [0; 16];
30삭제: crate::crypto::random(&mut random)?;
31삭제: let name = random
32삭제: .iter()
33삭제: .map(|b| format!("{b:02x}"))
34삭제: .collect::<String>();
94추가: let name = random_name()?;
3595 let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp"));
3696 let file = OpenOptions::new()
3797 .read(true)
@@ -50,26 +110,27 @@ pub(crate) fn temporary() -> Result<File> {
50110 }
51111 #[cfg(windows)]
52112 {
53삭제: use std::os::windows::fs::OpenOptionsExt;
54삭제: let mut random = [0; 16];
55삭제: crate::crypto::random(&mut random)?;
56삭제: let name = random
57삭제: .iter()
58삭제: .map(|b| format!("{b:02x}"))
59삭제: .collect::<String>();
60삭제: OpenOptions::new()
61삭제: .read(true)
62삭제: .write(true)
63삭제: .create_new(true)
64삭제: .share_mode(0)
65삭제: .access_mode(0xc0010000)
66삭제: .custom_flags(0x04000000 | 0x00200000)
67삭제: .attributes(0x100)
68삭제: .open(std::env::temp_dir().join(format!("zipelo-{name}.tmp")))
69삭제: .map_err(crate::space::io_error)
113추가: windows_temporary(&std::env::temp_dir(), "zipelo-", false)
70114 }
71115}
72116
117추가: /// 닫으면 지워지는 Windows 임시 파일을 지정한 폴더에 만듦. 출력 폴더에서는 숨김 속성을 붙임.
118추가: #[cfg(windows)]
119추가: pub(crate) fn windows_temporary(parent: &Path, prefix: &str, hidden: bool) -> Result<File> {
120추가: use std::os::windows::fs::OpenOptionsExt;
121추가: let name = random_name()?;
122추가: OpenOptions::new()
123추가: .read(true)
124추가: .write(true)
125추가: .create_new(true)
126추가: .share_mode(0)
127추가: .access_mode(0xc0010000)
128추가: .custom_flags(0x04000000 | 0x00200000)
129추가: .attributes(if hidden { 0x100 | 0x2 } else { 0x100 })
130추가: .open(parent.join(format!("{prefix}{name}.tmp")))
131추가: .map_err(crate::space::io_error)
132추가: }
133추가:
73134#[derive(Clone, Copy, Debug)]
74135pub(crate) enum Step {
75136 Check,
수정experiments/rust-ui-memory-app/src/archive_screen.rs+3-1
@@ -2323,7 +2323,9 @@ impl ArchiveApp {
23232323 let success = self.model.confirmed
23242324 && self.model.error.is_none()
23252325 && t.as_ref().is_some_and(|t| t.outcome == Outcome::Completed)
2326삭제: && warnings.is_empty();
2326추가: && warnings
2327추가: .iter()
2328추가: .all(|warning| !creating && *warning == present::CLEANUP_WARNING);
23272329 let durability_warning = t
23282330 .as_ref()
23292331 .filter(|_| self.model.confirmed && !listing)
수정tests/rust-app-ui/scenario_tests.rs+72-0
@@ -164,6 +164,9 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() {
164164 "tar-bz2" | "tar-xz" => "읽어주세요.txt",
165165 "folder-empty" => "이 폴더는 비어 있습니다",
166166 "dialog-error" => "파일 선택 창을 열 수 없습니다",
167추가: "extract-complete-cleanup-failed" => "압축을 풀었습니다",
168추가: "extract-disk-full" => "디스크 여유 공간이 부족합니다",
169추가: "extract-cleanup-failed" => "풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다",
167170 "extract-partial" => "일부 파일만 풀렸습니다",
168171 "extract-uncertain" => "저장이 끝났는지 확인하지 못했습니다",
169172 "extract-unsynced" => "파일을 디스크에 완전히 저장했는지 확인하지 못했습니다",
@@ -190,6 +193,75 @@ fn every_listed_scenario_draws_and_keeps_its_expected_screen() {
190193 _ => "읽어주세요.txt",
191194 };
192195 assert!(labels.contains(expected), "{}: {labels}", scenario.name);
196추가: if scenario.name == "extract-complete-cleanup-failed" {
197추가: use zipelo_ui_memory_app::archive_ui::{
198추가: Cleanup, Disposition, Outcome, Publication,
199추가: };
200추가: let terminal = app.model.terminal.as_ref().unwrap();
201추가: assert!(app.model.confirmed);
202추가: assert_eq!(terminal.outcome, Outcome::Completed);
203추가: assert_eq!(terminal.error, None);
204추가: assert_eq!(terminal.publication, Publication::Complete);
205추가: assert_eq!(terminal.cleanup, Cleanup::Failed);
206추가: assert_eq!(terminal.created_count, app.model.outputs.len() as u64);
207추가: assert!(app
208추가: .model
209추가: .outputs
210추가: .iter()
211추가: .all(|(_, state)| *state == Disposition::Created));
212추가: assert!(labels.contains("폴더에 저장했습니다"), "{labels}");
213추가: assert!(labels.contains("임시 파일을 지우지 못했습니다"), "{labels}");
214추가: assert!(
215추가: labels.contains("풀 위치 폴더에 남은 임시 파일이 있을 수 있습니다"),
216추가: "{labels}"
217추가: );
218추가: assert!(!labels.contains("압축을 풀지 못했습니다"), "{labels}");
219추가: assert!(!labels.contains("아무 파일도 풀지 않았습니다"), "{labels}");
220추가: }
221추가: if matches!(
222추가: scenario.name,
223추가: "extract-disk-full" | "extract-cleanup-failed"
224추가: ) {
225추가: use zipelo_ui_memory_app::archive_ui::{Cleanup, ErrorCode, Outcome, Publication};
226추가: let cleanup_failed = scenario.name == "extract-cleanup-failed";
227추가: let terminal = app.model.terminal.as_ref().unwrap();
228추가: assert!(app.model.confirmed);
229추가: assert_eq!(terminal.outcome, Outcome::Failed);
230추가: assert_eq!(terminal.publication, Publication::None);
231추가: assert_eq!(terminal.created_count, 0);
232추가: assert_eq!(terminal.retained_partial_count, 0);
233추가: assert_eq!(
234추가: terminal.error,
235추가: Some(if cleanup_failed {
236추가: ErrorCode::Io
237추가: } else {
238추가: ErrorCode::DiskFull
239추가: })
240추가: );
241추가: assert_eq!(
242추가: terminal.cleanup,
243추가: if cleanup_failed {
244추가: Cleanup::Failed
245추가: } else {
246추가: Cleanup::Complete
247추가: }
248추가: );
249추가: assert!(labels.contains("압축을 풀지 못했습니다"), "{labels}");
250추가: assert!(!labels.contains("압축을 풀었습니다"), "{labels}");
251추가: assert_eq!(
252추가: labels.contains("임시 파일을 지우지 못했습니다"),
253추가: cleanup_failed
254추가: );
255추가: if cleanup_failed {
256추가: assert!(!labels.contains("아무 파일도 풀지 않았습니다"), "{labels}");
257추가: } else {
258추가: assert!(
259추가: labels.contains("공간을 확보한 뒤 다시 시도하세요"),
260추가: "{labels}"
261추가: );
262추가: assert!(labels.contains("아무 파일도 풀지 않았습니다"), "{labels}");
263추가: }
264추가: }
193265 if scenario.name == "extract-rename-failed" {
194266 assert!(labels.contains("파일을 읽거나 쓰지 못했습니다"), "{labels}");
195267 assert!(!labels.contains("이름 바꿔 저장:"), "{labels}");
수정tests/rust-app-ui/scenarios.rs+34-2
@@ -90,6 +90,9 @@ catalog! {
9090 "create-complete" => "ZIP 만들기 완료",
9191 "folder-empty" => "항목이 없는 하위 폴더",
9292 "gzip-conflict" => "단일 GZ 파일 이름 충돌",
93추가: "extract-disk-full" => "압축 해제 중 디스크 공간 또는 할당량 부족",
94추가: "extract-complete-cleanup-failed" => "압축 해제 완료와 출력 폴더의 임시 파일 정리 실패",
95추가: "extract-cleanup-failed" => "압축 해제 실패와 출력 폴더의 임시 파일 정리 실패",
9396 "extract-partial" => "일부 파일만 풀린 결과",
9497 "extract-uncertain" => "저장 여부를 확인할 수 없는 결과",
9598 "extract-unsynced" => "완료 뒤 저장 확인 경고의 상세 정보",
@@ -902,7 +905,8 @@ impl Scenario {
902905 "extract-complete"
903906 | "create-complete"
904907 | "create-sevenzip-complete"
905삭제: | "extract-unsynced" => {
908추가: | "extract-unsynced"
909추가: | "extract-complete-cleanup-failed" => {
906910 let names = app.targets.as_ref().unwrap();
907911 for name in names {
908912 state.frame(Event::Output {
@@ -922,7 +926,11 @@ impl Scenario {
922926 } else {
923927 Durability::Synced
924928 },
925삭제: cleanup: Cleanup::Complete,
929추가: cleanup: if self.name == "extract-complete-cleanup-failed" {
930추가: Cleanup::Failed
931추가: } else {
932추가: Cleanup::Complete
933추가: },
926934 }));
927935 state.queue.extend([
928936 HostEvent::StdoutEof,
@@ -961,6 +969,30 @@ impl Scenario {
961969 HostEvent::Exited { success: true },
962970 ]);
963971 }
972추가: "extract-disk-full" | "extract-cleanup-failed" => {
973추가: state.frame(Event::Terminal(Terminal {
974추가: outcome: Outcome::Failed,
975추가: error: Some(if self.name == "extract-disk-full" {
976추가: ErrorCode::DiskFull
977추가: } else {
978추가: ErrorCode::Io
979추가: }),
980추가: publication: Publication::None,
981추가: created_count: 0,
982추가: retained_partial_count: 0,
983추가: durability: Durability::NotApplicable,
984추가: cleanup: if self.name == "extract-cleanup-failed" {
985추가: Cleanup::Failed
986추가: } else {
987추가: Cleanup::Complete
988추가: },
989추가: }));
990추가: state.queue.extend([
991추가: HostEvent::StdoutEof,
992추가: HostEvent::StderrEof,
993추가: HostEvent::Exited { success: true },
994추가: ]);
995추가: }
964996 "conflict"
965997 | "gzip-conflict"
966998 | "unsupported"
수정tests/rust-archive-worker/hardening.rs+24-0
@@ -820,6 +820,30 @@ mod linux {
820820 assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
821821 assert!(s.0.join("paused").exists());
822822 assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
823추가: // 출력 폴더의 이름 있는 대체 임시 파일도 사용 전에 이름이 지워져야 함.
824추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 1);
825추가: assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
826추가: }
827추가: #[test]
828추가: fn destination_fallback_unlink_failure_reports_cleanup_and_moves_to_system_temp() {
829추가: let s = Scratch::new();
830추가: generate(&s, "store", 1024 * 1024);
831추가: let request = start(&s, false, Limits::default().output);
832추가: let child = spawn(&s, request, Some("fallback-unlink-denied"));
833추가: assert_eq!(wait(child.id()).0, 0);
834추가: let events = events(&s);
835추가: let t = terminal(&events);
836추가: // 이름을 지우지 못한 대체 임시 파일은 정리 실패로 알리고, 남은 작업은 시스템 임시 폴더에서 계속함.
837추가: assert_eq!(t.outcome, Outcome::Completed, "{events:?}");
838추가: assert_eq!(t.cleanup, Cleanup::Failed, "{events:?}");
839추가: assert!(s.0.join("paused").exists());
840추가: let leftovers = fs::read_dir(s.0.join("output"))
841추가: .unwrap()
842추가: .map(|entry| entry.unwrap().file_name().into_string().unwrap())
843추가: .filter(|name| name.starts_with(".zipelo-"))
844추가: .count();
845추가: assert_eq!(leftovers, 1, "첫 시도의 대체 임시 파일 하나만 남아야 함");
846추가: assert_eq!(fs::read_dir(s.0.join("staging")).unwrap().count(), 0);
823847 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
824848 }
825849 struct Subreaper(i32);
수정tests/rust-archive-worker/io_fault.c+36-1
@@ -26,6 +26,15 @@ __attribute__((constructor)) static void initialize(void) {
2626 real_fstatvfs = dlsym(RTLD_NEXT, "fstatvfs");
2727}
2828
29추가: /* 출력 폴더 임시 파일의 대체 이름(.zipelo-<hex 32>.tmp). 게시 임시 이름(.zipelo-<pid>-<n>.tmp)은 제외함. */
30추가: static int spool_name(const char *path) {
31추가: size_t length = strlen(path);
32추가: if (length != 44 || strncmp(path, ".zipelo-", 8) || strcmp(path + 40, ".tmp")) return 0;
33추가: for (size_t i = 8; i < 40; i++)
34추가: if (!strchr("0123456789abcdef", path[i])) return 0;
35추가: return 1;
36추가: }
37추가:
2938static int output_file(int fd) {
3039 char link[64], path[4096];
3140 snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
@@ -39,18 +48,40 @@ static int output_file(int fd) {
3948
4049int openat(int fd, const char *path, int flags, ...) {
4150 mode_t mode = 0;
42삭제: if (flags & O_CREAT) {
51추가: if ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE)) {
4352 va_list args;
4453 va_start(args, flags);
4554 mode = va_arg(args, unsigned int);
4655 va_end(args);
4756 }
4857 const char *fault = getenv("ZIPELO_TEST_FAULT");
58추가: if (fault && !strncmp(fault, "destination-", 12)
59추가: && (((flags & O_TMPFILE) == O_TMPFILE) || ((flags & O_CREAT) && spool_name(path)))) {
60추가: if (strstr(fault, "named") && (flags & O_TMPFILE) == O_TMPFILE) {
61추가: errno = EOPNOTSUPP;
62추가: } else {
63추가: errno = strstr(fault, "edquot") ? EDQUOT : strstr(fault, "denied") ? EACCES : ENOSPC;
64추가: }
65추가: return -1;
66추가: }
4967 if (fault && (!strcmp(fault, "create-full") || !strcmp(fault, "create-denied"))
5068 && !strncmp(path, ".zipelo-", 8)) {
5169 errno = !strcmp(fault, "create-full") ? ENOSPC : EACCES;
5270 return -1;
5371 }
72추가: /* 해제 작업의 원본 사본과 단계 임시 파일은 출력 폴더 핸들 기준 O_TMPFILE로 만듦. */
73추가: if ((flags & O_TMPFILE) == O_TMPFILE) {
74추가: if (fault && !strcmp(fault, "temp-full")) {
75추가: errno = ENOSPC;
76추가: return -1;
77추가: }
78추가: if (fault && (!strcmp(fault, "fallback") || !strcmp(fault, "fallback-unlink-denied"))) {
79추가: int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600);
80추가: if (marker >= 0) close(marker);
81추가: errno = EOPNOTSUPP;
82추가: return -1;
83추가: }
84추가: }
5485 return real_openat(fd, path, flags, mode);
5586}
5687
@@ -180,6 +211,10 @@ int unlinkat(int fd, const char *path, int flags) {
180211 errno = EACCES;
181212 return -1;
182213 }
214추가: if (fault && !strcmp(fault, "fallback-unlink-denied") && spool_name(path)) {
215추가: errno = EACCES;
216추가: return -1;
217추가: }
183218 int (*real_unlinkat)(int, const char *, int) = dlsym(RTLD_NEXT, "unlinkat");
184219 return real_unlinkat(fd, path, flags);
185220}
수정tests/rust-archive-worker/main.rs+3-0
@@ -1634,3 +1634,6 @@ mod recovery;
16341634
16351635#[cfg(target_os = "linux")]
16361636mod partial_output;
1637추가:
1638추가: #[cfg(target_os = "linux")]
1639추가: mod spool_location;
수정tests/rust-archive-worker/space_errors.rs+7-1
@@ -4,6 +4,10 @@ use std::io::{Error, ErrorKind};
44#[test]
55fn storage_full_is_distinct_from_other_io_errors() {
66 assert_eq!(io_error(ErrorKind::StorageFull.into()), ErrorCode::DiskFull);
7추가: assert_eq!(
8추가: io_error(ErrorKind::QuotaExceeded.into()),
9추가: ErrorCode::DiskFull
10추가: );
711 for kind in [
812 ErrorKind::PermissionDenied,
913 ErrorKind::Other,
@@ -17,6 +21,8 @@ fn storage_full_is_distinct_from_other_io_errors() {
1721#[test]
1822fn native_linux_enospc_is_disk_full() {
1923 assert_eq!(io_error(Error::from_raw_os_error(28)), ErrorCode::DiskFull);
24추가: // EDQUOT: tmpfs usrquota 등 사용자 할당량 초과도 권한 오류로 안내하지 않음.
25추가: assert_eq!(io_error(Error::from_raw_os_error(122)), ErrorCode::DiskFull);
2026 for code in [5, 13, 39, 112] {
2127 assert_eq!(io_error(Error::from_raw_os_error(code)), ErrorCode::Io);
2228 }
@@ -25,7 +31,7 @@ fn native_linux_enospc_is_disk_full() {
2531#[cfg(windows)]
2632#[test]
2733fn native_windows_disk_full_codes_are_distinct_from_access_denied() {
28삭제: for code in [39, 112] {
34추가: for code in [39, 112, 1295] {
2935 assert_eq!(
3036 io_error(Error::from_raw_os_error(code)),
3137 ErrorCode::DiskFull
추가tests/rust-archive-worker/spool_location.rs+182-0
@@ -0,0 +1,182 @@
1추가: use super::*;
2추가:
3추가: // 해제 작업의 원본 사본과 단계 임시 파일은 시스템 임시 폴더가 아니라 출력 폴더에 둠.
4추가: // 시스템 임시 폴더를 쓸 수 없게 만들어도(/tmp 할당량 초과와 같은 상황) 해제가 성공해야 함.
5추가: fn extract_without_system_temp(bytes: &[u8]) -> (Scratch, Vec<Message>) {
6추가: extract_unusable_system_temp(bytes, None, false)
7추가: }
8추가: fn extract_unusable_system_temp(
9추가: bytes: &[u8],
10추가: fault: Option<&str>,
11추가: file_at_temp_path: bool,
12추가: ) -> (Scratch, Vec<Message>) {
13추가: let s = Scratch::new();
14추가: let start = encrypted_start(&s, bytes);
15추가: let temp = s.0.join("missing-temp");
16추가: if file_at_temp_path {
17추가: fs::write(&temp, b"keep").unwrap();
18추가: }
19추가: let mut command = s.worker();
20추가: command.env("TMPDIR", &temp);
21추가: if let Some(fault) = fault {
22추가: let shim = s.0.join("io_fault.so");
23추가: assert!(
24추가: Command::new("cc")
25추가: .args(["-shared", "-fPIC", "-O2", "-Wall", "-Wextra", "-Werror"])
26추가: .arg(
27추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28추가: .join("../../tests/rust-archive-worker/io_fault.c")
29추가: )
30추가: .args(["-ldl", "-o"])
31추가: .arg(&shim)
32추가: .status()
33추가: .unwrap()
34추가: .success()
35추가: );
36추가: command
37추가: .env("LD_PRELOAD", shim)
38추가: .env("ZIPELO_TEST_FAULT", fault);
39추가: }
40추가: let mut child = command
41추가: .stdin(Stdio::piped())
42추가: .stdout(Stdio::piped())
43추가: .stderr(Stdio::piped())
44추가: .spawn()
45추가: .unwrap();
46추가: let mut writer = Some(Writer::new(child.stdin.take().unwrap(), 17));
47추가: writer
48추가: .as_mut()
49추가: .unwrap()
50추가: .send(&Message::StartInteractive(start))
51추가: .unwrap();
52추가: let mut reader = Reader::new(child.stdout.take().unwrap());
53추가: let mut events = Vec::new();
54추가: while let Some((job, _, event)) = reader.read().unwrap() {
55추가: assert_eq!(job, 17);
56추가: if let Message::PasswordRequired { challenge_id, .. } = &event {
57추가: for reply in password_reply(*challenge_id, TEST_PASSWORD) {
58추가: writer.as_mut().unwrap().send(&reply).unwrap();
59추가: }
60추가: }
61추가: if matches!(event, Message::Terminal(_)) {
62추가: writer = None;
63추가: }
64추가: events.push(event);
65추가: }
66추가: drop(writer);
67추가: let output = child.wait_with_output().unwrap();
68추가: assert!(output.status.success(), "{:?}", output.stderr);
69추가: assert!(output.stderr.is_empty());
70추가: if file_at_temp_path {
71추가: assert_eq!(fs::read(&temp).unwrap(), b"keep");
72추가: } else {
73추가: assert!(!temp.exists());
74추가: }
75추가: (s, events)
76추가: }
77추가:
78추가: fn assert_only_outputs(s: &Scratch, expected: &[&str]) {
79추가: let mut names = fs::read_dir(s.0.join("output"))
80추가: .unwrap()
81추가: .map(|entry| entry.unwrap().file_name().into_string().unwrap())
82추가: .collect::<Vec<_>>();
83추가: names.sort();
84추가: assert_eq!(names, expected, "임시 파일이 출력 폴더에 남으면 안 됨");
85추가: }
86추가:
87추가: #[test]
88추가: fn extract_spools_in_destination_when_system_temp_is_unusable() {
89추가: let (s, events) = extract_without_system_temp(include_bytes!("fixtures/deflate.zip"));
90추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
91추가: assert_eq!(terminal(&events).publication, Publication::Complete);
92추가: assert_eq!(
93추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
94추가: PAYLOAD
95추가: );
96추가: assert_only_outputs(&s, &["empty", "folder"]);
97추가: }
98추가:
99추가: #[test]
100추가: fn encrypted_extract_spools_in_destination_when_system_temp_is_unusable() {
101추가: let (s, events) = extract_without_system_temp(AES_ZIP);
102추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
103추가: assert_eq!(
104추가: fs::read(s.0.join("output/payload.bin")).unwrap(),
105추가: ENCRYPTED_PAYLOAD
106추가: );
107추가: assert_only_outputs(&s, &["payload.bin"]);
108추가: }
109추가:
110추가: #[test]
111추가: fn corrupt_archive_error_wins_over_read_only_destination() {
112추가: // 출력 폴더에 임시 파일을 만들 수 없으면 시스템 임시 폴더를 써서 기존 오류 우선순위를 유지함.
113추가: // 손상된 압축파일은 권한 문제가 아니라 손상으로 안내해야 함.
114추가: let bytes = seven_fixture("bad-trailing.7z");
115추가: let writable = Scratch::new();
116추가: let baseline = extract(
117추가: &writable,
118추가: &bytes,
119추가: None,
120추가: Selection::All,
121추가: None,
122추가: Limits::default(),
123추가: );
124추가: assert_eq!(terminal(&baseline).error, ErrorCode::Integrity);
125추가:
126추가: use std::os::unix::fs::PermissionsExt;
127추가: let s = Scratch::new();
128추가: let output = s.0.join("output");
129추가: fs::create_dir(&output).unwrap();
130추가: fs::set_permissions(&output, fs::Permissions::from_mode(0o500)).unwrap();
131추가: let events = extract(&s, &bytes, None, Selection::All, None, Limits::default());
132추가: fs::set_permissions(&output, fs::Permissions::from_mode(0o700)).unwrap();
133추가: assert_eq!(terminal(&events).error, ErrorCode::Integrity, "{events:?}");
134추가: assert_eq!(terminal(&events).publication, Publication::None);
135추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
136추가: assert_eq!(fs::read_dir(&output).unwrap().count(), 0);
137추가: }
138추가:
139추가: #[test]
140추가: fn destination_space_or_quota_failure_survives_unusable_system_temp() {
141추가: let input = include_bytes!("fixtures/deflate.zip");
142추가: for fault in [
143추가: "destination-enospc",
144추가: "destination-edquot",
145추가: "destination-named-enospc",
146추가: "destination-named-edquot",
147추가: ] {
148추가: for file in [false, true] {
149추가: let (s, events) = extract_unusable_system_temp(input, Some(fault), file);
150추가: let terminal = terminal(&events);
151추가: assert_eq!(
152추가: terminal.outcome,
153추가: Outcome::Failed,
154추가: "{fault}/{file}: {events:?}"
155추가: );
156추가: assert_eq!(
157추가: terminal.error,
158추가: ErrorCode::DiskFull,
159추가: "{fault}/{file}: {events:?}"
160추가: );
161추가: assert_eq!(terminal.publication, Publication::None);
162추가: assert_eq!(terminal.cleanup, Cleanup::Complete);
163추가: assert_eq!(terminal.created_count, 0);
164추가: assert_only_outputs(&s, &[]);
165추가: assert_eq!(fs::read(s.0.join("input")).unwrap(), input);
166추가: }
167추가: }
168추가: }
169추가:
170추가: #[test]
171추가: fn destination_permission_failure_with_unusable_system_temp_stays_io() {
172추가: for file in [false, true] {
173추가: let (s, events) = extract_unusable_system_temp(
174추가: include_bytes!("fixtures/deflate.zip"),
175추가: Some("destination-denied"),
176추가: file,
177추가: );
178추가: assert_eq!(terminal(&events).error, ErrorCode::Io, "{events:?}");
179추가: assert_eq!(terminal(&events).outcome, Outcome::Failed);
180추가: assert_only_outputs(&s, &[]);
181추가: }
182추가: }