team-ljyzipelo

공개
545줄18 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}
95pub(crate) fn 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(error) => {
150 *location = None;
151 Some(system_temporary().map_err(|fallback| {
152 if error == ErrorCode::DiskFull {
153 ErrorCode::DiskFull
154 } else {
155 fallback
156 }
157 }))
158 }
159 },
160 Some(Placement::Fallback {
161 source_parent,
162 next,
163 other_error,
164 }) => {
165 while *next < 3 {
166 let file = match *next {
167 0 => cache_directory().and_then(|dir| dir.temporary()),
168 1 => filesystem::Dir::root(source_parent).and_then(|dir| dir.temporary()),
169 _ => system_temporary(),
170 };
171 match file {
172 Ok(file) => return Some(Ok(file)),
173 Err(error) => {
174 if error != ErrorCode::DiskFull {
175 *other_error = Some(ErrorCode::Io);
176 }
177 *next += 1;
178 }
179 }
180 }
181 Some(Err(other_error.unwrap_or(ErrorCode::DiskFull)))
182 }
183 None => None,
184 }
185 });
186 placed.unwrap_or_else(system_temporary)
187}
188
189fn system_temporary() -> Result<File> {
190 #[cfg(target_os = "linux")]
191 {
192 use std::os::unix::fs::OpenOptionsExt;
193 // 이름 없는 임시 파일은 마지막 핸들을 닫으면 제거됨.
194 match OpenOptions::new()
195 .read(true)
196 .write(true)
197 .custom_flags(0x410000 | 0x80)
198 .mode(0o600)
199 .open(std::env::temp_dir())
200 {
201 Ok(file) => return Ok(file),
202 Err(error) => {
203 if crate::space::io_error(error) == ErrorCode::DiskFull {
204 return Err(ErrorCode::DiskFull);
205 }
206 }
207 }
208 let name = random_name()?;
209 let path = std::env::temp_dir().join(format!("zipelo-{name}.tmp"));
210 let file = OpenOptions::new()
211 .read(true)
212 .write(true)
213 .create_new(true)
214 .mode(0o600)
215 .custom_flags(0x20000)
216 .open(&path)
217 .map_err(crate::space::io_error)?;
218 std::fs::remove_file(path).map_err(|_| ErrorCode::Io)?;
219 use std::os::unix::fs::MetadataExt;
220 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
221 return Err(ErrorCode::Io);
222 }
223 Ok(file)
224 }
225 #[cfg(windows)]
226 {
227 windows_temporary(&std::env::temp_dir(), "zipelo-", false)
228 }
229}
230
231/// 닫으면 지워지는 Windows 임시 파일을 지정한 폴더에 만듦. 출력 폴더에서는 숨김 속성을 붙임.
232#[cfg(windows)]
233pub(crate) fn windows_temporary(parent: &Path, prefix: &str, hidden: bool) -> Result<File> {
234 use std::os::windows::fs::OpenOptionsExt;
235 let name = random_name()?;
236 OpenOptions::new()
237 .read(true)
238 .write(true)
239 .create_new(true)
240 .share_mode(0)
241 .access_mode(0xc0010000)
242 .custom_flags(0x04000000 | 0x00200000)
243 .attributes(if hidden { 0x100 | 0x2 } else { 0x100 })
244 .open(parent.join(format!("{prefix}{name}.tmp")))
245 .map_err(crate::space::io_error)
246}
247
248#[derive(Clone, Copy, Debug)]
249pub(crate) enum Step {
250 Check,
251 Activity,
252 Read { bytes: u64, total: u64 },
253}
254
255struct Progress<'a, F>(&'a mut F);
256impl<F: FnMut(Step) -> Result<()>> crate::resources::Monitor for Progress<'_, F> {
257 fn check(&mut self) -> Result<()> {
258 self.0(Step::Check)
259 }
260 fn activity(&mut self) -> Result<()> {
261 self.0(Step::Activity)
262 }
263}
264fn completed<T>(result: Result<T>, step: &mut impl FnMut(Step) -> Result<()>) -> Result<T> {
265 crate::resources::completed(result, &mut Progress(step))
266}
267
268pub(crate) struct Snapshot {
269 pub file: File,
270 pub len: u64,
271 pub object: SourceObject,
272 pub hash: [u8; 32],
273}
274pub(crate) struct DirectSource {
275 file: File,
276 path: std::path::PathBuf,
277 object: SourceObject,
278 len: u64,
279 modified: std::time::SystemTime,
280 changed: Option<(i64, i64)>,
281 hash: [u8; 32],
282}
283pub(crate) fn change_stamp(metadata: &std::fs::Metadata) -> Option<(i64, i64)> {
284 #[cfg(unix)]
285 {
286 use std::os::unix::fs::MetadataExt;
287 Some((metadata.ctime(), metadata.ctime_nsec()))
288 }
289 #[cfg(windows)]
290 {
291 let _ = metadata;
292 None
293 }
294}
295fn source_options() -> OpenOptions {
296 let mut options = OpenOptions::new();
297 options.read(true);
298 #[cfg(unix)]
299 {
300 use std::os::unix::fs::OpenOptionsExt;
301 options.custom_flags(0x20000 | 0x800);
302 }
303 #[cfg(windows)]
304 {
305 use std::os::windows::fs::OpenOptionsExt;
306 options.share_mode(1);
307 }
308 options
309}
310impl DirectSource {
311 fn unchanged(&self) -> Result<()> {
312 let before = self.file.metadata().map_err(|_| ErrorCode::SourceChanged)?;
313 let named = source_options()
314 .open(&self.path)
315 .map_err(|_| ErrorCode::SourceChanged)?;
316 let after = named.metadata().map_err(|_| ErrorCode::SourceChanged)?;
317 for (file, metadata) in [(&self.file, before), (&named, after)] {
318 if !metadata.is_file()
319 || filesystem::object(file)? != self.object
320 || metadata.len() != self.len
321 || metadata.modified().map_err(|_| ErrorCode::SourceChanged)? != self.modified
322 || change_stamp(&metadata) != self.changed
323 {
324 return Err(ErrorCode::SourceChanged);
325 }
326 }
327 Ok(())
328 }
329 pub(crate) fn verify(&mut self, step: &mut impl FnMut(Step) -> Result<()>) -> Result<()> {
330 self.unchanged()?;
331 let hash = hash_source(&mut self.file, self.len, step)?;
332 self.unchanged()?;
333 if hash != self.hash {
334 return Err(ErrorCode::SourceChanged);
335 }
336 Ok(())
337 }
338}
339fn hash_source(
340 file: &mut File,
341 length: u64,
342 step: &mut impl FnMut(Step) -> Result<()>,
343) -> Result<[u8; 32]> {
344 file.rewind().map_err(|_| ErrorCode::Io)?;
345 let mut hash = Sha256::new();
346 let mut bytes = 0u64;
347 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
348 let mut reported = std::time::Instant::now();
349 loop {
350 step(Step::Check)?;
351 let count = completed(file.read(&mut buffer[..]).map_err(|_| ErrorCode::Io), step)?;
352 if count == 0 {
353 break;
354 }
355 bytes = bytes
356 .checked_add(count as u64)
357 .filter(|n| *n <= length)
358 .ok_or(ErrorCode::SourceChanged)?;
359 hash.update(&buffer[..count]);
360 if reported.elapsed() >= std::time::Duration::from_millis(200) {
361 step(Step::Read {
362 bytes,
363 total: length,
364 })?;
365 reported = std::time::Instant::now();
366 }
367 }
368 if bytes != length {
369 return Err(ErrorCode::SourceChanged);
370 }
371 step(Step::Read {
372 bytes,
373 total: length,
374 })?;
375 file.rewind().map_err(|_| ErrorCode::Io)?;
376 Ok(hash.finalize().into())
377}
378impl Snapshot {
379 /// 열린 원본을 직접 읽고 작업 종료까지 같은 객체의 핸들을 유지함.
380 pub(crate) fn open_direct(
381 path: &Path,
382 limit: u64,
383 step: &mut impl FnMut(Step) -> Result<()>,
384 ) -> Result<(Self, DirectSource)> {
385 let mut file = completed(source_options().open(path).map_err(|_| ErrorCode::Io), step)?;
386 let metadata = file.metadata().map_err(|_| ErrorCode::Io)?;
387 if !metadata.is_file() {
388 return Err(ErrorCode::InvalidRequest);
389 }
390 if metadata.len() > limit {
391 return Err(ErrorCode::Limit);
392 }
393 let mut guard = DirectSource {
394 file: file.try_clone().map_err(|_| ErrorCode::Io)?,
395 path: path.to_path_buf(),
396 object: filesystem::object(&file)?,
397 len: metadata.len(),
398 modified: metadata.modified().map_err(|_| ErrorCode::Io)?,
399 changed: change_stamp(&metadata),
400 hash: [0; 32],
401 };
402 guard.hash = hash_source(&mut file, guard.len, step)?;
403 guard.unchanged()?;
404 Ok((
405 Self {
406 file,
407 len: guard.len,
408 object: guard.object.clone(),
409 hash: guard.hash,
410 },
411 guard,
412 ))
413 }
414 /// 원본을 임시 파일로 복사하는 동안 읽은 바이트와 전체 크기를 함께 알림.
415 pub fn open_reporting(
416 path: &Path,
417 limit: u64,
418 step: &mut impl FnMut(Step) -> Result<()>,
419 ) -> Result<Self> {
420 let mut options = OpenOptions::new();
421 options.read(true);
422 #[cfg(unix)]
423 {
424 use std::os::unix::fs::OpenOptionsExt;
425 options.custom_flags(0x20000 | 0x800);
426 }
427 #[cfg(windows)]
428 {
429 use std::os::windows::fs::OpenOptionsExt;
430 options.share_mode(1);
431 }
432 let mut source = completed(options.open(path).map_err(|_| ErrorCode::Io), step)?;
433 let snapshot = Self::capture_reporting(&mut source, limit, step)?;
434 let named = completed(
435 options.open(path).map_err(|_| ErrorCode::SourceChanged),
436 step,
437 )?;
438 if filesystem::object(&named)? != snapshot.object
439 || !named.metadata().map_err(|_| ErrorCode::Io)?.is_file()
440 {
441 return Err(ErrorCode::SourceChanged);
442 }
443 completed(Ok(snapshot), step)
444 }
445 pub(crate) fn capture(
446 source: &mut File,
447 limit: u64,
448 check: &mut impl crate::resources::Monitor,
449 ) -> Result<Self> {
450 Self::capture_reporting(source, limit, &mut |step| match step {
451 Step::Check => check.check(),
452 Step::Activity => crate::resources::completed(Ok(()), check),
453 Step::Read { .. } => check.check(),
454 })
455 }
456 pub(crate) fn capture_reporting(
457 source: &mut File,
458 limit: u64,
459 step: &mut impl FnMut(Step) -> Result<()>,
460 ) -> Result<Self> {
461 let original = source.metadata().map_err(|_| ErrorCode::Io)?;
462 loop {
463 step(Step::Check)?;
464 let current = source.metadata().map_err(|_| ErrorCode::Io)?;
465 if current.len() != original.len()
466 || current.modified().ok() != original.modified().ok()
467 {
468 return Err(ErrorCode::SourceChanged);
469 }
470 match Self::capture_once(source, limit, step) {
471 Err(ErrorCode::DiskFull) if next_after_full()? => continue,
472 result => return result,
473 }
474 }
475 }
476 fn capture_once(
477 source: &mut File,
478 limit: u64,
479 step: &mut impl FnMut(Step) -> Result<()>,
480 ) -> Result<Self> {
481 let before = completed(source.metadata().map_err(|_| ErrorCode::Io), step)?;
482 if !before.is_file() {
483 return Err(ErrorCode::InvalidRequest);
484 }
485 if before.len() > limit {
486 return Err(ErrorCode::Limit);
487 }
488 source.rewind().map_err(|_| ErrorCode::Io)?;
489 let object = filesystem::object(&source)?;
490 let mut file = completed(temporary(), step)?;
491 completed(crate::space::ensure(&file, before.len()), step)?;
492 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
493 let mut hash = Sha256::new();
494 let mut len = 0u64;
495 let total = before.len();
496 let mut reported = std::time::Instant::now();
497 loop {
498 step(Step::Check)?;
499 let n = completed(
500 source.read(&mut buffer[..]).map_err(|_| ErrorCode::Io),
501 step,
502 )?;
503 if n == 0 {
504 break;
505 }
506 len = len
507 .checked_add(n as u64)
508 .filter(|n| *n <= limit)
509 .ok_or(ErrorCode::Limit)?;
510 completed(
511 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
512 step,
513 )?;
514 hash.update(&buffer[..n]);
515 // 큰 파일에서도 진행이 보이도록 일정 간격으로만 알림.
516 if reported.elapsed() >= std::time::Duration::from_millis(200) {
517 step(Step::Read { bytes: len, total })?;
518 reported = std::time::Instant::now();
519 }
520 }
521 step(Step::Read { bytes: len, total })?;
522 let after = source.metadata().map_err(|_| ErrorCode::Io)?;
523 if filesystem::object(&source)? != object
524 || before.len() != len
525 || after.len() != len
526 || before.modified().ok() != after.modified().ok()
527 {
528 return Err(ErrorCode::SourceChanged);
529 }
530 completed(
531 file.seek(SeekFrom::Start(0)).map_err(|_| ErrorCode::Io),
532 step,
533 )?;
534 Ok(Self {
535 file,
536 len,
537 object,
538 hash: hash.finalize().into(),
539 })
540 }
541}
542
543#[cfg(test)]
544#[path = "../../../tests/rust-archive-worker/direct_source.rs"]
545mod direct_source_tests;