team-ljyzipelo

공개
1,021줄35 KB
1use crate::archive::valid_name;
2use crate::protocol::*;
3use crate::resources::{Monitor, completed};
4use sha2::{Digest, Sha256};
5use std::fs::{File, OpenOptions};
6use std::io::{Read, Write};
7#[cfg(windows)]
8use std::path::PathBuf;
9use std::path::{Component, Path};
10use std::sync::atomic::{AtomicU64, Ordering};
11
12type Result<T> = std::result::Result<T, ErrorCode>;
13static TEMP: AtomicU64 = AtomicU64::new(0);
14#[derive(Debug, PartialEq, Eq)]
15pub struct Existing {
16 parent: SourceObject,
17 object: SourceObject,
18 pub size: u64,
19 modified: std::time::SystemTime,
20}
21fn existing_file(parent: &File, file: File) -> Result<Existing> {
22 let metadata = file.metadata().map_err(|_| ErrorCode::Io)?;
23 if !metadata.is_file() {
24 return Err(ErrorCode::UnsafePath);
25 }
26 #[cfg(windows)]
27 {
28 use std::os::windows::fs::MetadataExt;
29 if metadata.file_attributes() & 0x400 != 0 {
30 return Err(ErrorCode::UnsafePath);
31 }
32 }
33 Ok(Existing {
34 parent: object(parent)?,
35 object: object(&file)?,
36 size: metadata.len(),
37 modified: metadata.modified().map_err(|_| ErrorCode::Io)?,
38 })
39}
40pub struct Snapshot {
41 pub bytes: Vec<u8>,
42 pub object: SourceObject,
43 pub hash: [u8; 32],
44}
45#[cfg(unix)]
46pub fn object(file: &File) -> Result<SourceObject> {
47 use std::os::unix::fs::MetadataExt;
48 let m = file.metadata().map_err(|_| ErrorCode::Io)?;
49 Ok(SourceObject::Unix {
50 device: m.dev(),
51 inode: m.ino(),
52 })
53}
54#[cfg(windows)]
55pub fn object(file: &File) -> Result<SourceObject> {
56 use std::os::windows::io::AsRawHandle;
57 #[repr(C)]
58 struct Info {
59 volume: u64,
60 id: [u8; 16],
61 }
62 unsafe extern "system" {
63 fn GetFileInformationByHandleEx(
64 h: *mut std::ffi::c_void,
65 class: u32,
66 info: *mut std::ffi::c_void,
67 size: u32,
68 ) -> i32;
69 }
70 let mut info = Info {
71 volume: 0,
72 id: [0; 16],
73 };
74 // 열린 핸들에 대해 고정 크기의 파일 식별 정보를 조회함.
75 if unsafe {
76 GetFileInformationByHandleEx(
77 file.as_raw_handle(),
78 18,
79 (&mut info as *mut Info).cast(),
80 size_of::<Info>() as u32,
81 )
82 } == 0
83 {
84 return Err(ErrorCode::UnsupportedFeature);
85 }
86 Ok(SourceObject::Windows {
87 volume_serial: info.volume,
88 file_id: info.id,
89 })
90}
91pub fn snapshot(
92 path: &Path,
93 limit: u64,
94 check: &mut impl crate::resources::Monitor,
95) -> Result<Snapshot> {
96 let mut options = OpenOptions::new();
97 options.read(true);
98 #[cfg(unix)]
99 {
100 use std::os::unix::fs::OpenOptionsExt;
101 options.custom_flags(0x20000 | 0x800);
102 }
103 #[cfg(windows)]
104 {
105 use std::os::windows::fs::OpenOptionsExt;
106 options.share_mode(1);
107 }
108 let mut file = options.open(path).map_err(|_| ErrorCode::Io)?;
109 let before = file.metadata().map_err(|_| ErrorCode::Io)?;
110 if !before.is_file() {
111 return Err(ErrorCode::InvalidRequest);
112 }
113 if before.len() > limit {
114 return Err(ErrorCode::Limit);
115 }
116 let identity = object(&file)?;
117 let mut bytes = Vec::new();
118 let mut hash = Sha256::new();
119 let mut buffer = [0; 65536];
120 loop {
121 check.check()?;
122 let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
123 if n == 0 {
124 break;
125 }
126 if bytes.len() as u64 + n as u64 > limit {
127 return Err(ErrorCode::Limit);
128 }
129 bytes.try_reserve(n).map_err(|_| ErrorCode::Limit)?;
130 bytes.extend_from_slice(&buffer[..n]);
131 hash.update(&buffer[..n]);
132 completed(Ok(()), check)?;
133 }
134 let after = file.metadata().map_err(|_| ErrorCode::Io)?;
135 let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
136 if !named
137 .metadata()
138 .map_err(|_| ErrorCode::SourceChanged)?
139 .is_file()
140 || object(&named)? != identity
141 || object(&file)? != identity
142 || before.len() != after.len()
143 || after.len() != bytes.len() as u64
144 || before.modified().ok() != after.modified().ok()
145 {
146 return Err(ErrorCode::SourceChanged);
147 }
148 close(file).map_err(|_| ErrorCode::Io)?;
149 Ok(Snapshot {
150 bytes,
151 object: identity,
152 hash: hash.finalize().into(),
153 })
154}
155#[cfg(unix)]
156fn close(file: File) -> std::io::Result<()> {
157 use std::os::unix::io::IntoRawFd;
158 unsafe extern "C" {
159 fn close(fd: i32) -> i32;
160 }
161 // 소유한 파일 디스크립터를 한 번만 닫음.
162 if unsafe { close(file.into_raw_fd()) } == 0 {
163 Ok(())
164 } else {
165 Err(std::io::Error::last_os_error())
166 }
167}
168#[cfg(windows)]
169fn close(file: File) -> std::io::Result<()> {
170 use std::os::windows::io::IntoRawHandle;
171 unsafe extern "system" {
172 fn CloseHandle(h: *mut std::ffi::c_void) -> i32;
173 }
174 // 소유한 핸들을 한 번만 닫음.
175 if unsafe { CloseHandle(file.into_raw_handle()) } != 0 {
176 Ok(())
177 } else {
178 Err(std::io::Error::last_os_error())
179 }
180}
181#[cfg(target_os = "linux")]
182mod platform {
183 use super::*;
184 use std::ffi::CString;
185 use std::os::unix::{
186 ffi::OsStrExt,
187 fs::MetadataExt,
188 io::{AsRawFd, FromRawFd},
189 };
190 unsafe extern "C" {
191 fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
192 fn mkdirat(fd: i32, path: *const i8, mode: u32) -> i32;
193 fn linkat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8, flags: i32) -> i32;
194 fn renameat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8) -> i32;
195 fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
196 fn geteuid() -> u32;
197 fn getegid() -> u32;
198 fn getgrgid_r(
199 gid: u32,
200 group: *mut Group,
201 buffer: *mut i8,
202 length: usize,
203 result: *mut *mut Group,
204 ) -> i32;
205 }
206 #[repr(C)]
207 struct Group {
208 name: *mut i8,
209 password: *mut i8,
210 gid: u32,
211 members: *mut *mut i8,
212 }
213 // 원격 계정 열거는 불완전할 수 있으므로 로컬 계정만 확인 가능한 경우에 허용함.
214 fn primary_group_is_private(gid: u32) -> bool {
215 let Ok(policy) = std::fs::read_to_string("/etc/nsswitch.conf") else {
216 return false;
217 };
218 let mut sources = policy.lines().filter_map(|line| {
219 let line = line.split('#').next().unwrap_or_default();
220 let (database, sources) = line.split_once(':')?;
221 (database.trim() == "passwd").then_some(sources)
222 });
223 let Some(source) = sources.next() else {
224 return false;
225 };
226 if sources.next().is_some() || !source.split_whitespace().eq(["files"]) {
227 return false;
228 }
229 let Ok(accounts) = std::fs::read_to_string("/etc/passwd") else {
230 return false;
231 };
232 let current_uid = unsafe { geteuid() };
233 let mut found_current = false;
234 for account in accounts.lines() {
235 if account.trim().is_empty() || account.starts_with('#') {
236 continue;
237 }
238 let fields: Vec<_> = account.split(':').collect();
239 if fields.len() != 7 || fields[0].is_empty() {
240 return false;
241 }
242 let (Ok(uid), Ok(primary_gid)) = (fields[2].parse::<u32>(), fields[3].parse::<u32>())
243 else {
244 return false;
245 };
246 if primary_gid == gid {
247 if uid != current_uid {
248 return false;
249 }
250 found_current = true;
251 }
252 }
253 found_current
254 }
255
256 // 기본 구성원과 보조 구성원을 모두 확인함.
257 fn private_group(gid: u32) -> bool {
258 if gid != unsafe { getegid() } || !primary_group_is_private(gid) {
259 return false;
260 }
261 let mut group = Group {
262 name: std::ptr::null_mut(),
263 password: std::ptr::null_mut(),
264 gid: 0,
265 members: std::ptr::null_mut(),
266 };
267 let mut result = std::ptr::null_mut();
268 let mut buffer = vec![0i8; 16 * 1024];
269 let status = unsafe {
270 getgrgid_r(
271 gid,
272 &mut group,
273 buffer.as_mut_ptr(),
274 buffer.len(),
275 &mut result,
276 )
277 };
278 // 그룹 정보를 읽지 못하면 안전하다고 볼 근거가 없으므로 거부함.
279 status == 0
280 && !result.is_null()
281 && group.gid == gid
282 && !group.members.is_null()
283 && unsafe { *group.members }.is_null()
284 }
285 pub struct Dir {
286 file: File,
287 }
288 fn name(s: &std::ffi::OsStr) -> Result<CString> {
289 CString::new(s.as_bytes()).map_err(|_| ErrorCode::UnsafePath)
290 }
291 fn open(parent: &File, s: &std::ffi::OsStr, flags: i32) -> std::io::Result<File> {
292 let n = name(s).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
293 // 부모 핸들 기준으로 심볼릭 링크를 따르지 않고 열음.
294 let fd = unsafe {
295 openat(
296 parent.as_raw_fd(),
297 n.as_ptr(),
298 flags | 0x80000 | 0x20000,
299 0o600u32,
300 )
301 };
302 if fd < 0 {
303 return Err(std::io::Error::last_os_error());
304 }
305 Ok(unsafe { File::from_raw_fd(fd) })
306 }
307 impl Dir {
308 pub fn root(path: &Path) -> Result<Self> {
309 if !path.is_absolute() {
310 return Err(ErrorCode::InvalidRequest);
311 }
312 let mut d = Self {
313 file: File::open("/").map_err(|_| ErrorCode::Io)?,
314 };
315 for c in path.components() {
316 match c {
317 Component::RootDir => {}
318 Component::Normal(n) => {
319 d = Self {
320 file: open(&d.file, n, 0x10000).map_err(|_| ErrorCode::UnsafePath)?,
321 }
322 }
323 _ => return Err(ErrorCode::UnsafePath),
324 }
325 }
326 d.trusted()?;
327 Ok(d)
328 }
329 fn trusted(&self) -> Result<()> {
330 let m = self.file.metadata().map_err(|_| ErrorCode::Io)?;
331 // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함.
332 // 그룹 쓰기는 그 그룹이 현재 계정만의 개인 그룹일 때만 허용함.
333 let group_writable = m.mode() & 0o020 != 0;
334 if !m.is_dir()
335 || m.uid() != unsafe { geteuid() }
336 || m.mode() & 0o002 != 0
337 || (group_writable && !private_group(m.gid()))
338 {
339 return Err(ErrorCode::UnsafePath);
340 }
341 Ok(())
342 }
343 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
344 match open(&self.file, std::ffi::OsStr::new(n), 0x10000) {
345 Ok(file) => {
346 let d = Self { file };
347 d.trusted()?;
348 Ok(Some(d))
349 }
350 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
351 if !create {
352 return Ok(None);
353 }
354 let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?;
355 // 고정 부모 안에 새 전용 디렉터리를 생성함.
356 if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 {
357 return Err(crate::space::io_error(std::io::Error::last_os_error()));
358 }
359 let file = open(
360 &self.file,
361 std::ffi::OsStr::new(n.to_str().unwrap()),
362 0x10000,
363 )
364 .map_err(|_| ErrorCode::UnsafePath)?;
365 let d = Self { file };
366 d.trusted()?;
367 Ok(Some(d))
368 }
369 Err(_) => Err(ErrorCode::UnsafePath),
370 }
371 }
372 pub(crate) fn handle(&self) -> &File {
373 &self.file
374 }
375 pub fn duplicate(&self) -> Result<Self> {
376 Ok(Self {
377 file: self.file.try_clone().map_err(|_| ErrorCode::Io)?,
378 })
379 }
380 pub fn absent(&self, n: &str) -> Result<bool> {
381 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
382 Ok(_) => Ok(false),
383 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
384 Err(_) => Err(ErrorCode::Io),
385 }
386 }
387 pub fn existing(&self, n: &str) -> Result<Option<Existing>> {
388 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
389 Ok(file) => existing_file(&self.file, file).map(Some),
390 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
391 Err(_) => Err(ErrorCode::Io),
392 }
393 }
394 pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> {
395 let from = CString::new(from).unwrap();
396 let to = CString::new(to).unwrap();
397 // 고정 부모 안에서 완성된 임시 파일로 원본 이름을 교체함.
398 if unsafe {
399 renameat(
400 self.file.as_raw_fd(),
401 from.as_ptr(),
402 self.file.as_raw_fd(),
403 to.as_ptr(),
404 )
405 } == 0
406 {
407 Ok(())
408 } else {
409 Err(std::io::Error::last_os_error())
410 }
411 }
412 pub fn create(&self, n: &str) -> std::io::Result<File> {
413 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
414 }
415 /// 이 폴더 안에 이름 없는 읽기/쓰기 임시 파일을 만듦. 마지막 핸들을 닫으면 제거됨.
416 pub(crate) fn temporary(&self) -> Result<File> {
417 // O_TMPFILE | O_EXCL: 이름이 생기지 않고 나중에 링크할 수도 없음.
418 match open(&self.file, std::ffi::OsStr::new("."), 2 | 0x410000 | 0x80) {
419 Ok(file) => return Ok(file),
420 Err(e) => {
421 if crate::space::io_error(e) == ErrorCode::DiskFull {
422 return Err(ErrorCode::DiskFull);
423 }
424 }
425 }
426 // O_TMPFILE을 지원하지 않는 파일 시스템은 숨김 이름으로 만든 즉시 이름을 지움.
427 let n = format!(".zipelo-{}.tmp", crate::spool::random_name()?);
428 let file = open(&self.file, std::ffi::OsStr::new(&n), 2 | 0x40 | 0x80)
429 .map_err(crate::space::io_error)?;
430 if !self.remove(&n) {
431 // 핸들을 닫고 한 번 더 지움. 그래도 남으면 정리 실패로 기록해 결과에 알림.
432 drop(file);
433 if !self.remove(&n) && !self.absent(&n).unwrap_or(false) {
434 crate::spool::note_leftover();
435 }
436 return Err(ErrorCode::Io);
437 }
438 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
439 return Err(ErrorCode::Io);
440 }
441 Ok(file)
442 }
443 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
444 let a = CString::new(from).unwrap();
445 let b = CString::new(to).unwrap();
446 // 배타적 hard link 게시로 기존 이름을 보존함.
447 if unsafe {
448 linkat(
449 self.file.as_raw_fd(),
450 a.as_ptr(),
451 self.file.as_raw_fd(),
452 b.as_ptr(),
453 0,
454 )
455 } == 0
456 {
457 Ok(())
458 } else {
459 Err(std::io::Error::last_os_error())
460 }
461 }
462 pub fn remove(&self, n: &str) -> bool {
463 let n = CString::new(n).unwrap();
464 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
465 }
466 pub fn sync(&self) -> Durability {
467 self.sync_checked().unwrap_or(Durability::Failed)
468 }
469 pub(crate) fn sync_checked(&self) -> Result<Durability> {
470 self.file.sync_all().map_err(crate::space::io_error)?;
471 Ok(Durability::Synced)
472 }
473 }
474}
475#[cfg(windows)]
476mod platform {
477 use super::*;
478 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
479 pub struct Dir {
480 path: PathBuf,
481 locks: Vec<File>,
482 }
483 fn lock(path: &Path) -> Result<File> {
484 let f = OpenOptions::new()
485 .access_mode(0x80)
486 .share_mode(3)
487 .custom_flags(0x02000000 | 0x00200000)
488 .open(path)
489 .map_err(|_| ErrorCode::UnsafePath)?;
490 let m = f.metadata().map_err(|_| ErrorCode::Io)?;
491 if !m.is_dir() || m.file_attributes() & 0x400 != 0 {
492 return Err(ErrorCode::UnsafePath);
493 }
494 Ok(f)
495 }
496 impl Dir {
497 pub fn root(path: &Path) -> Result<Self> {
498 let mut p = PathBuf::new();
499 let mut locks = Vec::new();
500 for c in path.components() {
501 match c {
502 Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()),
503 Component::Normal(n) => {
504 if locks.is_empty() {
505 locks.push(lock(&p)?);
506 }
507 p.push(n);
508 locks.push(lock(&p)?);
509 }
510 _ => return Err(ErrorCode::UnsafePath),
511 }
512 }
513 if locks.is_empty() {
514 locks.push(lock(&p)?);
515 }
516 Ok(Self { path: p, locks })
517 }
518 pub(crate) fn handle(&self) -> &File {
519 self.locks.last().unwrap()
520 }
521 pub fn duplicate(&self) -> Result<Self> {
522 Ok(Self {
523 path: self.path.clone(),
524 locks: self
525 .locks
526 .iter()
527 .map(|f| f.try_clone().map_err(|_| ErrorCode::Io))
528 .collect::<Result<_>>()?,
529 })
530 }
531 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
532 let p = self.path.join(n);
533 match std::fs::symlink_metadata(&p) {
534 Ok(_) => {}
535 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
536 if !create {
537 return Ok(None);
538 }
539 std::fs::create_dir(&p).map_err(crate::space::io_error)?;
540 }
541 Err(_) => return Err(ErrorCode::Io),
542 }
543 let mut d = self.duplicate()?;
544 d.locks.push(lock(&p)?);
545 d.path = p;
546 Ok(Some(d))
547 }
548 pub fn absent(&self, n: &str) -> Result<bool> {
549 match std::fs::symlink_metadata(self.path.join(n)) {
550 Ok(_) => Ok(false),
551 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
552 Err(_) => Err(ErrorCode::Io),
553 }
554 }
555 pub fn existing(&self, n: &str) -> Result<Option<Existing>> {
556 match OpenOptions::new()
557 .access_mode(0x80)
558 .share_mode(7)
559 .custom_flags(0x02000000 | 0x00200000)
560 .open(self.path.join(n))
561 {
562 Ok(file) => existing_file(self.handle(), file).map(Some),
563 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
564 Err(_) => Err(ErrorCode::Io),
565 }
566 }
567 pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> {
568 use std::os::windows::ffi::OsStrExt;
569 unsafe extern "system" {
570 fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
571 }
572 let extended = |name: &str| {
573 [92u16, 92, 63, 92]
574 .into_iter()
575 .chain(
576 self.path
577 .join(name)
578 .as_os_str()
579 .encode_wide()
580 .map(|unit| if unit == 47 { 92 } else { unit }),
581 )
582 .chain(Some(0))
583 .collect::<Vec<_>>()
584 };
585 let from = extended(from);
586 let to = extended(to);
587 // 같은 부모의 이름만 교체하고 복사나 사전 삭제는 하지 않음.
588 if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 1) } != 0 {
589 Ok(())
590 } else {
591 Err(std::io::Error::last_os_error())
592 }
593 }
594 pub fn create(&self, n: &str) -> std::io::Result<File> {
595 OpenOptions::new()
596 .write(true)
597 .create_new(true)
598 .share_mode(0)
599 .custom_flags(0x00200000)
600 .open(self.path.join(n))
601 }
602 /// 이 폴더 안에 닫으면 지워지는 숨김 임시 파일을 만듦.
603 pub(crate) fn temporary(&self) -> Result<File> {
604 crate::spool::windows_temporary(&self.path, ".zipelo-", true)
605 }
606 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
607 std::fs::hard_link(self.path.join(a), self.path.join(b))
608 }
609 pub fn remove(&self, n: &str) -> bool {
610 std::fs::remove_file(self.path.join(n)).is_ok()
611 }
612 pub fn sync(&self) -> Durability {
613 Durability::Unconfirmed
614 }
615 pub(crate) fn sync_checked(&self) -> Result<Durability> {
616 Ok(Durability::Unconfirmed)
617 }
618 }
619}
620#[cfg(not(any(target_os = "linux", windows)))]
621compile_error!("Archive worker supports Linux and Windows only");
622pub use platform::Dir;
623fn parent_with(
624 root: &Dir,
625 name: &str,
626 create: bool,
627 check: &mut impl Monitor,
628) -> Result<Option<(Dir, String)>> {
629 let mut parts = name.split('/').collect::<Vec<_>>();
630 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
631 let mut d = root.duplicate()?;
632 for p in parts {
633 match completed(d.child(p, create), check)? {
634 Some(child) => d = child,
635 None => return Ok(None),
636 }
637 }
638 Ok(Some((d, leaf.to_owned())))
639}
640pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> {
641 existing_with(root, name, &mut || Ok(()))
642}
643pub(crate) fn existing_with(
644 root: &Dir,
645 name: &str,
646 check: &mut impl Monitor,
647) -> Result<Option<Existing>> {
648 valid_name(name, false)?;
649 let result = match parent_with(root, name, false, check)? {
650 Some((dir, leaf)) => dir.existing(&leaf),
651 None => Ok(None),
652 };
653 completed(result, check)
654}
655pub fn unused(root: &Dir, name: &str) -> Result<bool> {
656 unused_with(root, name, &mut || Ok(()))
657}
658pub(crate) fn unused_with(root: &Dir, name: &str, check: &mut impl Monitor) -> Result<bool> {
659 valid_name(name, false)?;
660 let result = match parent_with(root, name, false, check)? {
661 Some((dir, leaf)) => dir.absent(&leaf),
662 None => Ok(true),
663 };
664 completed(result, check)
665}
666pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
667 preflight_mode(root, names, false)
668}
669pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> {
670 preflight_mode_with(root, names, interactive, &mut || Ok(()))
671}
672pub(crate) fn preflight_mode_with(
673 root: &Dir,
674 names: &[(String, EntryKind)],
675 interactive: bool,
676 check: &mut impl Monitor,
677) -> Result<()> {
678 for (name, kind) in names {
679 check.check()?;
680 if let Some((d, leaf)) = parent_with(root, name, false, check)? {
681 if *kind == EntryKind::Directory {
682 let _ = d.child(&leaf, false)?;
683 } else if interactive {
684 d.existing(&leaf)?;
685 } else if !d.absent(&leaf)? {
686 return Err(ErrorCode::Conflict);
687 }
688 }
689 completed(Ok(()), check)?;
690 }
691 Ok(())
692}
693pub(crate) fn preflight_space_with(
694 root: &Dir,
695 files: &[(String, u64)],
696 staging: Option<(&File, u64)>,
697 check: &mut impl Monitor,
698) -> Result<()> {
699 let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
700 let mut charge = |file: &File, bytes: u64| -> Result<()> {
701 crate::space::ensure(file, bytes)?;
702 let volume = crate::space::volume(file)?;
703 if let Some((_, total)) = volumes.get_mut(&volume) {
704 *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?;
705 } else {
706 volumes.insert(
707 volume,
708 (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes),
709 );
710 }
711 Ok(())
712 };
713 if let Some((file, bytes)) = staging {
714 completed(charge(file, bytes), check)?;
715 }
716 for (name, size) in files {
717 valid_name(name, false)?;
718 let mut parent = root.duplicate()?;
719 let mut parts = name.split('/').collect::<Vec<_>>();
720 parts.pop();
721 for part in parts {
722 match completed(parent.child(part, false), check)? {
723 Some(child) => parent = child,
724 None => break,
725 }
726 }
727 completed(charge(parent.handle(), *size), check)?;
728 }
729 for (file, bytes) in volumes.values() {
730 completed(crate::space::ensure(file, *bytes), check)?;
731 }
732 Ok(())
733}
734pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
735 directory_with(root, name, &mut || Ok(()))
736}
737pub(crate) fn directory_with(
738 root: &Dir,
739 name: &str,
740 check: &mut impl Monitor,
741) -> Result<(bool, Durability, Option<ErrorCode>)> {
742 directory_steps(root, name, &mut |step| match step {
743 PublishStep::Check | PublishStep::Commit(_) => check.check(),
744 PublishStep::Activity => check.activity(),
745 })
746}
747pub(crate) fn directory_steps(
748 root: &Dir,
749 name: &str,
750 check: &mut impl FnMut(PublishStep) -> Result<()>,
751) -> Result<(bool, Durability, Option<ErrorCode>)> {
752 let (d, leaf) =
753 parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
754 if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() {
755 return Ok((false, Durability::NotApplicable, None));
756 }
757 check(PublishStep::Commit(None))?;
758 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
759 let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err();
760 Ok(match d.sync_checked() {
761 Ok(durability) => (
762 true,
763 durability,
764 progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()),
765 ),
766 Err(error) => (true, Durability::Failed, Some(error)),
767 })
768}
769pub struct Published {
770 pub created: bool,
771 pub uncertain: bool,
772 pub error: Option<ErrorCode>,
773 pub durability: Durability,
774 pub cleanup: Cleanup,
775 pub retained: u64,
776 pub retained_name: Option<String>,
777}
778pub fn publish(
779 root: &Dir,
780 name: &str,
781 data: &[u8],
782 check: &mut impl FnMut(bool) -> Result<()>,
783) -> Published {
784 publish_reader(
785 root,
786 name,
787 &mut std::io::Cursor::new(data),
788 data.len() as u64,
789 check,
790 )
791}
792
793pub fn publish_reader(
794 root: &Dir,
795 name: &str,
796 data: &mut impl Read,
797 length: u64,
798 check: &mut impl FnMut(bool) -> Result<()>,
799) -> Published {
800 publish_reader_mode(root, name, data, length, None, check)
801}
802pub fn publish_reader_mode(
803 root: &Dir,
804 name: &str,
805 data: &mut impl Read,
806 length: u64,
807 replace: Option<&Existing>,
808 check: &mut impl FnMut(bool) -> Result<()>,
809) -> Published {
810 publish_reader_steps(root, name, data, length, replace, &mut |step| match step {
811 PublishStep::Check => check(false),
812 PublishStep::Commit(_) => check(true),
813 PublishStep::Activity => Ok(()),
814 })
815}
816pub(crate) struct PublicationTemp {
817 pub parent: SourceObject,
818 pub name: String,
819 pub object: SourceObject,
820}
821pub(crate) enum PublishStep {
822 Check,
823 Activity,
824 Commit(Option<PublicationTemp>),
825}
826struct PublicationMonitor<'a, F>(&'a mut F);
827impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> {
828 fn check(&mut self) -> Result<()> {
829 self.0(PublishStep::Check)
830 }
831 fn activity(&mut self) -> Result<()> {
832 self.0(PublishStep::Activity)
833 }
834}
835fn publication_activity(
836 finish: &mut Result<()>,
837 check: &mut impl FnMut(PublishStep) -> Result<()>,
838) {
839 let progress = completed(Ok(()), &mut PublicationMonitor(check));
840 if finish.is_ok() {
841 *finish = progress;
842 }
843}
844pub(crate) fn publish_reader_steps(
845 root: &Dir,
846 name: &str,
847 data: &mut impl Read,
848 length: u64,
849 replace: Option<&Existing>,
850 check: &mut impl FnMut(PublishStep) -> Result<()>,
851) -> Published {
852 let mut result = Published {
853 created: false,
854 uncertain: false,
855 error: None,
856 durability: Durability::NotApplicable,
857 cleanup: Cleanup::Complete,
858 retained: 0,
859 retained_name: None,
860 };
861 let prepared = (|| {
862 valid_name(name, false)?;
863 let (dir, leaf) =
864 parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
865 let temp = format!(
866 ".zipelo-{}-{}.tmp",
867 std::process::id(),
868 TEMP.fetch_add(1, Ordering::Relaxed)
869 );
870 let mut file = dir.create(&temp).map_err(|e| {
871 if e.kind() == std::io::ErrorKind::AlreadyExists {
872 ErrorCode::Conflict
873 } else {
874 crate::space::io_error(e)
875 }
876 })?;
877 let mut temporary = None;
878 let written = (|| {
879 temporary = Some(PublicationTemp {
880 parent: object(dir.handle())?,
881 name: temp.clone(),
882 object: object(&file)?,
883 });
884 completed(Ok(()), &mut PublicationMonitor(check))?;
885 completed(
886 crate::space::ensure(&file, length),
887 &mut PublicationMonitor(check),
888 )?;
889 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
890 let mut remaining = length;
891 while remaining != 0 {
892 check(PublishStep::Check)?;
893 let count = remaining.min(buffer.len() as u64) as usize;
894 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
895 if n == 0 {
896 return Err(ErrorCode::Io);
897 }
898 completed(Ok(()), &mut PublicationMonitor(check))?;
899 completed(
900 crate::space::ensure(&file, n as u64),
901 &mut PublicationMonitor(check),
902 )?;
903 completed(
904 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
905 &mut PublicationMonitor(check),
906 )?;
907 remaining -= n as u64;
908 }
909 completed(
910 file.sync_all().map_err(crate::space::io_error),
911 &mut PublicationMonitor(check),
912 )
913 })();
914 let identity = temporary.as_ref().map(|temp| temp.object.clone());
915 let closed = completed(
916 close(file).map_err(crate::space::io_error),
917 &mut PublicationMonitor(check),
918 );
919 let mut finish = written.and(closed).and_then(|_| {
920 check(PublishStep::Commit(temporary))?;
921 // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 확인함.
922 if dir.existing(&temp)?.as_ref().map(|file| &file.object) != identity.as_ref() {
923 return Err(ErrorCode::Conflict);
924 }
925 // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
926 if let Some(expected) = replace {
927 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
928 != Some(expected)
929 {
930 return Err(ErrorCode::Conflict);
931 }
932 }
933 Ok(())
934 });
935 let mut temp_consumed = false;
936 if finish.is_ok() {
937 let published = if replace.is_some() {
938 dir.replace(&temp, &leaf)
939 } else {
940 dir.link(&temp, &leaf)
941 };
942 match published {
943 Ok(()) => {
944 temp_consumed = replace.is_some();
945 result.created = true;
946 publication_activity(&mut finish, check);
947 match dir.sync_checked() {
948 Ok(durability) => {
949 result.durability = durability;
950 publication_activity(&mut finish, check);
951 }
952 Err(error) => {
953 result.durability = Durability::Failed;
954 finish = Err(error);
955 }
956 }
957 }
958 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
959 finish = Err(ErrorCode::Conflict)
960 }
961 Err(error) => {
962 result.uncertain = true;
963 result.durability = Durability::Unconfirmed;
964 finish = Err(crate::space::io_error(error));
965 }
966 }
967 }
968 if !temp_consumed {
969 match dir.existing(&temp) {
970 Ok(None) => result.cleanup = Cleanup::Unconfirmed,
971 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => {
972 if dir.remove(&temp) {
973 publication_activity(&mut finish, check);
974 } else {
975 result.cleanup = Cleanup::Failed;
976 result.retained = 1;
977 result.retained_name = Some(match name.rsplit_once('/') {
978 Some((prefix, _)) => format!("{prefix}/{temp}"),
979 None => temp.clone(),
980 });
981 }
982 }
983 _ => {
984 // 다른 파일은 보존하고 소유 임시 파일의 위치를 단정하지 않음.
985 result.cleanup = Cleanup::Unconfirmed;
986 }
987 }
988 if result.cleanup != Cleanup::Complete && finish.is_ok() {
989 finish = Err(ErrorCode::Io);
990 }
991 }
992 if result.created {
993 if let Err(error) = dir.sync_checked() {
994 result.durability = Durability::Failed;
995 finish = Err(error);
996 } else {
997 publication_activity(&mut finish, check);
998 }
999 }
1000 if result.created {
1001 // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함.
1002 let verified = match dir.existing(&leaf) {
1003 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => Ok(()),
1004 Ok(_) => Err(ErrorCode::Conflict),
1005 Err(error) => Err(error),
1006 };
1007 if let Err(error) = verified {
1008 result.created = false;
1009 result.uncertain = true;
1010 result.durability = Durability::Unconfirmed;
1011 if result.cleanup == Cleanup::Complete {
1012 result.cleanup = Cleanup::Unconfirmed;
1013 }
1014 finish = Err(error);
1015 }
1016 }
1017 finish
1018 })();
1019 result.error = prepared.err();
1020 result
1021}