team-ljyzipelo

공개

임시 폴더 내용을 열어 둔 핸들에 묶어 지움

작성자
호시노 히나타
작성 시각
커밋
554fee1fce15748035d7292de6d12963b88a76c7
부모
b332764
이 시점의 파일 보기

변경된 파일 5개

+291-6
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -16,6 +16,7 @@ mod space;
1616mod split_seven_zip;
1717mod spool;
1818mod streaming;
19추가: pub mod tree_remove;
1920pub mod wire;
2021mod zip_recovery;
2122
추가experiments/rust-archive-worker/src/tree_remove.rs+180-0
@@ -0,0 +1,180 @@
1추가: //! 열어 둔 폴더 핸들에 묶어서 폴더 안의 내용을 지움.
2추가: //! 경로를 다시 해석하지 않으므로 확인한 뒤 경로가 바뀌어도 다른 폴더를 지우지 않음.
3추가:
4추가: use std::fs::File;
5추가: use std::io;
6추가: use std::path::Path;
7추가:
8추가: /// `dir` 핸들이 가리키는 폴더 안의 모든 항목을 지움. 폴더 자체는 지우지 않음.
9추가: /// Linux는 핸들 기준 `unlinkat`으로 지우며 `path`는 쓰지 않음.
10추가: /// Windows는 호출한 쪽이 공유 삭제를 허용하지 않고 `dir`을 열어 두어 폴더 이름이
11추가: /// 바뀌지 않게 한 상태에서만 `path`를 씀.
12추가: pub fn remove_contents(dir: &File, path: &Path) -> io::Result<()> {
13추가: platform::remove_contents(dir, path)
14추가: }
15추가:
16추가: #[cfg(target_os = "linux")]
17추가: mod platform {
18추가: use std::ffi::{CStr, CString};
19추가: use std::fs::File;
20추가: use std::io;
21추가: use std::os::unix::{
22추가: fs::MetadataExt,
23추가: io::{AsRawFd, FromRawFd},
24추가: };
25추가: use std::path::Path;
26추가:
27추가: #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
28추가: const NOFOLLOW_DIRECTORY: i32 = 0x8000 | 0x4000;
29추가: #[cfg(not(any(target_arch = "aarch64", target_arch = "arm")))]
30추가: const NOFOLLOW_DIRECTORY: i32 = 0x20000 | 0x10000;
31추가: const CLOEXEC: i32 = 0x80000;
32추가: const AT_REMOVEDIR: i32 = 0x200;
33추가: const ENOENT: i32 = 2;
34추가: const EPERM: i32 = 1;
35추가: const EISDIR: i32 = 21;
36추가: /// 깊게 중첩된 폴더에서 파일 디스크립터가 바닥나지 않게 하는 한도.
37추가: const MAX_DEPTH: usize = 256;
38추가:
39추가: #[repr(C)]
40추가: struct Dirent64 {
41추가: inode: u64,
42추가: offset: i64,
43추가: length: u16,
44추가: kind: u8,
45추가: name: [i8; 256],
46추가: }
47추가:
48추가: unsafe extern "C" {
49추가: fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
50추가: fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
51추가: fn fdopendir(fd: i32) -> *mut std::ffi::c_void;
52추가: fn readdir64(stream: *mut std::ffi::c_void) -> *mut Dirent64;
53추가: fn rewinddir(stream: *mut std::ffi::c_void);
54추가: fn closedir(stream: *mut std::ffi::c_void) -> i32;
55추가: }
56추가:
57추가: pub fn remove_contents(dir: &File, _path: &Path) -> io::Result<()> {
58추가: let device = dir.metadata()?.dev();
59추가: remove_children(dir, device, 0)
60추가: }
61추가:
62추가: fn names(dir: &File) -> io::Result<Vec<CString>> {
63추가: let copy = dir.try_clone()?;
64추가: let fd = std::os::unix::io::IntoRawFd::into_raw_fd(copy);
65추가: // 복제한 디스크립터의 소유권은 폴더 스트림이 가져가며 closedir이 닫음.
66추가: let stream = unsafe { fdopendir(fd) };
67추가: if stream.is_null() {
68추가: let error = io::Error::last_os_error();
69추가: // 스트림을 만들지 못했으므로 복제한 디스크립터를 직접 돌려받아 닫음.
70추가: drop(unsafe { File::from_raw_fd(fd) });
71추가: return Err(error);
72추가: }
73추가: // 복제한 디스크립터는 원본과 읽기 위치를 공유하므로 처음부터 읽음.
74추가: unsafe { rewinddir(stream) };
75추가: let mut found = Vec::new();
76추가: loop {
77추가: let entry = unsafe { readdir64(stream) };
78추가: if entry.is_null() {
79추가: break;
80추가: }
81추가: // 반환된 항목은 다음 readdir64 호출 전까지 유효하며 바로 복사함.
82추가: let name = unsafe { CStr::from_ptr((*entry).name.as_ptr()) };
83추가: let bytes = name.to_bytes();
84추가: if bytes != b"." && bytes != b".." {
85추가: found.push(name.to_owned());
86추가: }
87추가: }
88추가: unsafe { closedir(stream) };
89추가: Ok(found)
90추가: }
91추가:
92추가: fn unlink(dir: &File, name: &CString, flags: i32) -> io::Result<()> {
93추가: // 부모 핸들 기준으로 이름 하나만 지움.
94추가: if unsafe { unlinkat(dir.as_raw_fd(), name.as_ptr(), flags) } == 0 {
95추가: Ok(())
96추가: } else {
97추가: Err(io::Error::last_os_error())
98추가: }
99추가: }
100추가:
101추가: fn open_directory(dir: &File, name: &CString) -> io::Result<File> {
102추가: // 심볼릭 링크를 따르지 않고 폴더만 부모 핸들 기준으로 엶.
103추가: let fd = unsafe {
104추가: openat(
105추가: dir.as_raw_fd(),
106추가: name.as_ptr(),
107추가: NOFOLLOW_DIRECTORY | CLOEXEC,
108추가: )
109추가: };
110추가: if fd < 0 {
111추가: return Err(io::Error::last_os_error());
112추가: }
113추가: Ok(unsafe { File::from_raw_fd(fd) })
114추가: }
115추가:
116추가: fn remove_children(dir: &File, device: u64, depth: usize) -> io::Result<()> {
117추가: let mut failure = None;
118추가: for name in names(dir)? {
119추가: if let Err(error) = remove_entry(dir, &name, device, depth) {
120추가: if error.raw_os_error() != Some(ENOENT) {
121추가: failure.get_or_insert(error);
122추가: }
123추가: }
124추가: }
125추가: failure.map_or(Ok(()), Err)
126추가: }
127추가:
128추가: fn remove_entry(dir: &File, name: &CString, device: u64, depth: usize) -> io::Result<()> {
129추가: match unlink(dir, name, 0) {
130추가: Ok(()) => return Ok(()),
131추가: Err(error) if matches!(error.raw_os_error(), Some(EISDIR | EPERM)) => {}
132추가: Err(error) => return Err(error),
133추가: }
134추가: if depth >= MAX_DEPTH {
135추가: return Err(io::Error::other("폴더가 너무 깊음"));
136추가: }
137추가: let child = match open_directory(dir, name) {
138추가: Ok(child) => child,
139추가: // 그 사이 폴더가 아닌 항목으로 바뀌었으면 항목 자체를 지움.
140추가: Err(_) => return unlink(dir, name, 0),
141추가: };
142추가: // 다른 파일 시스템이 연결된 폴더 안은 지우지 않음.
143추가: if child.metadata()?.dev() != device {
144추가: return Err(io::Error::other("다른 파일 시스템의 폴더"));
145추가: }
146추가: remove_children(&child, device, depth + 1)?;
147추가: drop(child);
148추가: unlink(dir, name, AT_REMOVEDIR)
149추가: }
150추가: }
151추가:
152추가: #[cfg(windows)]
153추가: mod platform {
154추가: use std::fs::{self, File};
155추가: use std::io;
156추가: use std::path::Path;
157추가:
158추가: pub fn remove_contents(_dir: &File, path: &Path) -> io::Result<()> {
159추가: let mut failure = None;
160추가: // 호출한 쪽의 핸들이 폴더 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
161추가: for entry in fs::read_dir(path)? {
162추가: let result = entry.and_then(|entry| {
163추가: let path = entry.path();
164추가: let kind = fs::symlink_metadata(&path)?.file_type();
165추가: if kind.is_symlink() {
166추가: // 링크는 따라가지 않고 링크 자체만 지움.
167추가: fs::remove_file(&path).or_else(|_| fs::remove_dir(&path))
168추가: } else if kind.is_dir() {
169추가: fs::remove_dir_all(&path)
170추가: } else {
171추가: fs::remove_file(&path)
172추가: }
173추가: });
174추가: if let Err(error) = result {
175추가: failure.get_or_insert(error);
176추가: }
177추가: }
178추가: failure.map_or(Ok(()), Err)
179추가: }
180추가: }
수정experiments/rust-ui-memory-app/src/archive_present.rs+20-5
@@ -547,7 +547,8 @@ fn open_root_handle(path: &Path) -> io::Result<fs::File> {
547547 {
548548 use std::os::windows::fs::OpenOptionsExt;
549549 // 폴더 자체를 열며 재분석 지점을 따라가지 않음.
550삭제: options.custom_flags(0x02000000 | 0x00200000);
550추가: // 삭제 공유를 허용하지 않아 열어 둔 동안 폴더 이름을 바꾸거나 지울 수 없게 함.
551추가: options.share_mode(1 | 2).custom_flags(0x02000000 | 0x00200000);
551552 }
552553 let file = options.open(path)?;
553554 let metadata = file.metadata()?;
@@ -597,10 +598,24 @@ pub fn open_root_name(archive_name: &str) -> String {
597598}
598599
599600/// 이 앱이 만든 열기용 폴더를 지움. 다른 프로그램이 파일을 쓰고 있으면 남을 수 있음.
600삭제: pub fn remove_open_root(root: &OpenRoot) {
601삭제: if root.is_current() {
602삭제: let _ = fs::remove_dir_all(root.path());
603삭제: }
601추가: pub fn remove_open_root(root: OpenRoot) {
602추가: remove_open_root_with(root, || {});
603추가: }
604추가:
605추가: /// `remove_open_root`와 같고, 정체를 확인한 직후 삭제 전에 `after_check`를 실행함.
606추가: /// 확인과 삭제 사이에 경로가 바뀌는 경우를 시험하려고 둠.
607추가: /// 내용은 만들 때 열어 둔 폴더 핸들에 묶어 지우므로 경로가 바뀌어도 다른 폴더는 건드리지 않음.
608추가: pub fn remove_open_root_with(root: OpenRoot, after_check: impl FnOnce()) {
609추가: if !root.is_current() {
610추가: return;
611추가: }
612추가: after_check();
613추가: let OpenRoot { path, handle, .. } = root;
614추가: let _ = worker_protocol::tree_remove::remove_contents(&handle, &path);
615추가: // Windows는 핸들을 닫아야 폴더를 지울 수 있음.
616추가: drop(handle);
617추가: // 비어 있지 않거나 링크로 바뀐 경로는 지워지지 않으므로 다른 내용이 사라지지 않음.
618추가: let _ = fs::remove_dir(&path);
604619}
605620
606621/// 기본 프로그램으로 열면 실행될 수 있는 파일은 바로 열지 않음.
수정experiments/rust-ui-memory-app/src/archive_screen.rs+1-1
@@ -3659,7 +3659,7 @@ impl Drop for ArchiveApp {
36593659 fn drop(&mut self) {
36603660 self.clear_password();
36613661 for (_, root) in self.open_roots.drain(..) {
3662삭제: present::remove_open_root(&root);
3662추가: present::remove_open_root(root);
36633663 }
36643664 }
36653665}
수정tests/rust-app-ui/presentation.rs+89-0
@@ -1158,6 +1158,7 @@ fn client_protocol_errors_hide_internal_terms_but_preserve_exit_uncertainty() {
11581158}
11591159
11601160#[cfg(feature = "ui")]
1161추가: #[cfg(unix)]
11611162#[test]
11621163fn app_exit_preserves_replaced_open_root() {
11631164 use zipelo_ui_memory_app::archive_screen::ArchiveApp;
@@ -1195,3 +1196,91 @@ fn app_exit_removes_original_open_root() {
11951196 drop(app);
11961197 assert!(!root.exists());
11971198}
1199추가:
1200추가: #[cfg(feature = "ui")]
1201추가: #[cfg(windows)]
1202추가: #[test]
1203추가: fn open_root_cannot_be_renamed_while_app_holds_it() {
1204추가: use zipelo_ui_memory_app::archive_screen::ArchiveApp;
1205추가: let scratch = Folder::new();
1206추가: let mut app = ArchiveApp::new(
1207추가: Box::new(FakeFactory::default()),
1208추가: Some(scratch.0.join("sample.zip")),
1209추가: false,
1210추가: );
1211추가: pump(&mut app.model);
1212추가: assert!(app.open_entry(0));
1213추가: let root = scratch.0.join(open_root_name("sample.zip"));
1214추가: // 열어 둔 핸들이 이름 변경을 막아 경로가 다른 폴더로 바뀌지 않음.
1215추가: assert!(fs::rename(&root, scratch.0.join("original")).is_err());
1216추가: drop(app);
1217추가: assert!(!root.exists());
1218추가: }
1219추가:
1220추가: #[cfg(unix)]
1221추가: fn open_root_with_contents(scratch: &Folder) -> (OpenRoot, PathBuf) {
1222추가: let root = create_open_root(&scratch.0.join("sample.zip")).unwrap();
1223추가: let path = root.path().to_path_buf();
1224추가: fs::create_dir_all(path.join("a/b")).unwrap();
1225추가: fs::write(path.join("a/b/deep.txt"), b"temporary").unwrap();
1226추가: fs::write(path.join("top.txt"), b"temporary").unwrap();
1227추가: (root, path)
1228추가: }
1229추가:
1230추가: #[cfg(unix)]
1231추가: #[test]
1232추가: fn removal_is_bound_to_checked_folder_when_replaced_after_check() {
1233추가: let scratch = Folder::new();
1234추가: let (root, path) = open_root_with_contents(&scratch);
1235추가: let original = scratch.0.join("original");
1236추가: remove_open_root_with(root, || {
1237추가: fs::rename(&path, &original).unwrap();
1238추가: fs::create_dir(&path).unwrap();
1239추가: fs::write(path.join("keep.txt"), b"user data").unwrap();
1240추가: });
1241추가: assert_eq!(fs::read(path.join("keep.txt")).unwrap(), b"user data");
1242추가: // 확인한 폴더의 내용만 지움.
1243추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1244추가: }
1245추가:
1246추가: #[cfg(unix)]
1247추가: #[test]
1248추가: fn removal_does_not_follow_link_swapped_in_after_check() {
1249추가: let scratch = Folder::new();
1250추가: let (root, path) = open_root_with_contents(&scratch);
1251추가: let victim = scratch.0.join("victim");
1252추가: fs::create_dir(&victim).unwrap();
1253추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1254추가: let original = scratch.0.join("original");
1255추가: remove_open_root_with(root, || {
1256추가: fs::rename(&path, &original).unwrap();
1257추가: std::os::unix::fs::symlink(&victim, &path).unwrap();
1258추가: });
1259추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1260추가: assert!(fs::symlink_metadata(&path).unwrap().file_type().is_symlink());
1261추가: assert_eq!(fs::read_dir(&original).unwrap().count(), 0);
1262추가: }
1263추가:
1264추가: #[cfg(unix)]
1265추가: #[test]
1266추가: fn removal_does_not_follow_links_inside_folder() {
1267추가: let scratch = Folder::new();
1268추가: let (root, path) = open_root_with_contents(&scratch);
1269추가: let victim = scratch.0.join("victim");
1270추가: fs::create_dir(&victim).unwrap();
1271추가: fs::write(victim.join("keep.txt"), b"user data").unwrap();
1272추가: std::os::unix::fs::symlink(&victim, path.join("a/link")).unwrap();
1273추가: std::os::unix::fs::symlink(victim.join("keep.txt"), path.join("file-link")).unwrap();
1274추가: remove_open_root(root);
1275추가: assert!(!path.exists());
1276추가: assert_eq!(fs::read(victim.join("keep.txt")).unwrap(), b"user data");
1277추가: }
1278추가:
1279추가: #[cfg(unix)]
1280추가: #[test]
1281추가: fn removal_of_original_folder_clears_nested_contents() {
1282추가: let scratch = Folder::new();
1283추가: let (root, path) = open_root_with_contents(&scratch);
1284추가: remove_open_root(root);
1285추가: assert!(!path.exists());
1286추가: }