team-ljyzipelo

공개
396줄13 KB
1use crate::{filesystem, protocol::*};
2use sha2::{Digest, Sha256};
3use std::{
4 fs::{File, OpenOptions},
5 io::{Read, Seek, SeekFrom, Write},
6 path::Path,
7};
8
9type Result<T> = std::result::Result<T, ErrorCode>;
10
11enum Placement {
12 Fixed(filesystem::Dir),
13 Fallback {
14 source_parent: std::path::PathBuf,
15 next: usize,
16 other_error: Option<ErrorCode>,
17 },
18}
19
20thread_local! {
21 // 작업 스레드의 임시 파일 정책만 보관함.
22 static LOCATION: std::cell::RefCell<Option<Placement>> =
23 const { std::cell::RefCell::new(None) };
24 // 출력 폴더에 이름 있는 임시 파일을 만든 뒤 이름을 지우지 못했는지 기록함.
25 static LEFTOVER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
26}
27
28pub(crate) struct Location(Option<Placement>);
29impl Drop for Location {
30 fn drop(&mut self) {
31 LOCATION.with(|location| *location.borrow_mut() = self.0.take());
32 }
33}
34pub(crate) fn place_in(dir: &filesystem::Dir) -> Result<Location> {
35 let placement = Placement::Fixed(dir.duplicate()?);
36 LEFTOVER.with(|leftover| leftover.set(false));
37 Ok(LOCATION.with(|location| Location(location.replace(Some(placement)))))
38}
39pub(crate) fn fallback_for(path: &Path) -> Location {
40 LEFTOVER.with(|leftover| leftover.set(false));
41 let placement = Placement::Fallback {
42 source_parent: path.parent().unwrap_or(Path::new("")).to_path_buf(),
43 next: 0,
44 other_error: None,
45 };
46 LOCATION.with(|location| Location(location.replace(Some(placement))))
47}
48
49#[cfg(target_os = "linux")]
50fn private_directory(path: &Path) -> Result<filesystem::Dir> {
51 if !path.is_absolute() {
52 return Err(ErrorCode::Io);
53 }
54 match filesystem::Dir::root(path) {
55 Ok(dir) => Ok(dir),
56 Err(error) => {
57 if !matches!(std::fs::symlink_metadata(path), Err(ref e) if e.kind() == std::io::ErrorKind::NotFound)
58 {
59 return Err(error);
60 }
61 let parent = private_directory(path.parent().ok_or(ErrorCode::Io)?)?;
62 let name = path
63 .file_name()
64 .and_then(|n| n.to_str())
65 .ok_or(ErrorCode::Io)?;
66 parent.child(name, true)?.ok_or(ErrorCode::Io)
67 }
68 }
69}
70fn cache_directory() -> Result<filesystem::Dir> {
71 #[cfg(target_os = "linux")]
72 {
73 let base = match std::env::var_os("XDG_CACHE_HOME").filter(|p| !p.is_empty()) {
74 Some(path) => std::path::PathBuf::from(path),
75 None => std::path::PathBuf::from(std::env::var_os("HOME").ok_or(ErrorCode::Io)?)
76 .join(".cache"),
77 };
78 private_directory(&base)?
79 .child("zipelo", true)?
80 .ok_or(ErrorCode::Io)
81 }
82 #[cfg(windows)]
83 {
84 let base = std::path::PathBuf::from(std::env::var_os("LOCALAPPDATA").ok_or(ErrorCode::Io)?);
85 if !base.is_absolute() {
86 return Err(ErrorCode::Io);
87 }
88 filesystem::Dir::root(&base)?
89 .child("Zipelo", true)?
90 .ok_or(ErrorCode::Io)?
91 .child("Temp", true)?
92 .ok_or(ErrorCode::Io)
93 }
94}
95fn next_after_full() -> Result<bool> {
96 LOCATION.with(|location| {
97 let mut location = location.borrow_mut();
98 match location.as_mut() {
99 Some(Placement::Fallback {
100 next, other_error, ..
101 }) => {
102 *next += 1;
103 if *next >= 3 {
104 Err(other_error.unwrap_or(ErrorCode::DiskFull))
105 } else {
106 Ok(true)
107 }
108 }
109 _ => Ok(false),
110 }
111 })
112}
113
114/// 출력 폴더에 지우지 못한 임시 파일이 남았음을 기록함. Windows 임시 파일은 닫으면 지워지므로
115/// Linux 대체 이름 경로에서만 사용함.
116#[cfg(target_os = "linux")]
117pub(crate) fn note_leftover() {
118 LEFTOVER.with(|leftover| leftover.set(true));
119}
120
121/// 작업 중 출력 폴더에 임시 파일이 남았는지 확인하고 기록을 비움.
122pub(crate) fn take_leftover() -> bool {
123 LEFTOVER.with(|leftover| leftover.replace(false))
124}
125
126/// 실패한 단계의 임시 파일이 닫힌 뒤 다음 위치에서 다시 시도함.
127pub(crate) fn retry_full<T>(mut operation: impl FnMut() -> Result<T>) -> Result<T> {
128 loop {
129 match operation() {
130 Err(ErrorCode::DiskFull) if next_after_full()? => continue,
131 result => return result,
132 }
133 }
134}
135
136pub(crate) fn random_name() -> Result<String> {
137 let mut random = [0; 16];
138 crate::crypto::random(&mut random)?;
139 Ok(random.iter().map(|b| format!("{b:02x}")).collect())
140}
141
142/// 지정한 정책에 따라 이름 없는 임시 파일을 만듦.
143pub(crate) fn temporary() -> Result<File> {
144 let placed = LOCATION.with(|location| {
145 let mut location = location.borrow_mut();
146 match location.as_mut() {
147 Some(Placement::Fixed(dir)) => match dir.temporary() {
148 Ok(file) => Some(Ok(file)),
149 Err(_) => {
150 *location = None;
151 None
152 }
153 },
154 Some(Placement::Fallback {
155 source_parent,
156 next,
157 other_error,
158 }) => {
159 while *next < 3 {
160 let file = match *next {
161 0 => cache_directory().and_then(|dir| dir.temporary()),
162 1 => filesystem::Dir::root(source_parent).and_then(|dir| dir.temporary()),
163 _ => system_temporary(),
164 };
165 match file {
166 Ok(file) => return Some(Ok(file)),
167 Err(error) => {
168 if error != ErrorCode::DiskFull {
169 *other_error = Some(ErrorCode::Io);
170 }
171 *next += 1;
172 }
173 }
174 }
175 Some(Err(other_error.unwrap_or(ErrorCode::DiskFull)))
176 }
177 None => None,
178 }
179 });
180 placed.unwrap_or_else(system_temporary)
181}
182
183fn system_temporary() -> Result<File> {
184 #[cfg(target_os = "linux")]
185 {
186 use std::os::unix::fs::OpenOptionsExt;
187 // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨.
188 match OpenOptions::new()
189 .read(true)
190 .write(true)
191 .custom_flags(0x410000 | 0x80)
192 .mode(0o600)
193 .open(std::env::temp_dir())
194 {
195 Ok(file) => return Ok(file),
196 Err(error) => {
197 if crate::space::io_error(error) == ErrorCode::DiskFull {
198 return Err(ErrorCode::DiskFull);
199 }
200 }
201 }
202 let name = random_name()?;
203 let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp"));
204 let file = OpenOptions::new()
205 .read(true)
206 .write(true)
207 .create_new(true)
208 .mode(0o600)
209 .custom_flags(0x20000)
210 .open(&path)
211 .map_err(crate::space::io_error)?;
212 std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?;
213 use std::os::unix::fs::MetadataExt;
214 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
215 return Err(ErrorCode::Io);
216 }
217 Ok(file)
218 }
219 #[cfg(windows)]
220 {
221 windows_temporary(&std::env::temp_dir(), "zipelo-", false)
222 }
223}
224
225/// 닫으면 지워지는 Windows 임시 파일을 지정한 폴더에 만듦. 출력 폴더에서는 숨김 속성을 붙임.
226#[cfg(windows)]
227pub(crate) fn windows_temporary(parent: &Path, prefix: &str, hidden: bool) -> Result<File> {
228 use std::os::windows::fs::OpenOptionsExt;
229 let name = random_name()?;
230 OpenOptions::new()
231 .read(true)
232 .write(true)
233 .create_new(true)
234 .share_mode(0)
235 .access_mode(0xc0010000)
236 .custom_flags(0x04000000 | 0x00200000)
237 .attributes(if hidden { 0x100 | 0x2 } else { 0x100 })
238 .open(parent.join(format!("{prefix}{name}.tmp")))
239 .map_err(crate::space::io_error)
240}
241
242#[derive(Clone, Copy, Debug)]
243pub(crate) enum Step {
244 Check,
245 Activity,
246 Read { bytes: u64, total: u64 },
247}
248
249struct Progress<'a, F>(&'a mut F);
250impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> {
251 fn check(&mut self) -> Result<()> {
252 self.0(Step::Check)
253 }
254 fn activity(&mut self) -> Result<()> {
255 self.0(Step::Activity)
256 }
257}
258fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> {
259 crate::resources::completed(result, &mut Progress(step))
260}
261
262pub(crate) struct Snapshot {
263 pub file: File,
264 pub len: u64,
265 pub object: SourceObject,
266 pub hash: [u8; 32],
267}
268impl Snapshot {
269 /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림.
270 pub fn open_reporting(
271 path: &Path,
272 limit: u64,
273 step: &mut impl FnMut(Step) -> Result<()>,
274 ) -> Result<Self> {
275 let mut options = OpenOptions::new();
276 options.read(true);
277 #[cfg(unix)]
278 {
279 use std::os::unix::fs::OpenOptionsExt;
280 options.custom_flags(0x20000 | 0x800);
281 }
282 #[cfg(windows)]
283 {
284 use std::os::windows::fs::OpenOptionsExt;
285 options.share_mode(1);
286 }
287 let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?;
288 let snapshot = Self::capture_reporting(&mut source, limit, step)?;
289 let named = completed(
290 options.open(path).map_err(|_| ErrorCode::SourceChanged),
291 step,
292 )?;
293 if filesystem::object(&named)? != snapshot.object
294 || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
295 {
296 return Err(ErrorCode::SourceChanged);
297 }
298 completed(Ok(snapshot), step)
299 }
300 pub(crate) fn capture(
301 source: &mut File,
302 limit: u64,
303 check: &mut impl crate::resources::Monitor,
304 ) -> Result<Self> {
305 Self::capture_reporting(source, limit, &mut |step| match step {
306 Step::Check => check.check(),
307 Step::Activity => crate::resources::completed(Ok(()), check),
308 Step::Read { .. } => check.check(),
309 })
310 }
311 pub(crate) fn capture_reporting(
312 source: &mut File,
313 limit: u64,
314 step: &mut impl FnMut(Step) -> Result<()>,
315 ) -> Result<Self> {
316 let original = source.metadata().map_err(|_| ErrorCode::Io)?;
317 loop {
318 step(Step::Check)?;
319 let current = source.metadata().map_err(|_| ErrorCode::Io)?;
320 if current.len() != original.len()
321 || current.modified().ok() != original.modified().ok()
322 {
323 return Err(ErrorCode::SourceChanged);
324 }
325 match Self::capture_once(source, limit, step) {
326 Err(ErrorCode::DiskFull) if next_after_full()? => continue,
327 result => return result,
328 }
329 }
330 }
331 fn capture_once(
332 source: &mut File,
333 limit: u64,
334 step: &mut impl FnMut(Step) -> Result<()>,
335 ) -> Result<Self> {
336 let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
337 if !before.is_file() {
338 return Err(ErrorCode::InvalidRequest);
339 }
340 if before.len() > limit {
341 return Err(ErrorCode::Limit);
342 }
343 source.rewind().map_err(|_| ErrorCode::Io)?;
344 let object = filesystem::object(&source)?;
345 let mut file = completed(temporary(), step)?;
346 completed(crate::space::ensure(&file, before.len()), step)?;
347 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
348 let mut hash = Sha256::new();
349 let mut len = 0u64;
350 let total = before.len();
351 let mut reported = std::time::Instant::now();
352 loop {
353 step(Step::Check)?;
354 let n = completed(
355 source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io),
356 step,
357 )?;
358 if n == 0 {
359 break;
360 }
361 len = len
362 .checked_add(n as u64)
363 .filter(|n| *n <= limit)
364 .ok_or(ErrorCode::Limit)?;
365 completed(
366 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
367 step,
368 )?;
369 hash.update(&buffer[..n]);
370 // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림.
371 if reported.elapsed() >= std::time::Duration::from_millis(200) {
372 step(Step::Read { bytes: len, total })?;
373 reported = std::time::Instant::now();
374 }
375 }
376 step(Step::Read { bytes: len, total })?;
377 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
378 if filesystem::object(&source)? != object
379 || before.len() != len
380 || after.len() != len
381 || before.modified().ok() != after.modified().ok()
382 {
383 return Err(ErrorCode::SourceChanged);
384 }
385 completed(
386 file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io),
387 step,
388 )?;
389 Ok(Self {
390 file,
391 len,
392 object,
393 hash: hash.finalize().into(),
394 })
395 }
396}