team-ljyzipelo

공개
194줄7.2 KB
1//! 열어 둔 폴더 핸들에 묶어서 폴더 안의 내용을 지움.
2//! 경로를 다시 해석하지 않으므로 확인한 뒤 경로가 바뀌어도 다른 폴더를 지우지 않음.
3
4use std::fs::File;
5use std::io;
6use std::path::Path;
7
8/// `dir` 핸들이 가리키는 폴더 안의 모든 항목을 지움. 폴더 자체는 지우지 않음.
9/// Linux는 핸들 기준 `unlinkat`으로 지우며 `path`는 쓰지 않음.
10/// Windows는 호출한 쪽이 공유 삭제를 허용하지 않고 `dir`을 열어 두어 폴더 이름이
11/// 바뀌지 않게 한 상태에서만 `path`를 씀.
12pub fn remove_contents(dir: &File, path: &Path) -> io::Result<()> {
13 platform::remove_contents(dir, path)
14}
15
16/// `dir` 핸들이 가리키는 폴더가 비어 있는지 확인함. 새로 만든 폴더를 핸들로 잡은 직후 쓰임.
17pub fn is_empty(dir: &File, path: &Path) -> io::Result<bool> {
18 platform::is_empty(dir, path)
19}
20
21#[cfg(target_os = "linux")]
22mod platform {
23 use std::ffi::{CStr, CString};
24 use std::fs::File;
25 use std::io;
26 use std::os::unix::{
27 fs::MetadataExt,
28 io::{AsRawFd, FromRawFd},
29 };
30 use std::path::Path;
31
32 #[cfg(any(target_arch = "aarch64", target_arch = "arm"))]
33 const NOFOLLOW_DIRECTORY: i32 = 0x8000 | 0x4000;
34 #[cfg(not(any(target_arch = "aarch64", target_arch = "arm")))]
35 const NOFOLLOW_DIRECTORY: i32 = 0x20000 | 0x10000;
36 const CLOEXEC: i32 = 0x80000;
37 const AT_REMOVEDIR: i32 = 0x200;
38 const ENOENT: i32 = 2;
39 const EPERM: i32 = 1;
40 const EISDIR: i32 = 21;
41 /// 깊게 중첩된 폴더에서 파일 디스크립터가 바닥나지 않게 하는 한도.
42 const MAX_DEPTH: usize = 256;
43
44 #[repr(C)]
45 struct Dirent64 {
46 inode: u64,
47 offset: i64,
48 length: u16,
49 kind: u8,
50 name: [i8; 256],
51 }
52
53 unsafe extern "C" {
54 fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
55 fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
56 fn fdopendir(fd: i32) -> *mut std::ffi::c_void;
57 fn readdir64(stream: *mut std::ffi::c_void) -> *mut Dirent64;
58 fn rewinddir(stream: *mut std::ffi::c_void);
59 fn closedir(stream: *mut std::ffi::c_void) -> i32;
60 }
61
62 pub fn remove_contents(dir: &File, _path: &Path) -> io::Result<()> {
63 let device = dir.metadata()?.dev();
64 remove_children(dir, device, 0)
65 }
66
67 pub fn is_empty(dir: &File, _path: &Path) -> io::Result<bool> {
68 Ok(names(dir)?.is_empty())
69 }
70
71 fn names(dir: &File) -> io::Result<Vec<CString>> {
72 let copy = dir.try_clone()?;
73 let fd = std::os::unix::io::IntoRawFd::into_raw_fd(copy);
74 // 복제한 디스크립터의 소유권은 폴더 스트림이 가져가며 closedir이 닫음.
75 let stream = unsafe { fdopendir(fd) };
76 if stream.is_null() {
77 let error = io::Error::last_os_error();
78 // 스트림을 만들지 못했으므로 복제한 디스크립터를 직접 돌려받아 닫음.
79 drop(unsafe { File::from_raw_fd(fd) });
80 return Err(error);
81 }
82 // 복제한 디스크립터는 원본과 읽기 위치를 공유하므로 처음부터 읽음.
83 unsafe { rewinddir(stream) };
84 let mut found = Vec::new();
85 loop {
86 let entry = unsafe { readdir64(stream) };
87 if entry.is_null() {
88 break;
89 }
90 // 반환된 항목은 다음 readdir64 호출 전까지 유효하며 바로 복사함.
91 let name = unsafe { CStr::from_ptr((*entry).name.as_ptr()) };
92 let bytes = name.to_bytes();
93 if bytes != b"." && bytes != b".." {
94 found.push(name.to_owned());
95 }
96 }
97 unsafe { closedir(stream) };
98 Ok(found)
99 }
100
101 fn unlink(dir: &File, name: &CString, flags: i32) -> io::Result<()> {
102 // 부모 핸들 기준으로 이름 하나만 지움.
103 if unsafe { unlinkat(dir.as_raw_fd(), name.as_ptr(), flags) } == 0 {
104 Ok(())
105 } else {
106 Err(io::Error::last_os_error())
107 }
108 }
109
110 fn open_directory(dir: &File, name: &CString) -> io::Result<File> {
111 // 심볼릭 링크를 따르지 않고 폴더만 부모 핸들 기준으로 엶.
112 let fd = unsafe {
113 openat(
114 dir.as_raw_fd(),
115 name.as_ptr(),
116 NOFOLLOW_DIRECTORY | CLOEXEC,
117 )
118 };
119 if fd < 0 {
120 return Err(io::Error::last_os_error());
121 }
122 Ok(unsafe { File::from_raw_fd(fd) })
123 }
124
125 fn remove_children(dir: &File, device: u64, depth: usize) -> io::Result<()> {
126 let mut failure = None;
127 for name in names(dir)? {
128 if let Err(error) = remove_entry(dir, &name, device, depth) {
129 if error.raw_os_error() != Some(ENOENT) {
130 failure.get_or_insert(error);
131 }
132 }
133 }
134 failure.map_or(Ok(()), Err)
135 }
136
137 fn remove_entry(dir: &File, name: &CString, device: u64, depth: usize) -> io::Result<()> {
138 match unlink(dir, name, 0) {
139 Ok(()) => return Ok(()),
140 Err(error) if matches!(error.raw_os_error(), Some(EISDIR | EPERM)) => {}
141 Err(error) => return Err(error),
142 }
143 if depth >= MAX_DEPTH {
144 return Err(io::Error::other("폴더가 너무 깊음"));
145 }
146 let child = match open_directory(dir, name) {
147 Ok(child) => child,
148 // 그 사이 폴더가 아닌 항목으로 바뀌었으면 항목 자체를 지움.
149 Err(_) => return unlink(dir, name, 0),
150 };
151 // 다른 파일 시스템이 연결된 폴더 안은 지우지 않음.
152 if child.metadata()?.dev() != device {
153 return Err(io::Error::other("다른 파일 시스템의 폴더"));
154 }
155 remove_children(&child, device, depth + 1)?;
156 drop(child);
157 unlink(dir, name, AT_REMOVEDIR)
158 }
159}
160
161#[cfg(windows)]
162mod platform {
163 use std::fs::{self, File};
164 use std::io;
165 use std::path::Path;
166
167 pub fn is_empty(_dir: &File, path: &Path) -> io::Result<bool> {
168 // 호출한 쪽의 핸들이 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
169 Ok(fs::read_dir(path)?.next().is_none())
170 }
171
172 pub fn remove_contents(_dir: &File, path: &Path) -> io::Result<()> {
173 let mut failure = None;
174 // 호출한 쪽의 핸들이 폴더 이름 변경을 막고 있으므로 경로가 같은 폴더를 가리킴.
175 for entry in fs::read_dir(path)? {
176 let result = entry.and_then(|entry| {
177 let path = entry.path();
178 let kind = fs::symlink_metadata(&path)?.file_type();
179 if kind.is_symlink() {
180 // 링크는 따라가지 않고 링크 자체만 지움.
181 fs::remove_file(&path).or_else(|_| fs::remove_dir(&path))
182 } else if kind.is_dir() {
183 fs::remove_dir_all(&path)
184 } else {
185 fs::remove_file(&path)
186 }
187 });
188 if let Err(error) = result {
189 failure.get_or_insert(error);
190 }
191 }
192 failure.map_or(Ok(()), Err)
193 }
194}