team-ljyzipelo

공개

압축 풀기 임시 파일을 풀 위치 폴더에 만들고 할당량 초과를 공간 부족으로 안내

압축 풀기는 원본 사본과 단계 임시 파일을 시스템 임시 폴더(/tmp)에 만들었다.
/tmp가 사용자 할당량이 있는 tmpfs이면 큰 압축파일에서 쓰기가 EDQUOT로 실패했고,
이 오류가 Io로 분류되어 "접근 권한을 확인하세요"라는 잘못된 안내가 나왔다.

- 압축 풀기 작업 동안 spool::temporary()가 풀 위치 폴더에 임시 파일을 만든다.
  Linux는 O_TMPFILE, 미지원 파일 시스템은 숨김 이름으로 만든 즉시 unlink,
  Windows는 숨김 delete-on-close 파일을 쓴다. 폴더를 미리 열 수 없으면 기존
  위치를 쓰고 오류는 원래 지점에서 같은 순서로 보고한다.
- EDQUOT/QuotaExceeded와 Windows 1295를 DiskFull로 변환한다.
- 시스템 임시 폴더를 쓸 수 없어도 해제가 성공하고 출력 폴더에 임시 파일이
  남지 않는지 시험한다. io_fault 주입기를 새 위치의 O_TMPFILE에도 적용한다.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
작성자
LeeJunyoung
작성 시각
커밋
97cc56315c3418756383d7fbdba0b42fbf7167da
부모
5d0afa5
이 시점의 파일 보기

변경된 파일 9개

+201-31
수정experiments/rust-archive-worker/src/filesystem.rs+27-0
@@ -319,6 +319,29 @@ 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추가: return Err(ErrorCode::Io);
339추가: }
340추가: if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
341추가: return Err(ErrorCode::Io);
342추가: }
343추가: Ok(file)
344추가: }
322345 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
323346 let a = CString::new(from).unwrap();
324347 let b = CString::new(to).unwrap();
@@ -478,6 +501,10 @@ mod platform {
478501 .custom_flags(0x00200000)
479502 .open(self.path.join(n))
480503 }
504추가: /// 이 폴더 안에 닫으면 지워지는 숨김 임시 파일을 만듦.
505추가: pub(crate) fn temporary(&self) -> Result<File> {
506추가: crate::spool::windows_temporary(&self.path, ".zipelo-", true)
507추가: }
481508 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
482509 std::fs::hard_link(self.path.join(a), self.path.join(b))
483510 }
수정experiments/rust-archive-worker/src/runtime.rs+11-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,
수정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+56-26
@@ -8,7 +8,40 @@ 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추가:
17추가: /// 해제 작업의 임시 파일을 출력 폴더에 두도록 지정함. 반환값이 사라지면 해제됨.
18추가: /// 작업은 한 스레드에서 실행되므로 다른 작업이나 시험에 섞이지 않음.
19추가: pub(crate) struct Location(());
20추가: impl Drop for Location {
21추가: fn drop(&mut self) {
22추가: LOCATION.with(|location| *location.borrow_mut() = None);
23추가: }
24추가: }
25추가: pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
26추가: let dir = dir.duplicate()?;
27추가: LOCATION.with(|location| *location.borrow_mut() = Some(dir));
28추가: Ok(Location(()))
29추가: }
30추가:
31추가: pub(crate) fn random_name() -> Result<String> {
32추가: let mut random = [0; 16];
33추가: crate::crypto::random(&mut random)?;
34추가: Ok(random.iter().map(|b| format!("{b:02x}")).collect())
35추가: }
36추가:
37추가: /// 이름 없는 임시 파일을 만듦. 해제 작업에서는 출력 폴더에, 그 외에는 시스템 임시 폴더에 둠.
38추가: /// 출력 폴더에 두면 공간 판단이 실제 출력 디스크와 같아지고 /tmp 크기나 할당량에 묶이지 않음.
1139pub(crate) fn temporary() -> Result<File> {
40추가: if let Some(file) =
41추가: LOCATION.with(|location| location.borrow().as_ref().map(filesystem::Dir::temporary))
42추가: {
43추가: return file;
44추가: }
1245 #[cfg(target_os = "linux")]
1346 {
1447 use std::os::unix::fs::OpenOptionsExt;
@@ -21,17 +54,13 @@ pub(crate) fn temporary() -> Result<File> {
2154 .open(std::env::temp_dir())
2255 {
2356 Ok(file) => return Ok(file),
24삭제: Err(ref error) if error.kind() == std::io::ErrorKind::StorageFull => {
25삭제: return Err(ErrorCode::DiskFull);
57추가: Err(error) => {
58추가: if crate::space::io_error(error) == ErrorCode::DiskFull {
59추가: return Err(ErrorCode::DiskFull);
60추가: }
2661 }
27삭제: Err(_) => {}
2862 }
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>();
63추가: let name = random_name()?;
3564 let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp"));
3665 let file = OpenOptions::new()
3766 .read(true)
@@ -50,26 +79,27 @@ pub(crate) fn temporary() -> Result<File> {
5079 }
5180 #[cfg(windows)]
5281 {
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)
82추가: windows_temporary(&std::env::temp_dir(), "zipelo-", false)
7083 }
7184}
7285
86추가: /// 닫으면 지워지는 Windows 임시 파일을 지정한 폴더에 만듦. 출력 폴더에서는 숨김 속성을 붙임.
87추가: #[cfg(windows)]
88추가: pub(crate) fn windows_temporary(parent: &Path, prefix: &str, hidden: bool) -> Result<File> {
89추가: use std::os::windows::fs::OpenOptionsExt;
90추가: let name = random_name()?;
91추가: OpenOptions::new()
92추가: .read(true)
93추가: .write(true)
94추가: .create_new(true)
95추가: .share_mode(0)
96추가: .access_mode(0xc0010000)
97추가: .custom_flags(0x04000000 | 0x00200000)
98추가: .attributes(if hidden { 0x100 | 0x2 } else { 0x100 })
99추가: .open(parent.join(format!("{prefix}{name}.tmp")))
100추가: .map_err(crate::space::io_error)
101추가: }
102추가:
73103#[derive(Clone, Copy, Debug)]
74104pub(crate) enum Step {
75105 Check,
수정tests/rust-archive-worker/hardening.rs+2-0
@@ -820,6 +820,8 @@ 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);
823825 assert_zero_file(&s.0.join("output/payload.bin"), 1024 * 1024);
824826 }
825827 struct Subreaper(i32);
수정tests/rust-archive-worker/io_fault.c+14-1
@@ -39,7 +39,7 @@ static int output_file(int fd) {
3939
4040int openat(int fd, const char *path, int flags, ...) {
4141 mode_t mode = 0;
42삭제: if (flags & O_CREAT) {
42추가: if ((flags & O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE)) {
4343 va_list args;
4444 va_start(args, flags);
4545 mode = va_arg(args, unsigned int);
@@ -51,6 +51,19 @@ int openat(int fd, const char *path, int flags, ...) {
5151 errno = !strcmp(fault, "create-full") ? ENOSPC : EACCES;
5252 return -1;
5353 }
54추가: /* 해제 작업의 원본 사본과 단계 임시 파일은 출력 폴더 핸들 기준 O_TMPFILE로 만듦. */
55추가: if ((flags & O_TMPFILE) == O_TMPFILE) {
56추가: if (fault && !strcmp(fault, "temp-full")) {
57추가: errno = ENOSPC;
58추가: return -1;
59추가: }
60추가: if (fault && !strcmp(fault, "fallback")) {
61추가: int marker = real_openat(AT_FDCWD, getenv("ZIPELO_TEST_MARKER"), O_CREAT | O_WRONLY, 0600);
62추가: if (marker >= 0) close(marker);
63추가: errno = EOPNOTSUPP;
64추가: return -1;
65추가: }
66추가: }
5467 return real_openat(fd, path, flags, mode);
5568}
5669
수정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+74-0
@@ -0,0 +1,74 @@
1추가: use super::*;
2추가:
3추가: // 해제 작업의 원본 사본과 단계 임시 파일은 시스템 임시 폴더가 아니라 출력 폴더에 둠.
4추가: // 시스템 임시 폴더를 쓸 수 없게 만들어도(/tmp 할당량 초과와 같은 상황) 해제가 성공해야 함.
5추가: fn extract_without_system_temp(bytes: &[u8]) -> (Scratch, Vec<Message>) {
6추가: let s = Scratch::new();
7추가: let start = encrypted_start(&s, bytes);
8추가: let mut child = s
9추가: .worker()
10추가: .env("TMPDIR", s.0.join("missing-temp"))
11추가: .stdin(Stdio::piped())
12추가: .stdout(Stdio::piped())
13추가: .stderr(Stdio::piped())
14추가: .spawn()
15추가: .unwrap();
16추가: let mut writer = Some(Writer::new(child.stdin.take().unwrap(), 17));
17추가: writer
18추가: .as_mut()
19추가: .unwrap()
20추가: .send(&Message::StartInteractive(start))
21추가: .unwrap();
22추가: let mut reader = Reader::new(child.stdout.take().unwrap());
23추가: let mut events = Vec::new();
24추가: while let Some((job, _, event)) = reader.read().unwrap() {
25추가: assert_eq!(job, 17);
26추가: if let Message::PasswordRequired { challenge_id, .. } = &event {
27추가: for reply in password_reply(*challenge_id, TEST_PASSWORD) {
28추가: writer.as_mut().unwrap().send(&reply).unwrap();
29추가: }
30추가: }
31추가: if matches!(event, Message::Terminal(_)) {
32추가: writer = None;
33추가: }
34추가: events.push(event);
35추가: }
36추가: drop(writer);
37추가: let output = child.wait_with_output().unwrap();
38추가: assert!(output.status.success(), "{:?}", output.stderr);
39추가: assert!(output.stderr.is_empty());
40추가: assert!(!s.0.join("missing-temp").exists());
41추가: (s, events)
42추가: }
43추가:
44추가: fn assert_only_outputs(s: &Scratch, expected: &[&str]) {
45추가: let mut names = fs::read_dir(s.0.join("output"))
46추가: .unwrap()
47추가: .map(|entry| entry.unwrap().file_name().into_string().unwrap())
48추가: .collect::<Vec<_>>();
49추가: names.sort();
50추가: assert_eq!(names, expected, "임시 파일이 출력 폴더에 남으면 안 됨");
51추가: }
52추가:
53추가: #[test]
54추가: fn extract_spools_in_destination_when_system_temp_is_unusable() {
55추가: let (s, events) = extract_without_system_temp(include_bytes!("fixtures/deflate.zip"));
56추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
57추가: assert_eq!(terminal(&events).publication, Publication::Complete);
58추가: assert_eq!(
59추가: fs::read(s.0.join("output/folder/hello.txt")).unwrap(),
60추가: PAYLOAD
61추가: );
62추가: assert_only_outputs(&s, &["empty", "folder"]);
63추가: }
64추가:
65추가: #[test]
66추가: fn encrypted_extract_spools_in_destination_when_system_temp_is_unusable() {
67추가: let (s, events) = extract_without_system_temp(AES_ZIP);
68추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
69추가: assert_eq!(
70추가: fs::read(s.0.join("output/payload.bin")).unwrap(),
71추가: ENCRYPTED_PAYLOAD
72추가: );
73추가: assert_only_outputs(&s, &["payload.bin"]);
74추가: }