team-ljyzipelo

공개
1,072줄37 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 path_is_absent(path: &Path) -> bool {
215 let mut prefix = std::path::PathBuf::new();
216 for component in path.components() {
217 prefix.push(component.as_os_str());
218 match std::fs::symlink_metadata(&prefix) {
219 Ok(metadata) if metadata.is_dir() => {}
220 Ok(_) => return false,
221 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return true,
222 Err(_) => return false,
223 }
224 }
225 false
226 }
227
228 fn sss_is_unused(socket: &Path, cache: &Path) -> bool {
229 path_is_absent(socket)
230 && ["passwd", "group", "initgr"]
231 .iter()
232 .all(|name| path_is_absent(&cache.join(name)))
233 }
234
235 // sss는 소켓과 캐시가 모두 없을 때만 빈 소스로 취급함.
236 fn primary_group_is_private(gid: u32) -> bool {
237 let Ok(policy) = std::fs::read_to_string("/etc/nsswitch.conf") else {
238 return false;
239 };
240 let mut sources = policy.lines().filter_map(|line| {
241 let line = line.split('#').next().unwrap_or_default();
242 let (database, sources) = line.split_once(':')?;
243 (database.trim() == "passwd").then_some(sources)
244 });
245 let Some(source) = sources.next() else {
246 return false;
247 };
248 let source: Vec<_> = source.split_whitespace().collect();
249 if sources.next().is_some()
250 || !matches!(
251 source.as_slice(),
252 ["files"] | ["files", "systemd"] | ["files", "sss"] | ["files", "systemd", "sss"]
253 )
254 || (source.contains(&"sss")
255 && !sss_is_unused(
256 Path::new("/var/lib/sss/pipes/nss"),
257 Path::new("/var/lib/sss/mc"),
258 ))
259 {
260 return false;
261 }
262 let Ok(accounts) = std::fs::read_to_string("/etc/passwd") else {
263 return false;
264 };
265 let current_uid = unsafe { geteuid() };
266 let mut current_name = None;
267 for account in accounts.lines() {
268 if account.trim().is_empty() || account.starts_with('#') {
269 continue;
270 }
271 let fields: Vec<_> = account.split(':').collect();
272 if fields.len() != 7 || fields[0].is_empty() {
273 return false;
274 }
275 let (Ok(uid), Ok(primary_gid)) = (fields[2].parse::<u32>(), fields[3].parse::<u32>())
276 else {
277 return false;
278 };
279 if primary_gid == gid {
280 if uid != current_uid {
281 return false;
282 }
283 if current_name.replace(fields[0]).is_some() {
284 return false;
285 }
286 }
287 }
288 let Some(current_name) = current_name else {
289 return false;
290 };
291 !source.contains(&"systemd")
292 || crate::systemd_userdb::group_is_private(
293 gid,
294 current_uid,
295 current_name,
296 Path::new("/run/systemd/userdb/"),
297 &[
298 Path::new("/etc/userdb"),
299 Path::new("/run/userdb"),
300 Path::new("/run/host/userdb"),
301 Path::new("/usr/local/lib/userdb"),
302 Path::new("/usr/lib/userdb"),
303 ],
304 )
305 }
306
307 // 기본 구성원과 보조 구성원을 모두 확인함.
308 fn private_group(gid: u32) -> bool {
309 if gid != unsafe { getegid() } || !primary_group_is_private(gid) {
310 return false;
311 }
312 let mut group = Group {
313 name: std::ptr::null_mut(),
314 password: std::ptr::null_mut(),
315 gid: 0,
316 members: std::ptr::null_mut(),
317 };
318 let mut result = std::ptr::null_mut();
319 let mut buffer = vec![0i8; 16 * 1024];
320 let status = unsafe {
321 getgrgid_r(
322 gid,
323 &mut group,
324 buffer.as_mut_ptr(),
325 buffer.len(),
326 &mut result,
327 )
328 };
329 // 그룹 정보를 읽지 못하면 안전하다고 볼 근거가 없으므로 거부함.
330 status == 0
331 && !result.is_null()
332 && group.gid == gid
333 && !group.members.is_null()
334 && unsafe { *group.members }.is_null()
335 }
336 pub struct Dir {
337 file: File,
338 }
339 fn name(s: &std::ffi::OsStr) -> Result<CString> {
340 CString::new(s.as_bytes()).map_err(|_| ErrorCode::UnsafePath)
341 }
342 fn open(parent: &File, s: &std::ffi::OsStr, flags: i32) -> std::io::Result<File> {
343 let n = name(s).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
344 // 부모 핸들 기준으로 심볼릭 링크를 따르지 않고 열음.
345 let fd = unsafe {
346 openat(
347 parent.as_raw_fd(),
348 n.as_ptr(),
349 flags | 0x80000 | 0x20000,
350 0o600u32,
351 )
352 };
353 if fd < 0 {
354 return Err(std::io::Error::last_os_error());
355 }
356 Ok(unsafe { File::from_raw_fd(fd) })
357 }
358 impl Dir {
359 pub fn root(path: &Path) -> Result<Self> {
360 if !path.is_absolute() {
361 return Err(ErrorCode::InvalidRequest);
362 }
363 let mut d = Self {
364 file: File::open("/").map_err(|_| ErrorCode::Io)?,
365 };
366 for c in path.components() {
367 match c {
368 Component::RootDir => {}
369 Component::Normal(n) => {
370 d = Self {
371 file: open(&d.file, n, 0x10000).map_err(|_| ErrorCode::UnsafePath)?,
372 }
373 }
374 _ => return Err(ErrorCode::UnsafePath),
375 }
376 }
377 d.trusted()?;
378 Ok(d)
379 }
380 fn trusted(&self) -> Result<()> {
381 let m = self.file.metadata().map_err(|_| ErrorCode::Io)?;
382 // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함.
383 // 그룹 쓰기는 그 그룹이 현재 계정만의 개인 그룹일 때만 허용함.
384 let group_writable = m.mode() & 0o020 != 0;
385 if !m.is_dir()
386 || m.uid() != unsafe { geteuid() }
387 || m.mode() & 0o002 != 0
388 || (group_writable && !private_group(m.gid()))
389 {
390 return Err(ErrorCode::UnsafePath);
391 }
392 Ok(())
393 }
394 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
395 match open(&self.file, std::ffi::OsStr::new(n), 0x10000) {
396 Ok(file) => {
397 let d = Self { file };
398 d.trusted()?;
399 Ok(Some(d))
400 }
401 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
402 if !create {
403 return Ok(None);
404 }
405 let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?;
406 // 고정 부모 안에 새 전용 디렉터리를 생성함.
407 if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 {
408 return Err(crate::space::io_error(std::io::Error::last_os_error()));
409 }
410 let file = open(
411 &self.file,
412 std::ffi::OsStr::new(n.to_str().unwrap()),
413 0x10000,
414 )
415 .map_err(|_| ErrorCode::UnsafePath)?;
416 let d = Self { file };
417 d.trusted()?;
418 Ok(Some(d))
419 }
420 Err(_) => Err(ErrorCode::UnsafePath),
421 }
422 }
423 pub(crate) fn handle(&self) -> &File {
424 &self.file
425 }
426 pub fn duplicate(&self) -> Result<Self> {
427 Ok(Self {
428 file: self.file.try_clone().map_err(|_| ErrorCode::Io)?,
429 })
430 }
431 pub fn absent(&self, n: &str) -> Result<bool> {
432 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
433 Ok(_) => Ok(false),
434 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
435 Err(_) => Err(ErrorCode::Io),
436 }
437 }
438 pub fn existing(&self, n: &str) -> Result<Option<Existing>> {
439 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
440 Ok(file) => existing_file(&self.file, file).map(Some),
441 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
442 Err(_) => Err(ErrorCode::Io),
443 }
444 }
445 pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> {
446 let from = CString::new(from).unwrap();
447 let to = CString::new(to).unwrap();
448 // 고정 부모 안에서 완성된 임시 파일로 원본 이름을 교체함.
449 if unsafe {
450 renameat(
451 self.file.as_raw_fd(),
452 from.as_ptr(),
453 self.file.as_raw_fd(),
454 to.as_ptr(),
455 )
456 } == 0
457 {
458 Ok(())
459 } else {
460 Err(std::io::Error::last_os_error())
461 }
462 }
463 pub fn create(&self, n: &str) -> std::io::Result<File> {
464 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
465 }
466 /// 이 폴더 안에 이름 없는 읽기/쓰기 임시 파일을 만듦. 마지막 핸들을 닫으면 제거됨.
467 pub(crate) fn temporary(&self) -> Result<File> {
468 // O_TMPFILE | O_EXCL: 이름이 생기지 않고 나중에 링크할 수도 없음.
469 match open(&self.file, std::ffi::OsStr::new("."), 2 | 0x410000 | 0x80) {
470 Ok(file) => return Ok(file),
471 Err(e) => {
472 if crate::space::io_error(e) == ErrorCode::DiskFull {
473 return Err(ErrorCode::DiskFull);
474 }
475 }
476 }
477 // O_TMPFILE을 지원하지 않는 파일 시스템은 숨김 이름으로 만든 즉시 이름을 지움.
478 let n = format!(".zipelo-{}.tmp", crate::spool::random_name()?);
479 let file = open(&self.file, std::ffi::OsStr::new(&n), 2 | 0x40 | 0x80)
480 .map_err(crate::space::io_error)?;
481 if !self.remove(&n) {
482 // 핸들을 닫고 한 번 더 지움. 그래도 남으면 정리 실패로 기록해 결과에 알림.
483 drop(file);
484 if !self.remove(&n) && !self.absent(&n).unwrap_or(false) {
485 crate::spool::note_leftover();
486 }
487 return Err(ErrorCode::Io);
488 }
489 if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 {
490 return Err(ErrorCode::Io);
491 }
492 Ok(file)
493 }
494 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
495 let a = CString::new(from).unwrap();
496 let b = CString::new(to).unwrap();
497 // 배타적 hard link 게시로 기존 이름을 보존함.
498 if unsafe {
499 linkat(
500 self.file.as_raw_fd(),
501 a.as_ptr(),
502 self.file.as_raw_fd(),
503 b.as_ptr(),
504 0,
505 )
506 } == 0
507 {
508 Ok(())
509 } else {
510 Err(std::io::Error::last_os_error())
511 }
512 }
513 pub fn remove(&self, n: &str) -> bool {
514 let n = CString::new(n).unwrap();
515 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
516 }
517 pub fn sync(&self) -> Durability {
518 self.sync_checked().unwrap_or(Durability::Failed)
519 }
520 pub(crate) fn sync_checked(&self) -> Result<Durability> {
521 self.file.sync_all().map_err(crate::space::io_error)?;
522 Ok(Durability::Synced)
523 }
524 }
525}
526#[cfg(windows)]
527mod platform {
528 use super::*;
529 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
530 pub struct Dir {
531 path: PathBuf,
532 locks: Vec<File>,
533 }
534 fn lock(path: &Path) -> Result<File> {
535 let f = OpenOptions::new()
536 .access_mode(0x80)
537 .share_mode(3)
538 .custom_flags(0x02000000 | 0x00200000)
539 .open(path)
540 .map_err(|_| ErrorCode::UnsafePath)?;
541 let m = f.metadata().map_err(|_| ErrorCode::Io)?;
542 if !m.is_dir() || m.file_attributes() & 0x400 != 0 {
543 return Err(ErrorCode::UnsafePath);
544 }
545 Ok(f)
546 }
547 impl Dir {
548 pub fn root(path: &Path) -> Result<Self> {
549 let mut p = PathBuf::new();
550 let mut locks = Vec::new();
551 for c in path.components() {
552 match c {
553 Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()),
554 Component::Normal(n) => {
555 if locks.is_empty() {
556 locks.push(lock(&p)?);
557 }
558 p.push(n);
559 locks.push(lock(&p)?);
560 }
561 _ => return Err(ErrorCode::UnsafePath),
562 }
563 }
564 if locks.is_empty() {
565 locks.push(lock(&p)?);
566 }
567 Ok(Self { path: p, locks })
568 }
569 pub(crate) fn handle(&self) -> &File {
570 self.locks.last().unwrap()
571 }
572 pub fn duplicate(&self) -> Result<Self> {
573 Ok(Self {
574 path: self.path.clone(),
575 locks: self
576 .locks
577 .iter()
578 .map(|f| f.try_clone().map_err(|_| ErrorCode::Io))
579 .collect::<Result<_>>()?,
580 })
581 }
582 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
583 let p = self.path.join(n);
584 match std::fs::symlink_metadata(&p) {
585 Ok(_) => {}
586 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
587 if !create {
588 return Ok(None);
589 }
590 std::fs::create_dir(&p).map_err(crate::space::io_error)?;
591 }
592 Err(_) => return Err(ErrorCode::Io),
593 }
594 let mut d = self.duplicate()?;
595 d.locks.push(lock(&p)?);
596 d.path = p;
597 Ok(Some(d))
598 }
599 pub fn absent(&self, n: &str) -> Result<bool> {
600 match std::fs::symlink_metadata(self.path.join(n)) {
601 Ok(_) => Ok(false),
602 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
603 Err(_) => Err(ErrorCode::Io),
604 }
605 }
606 pub fn existing(&self, n: &str) -> Result<Option<Existing>> {
607 match OpenOptions::new()
608 .access_mode(0x80)
609 .share_mode(7)
610 .custom_flags(0x02000000 | 0x00200000)
611 .open(self.path.join(n))
612 {
613 Ok(file) => existing_file(self.handle(), file).map(Some),
614 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
615 Err(_) => Err(ErrorCode::Io),
616 }
617 }
618 pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> {
619 use std::os::windows::ffi::OsStrExt;
620 unsafe extern "system" {
621 fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32;
622 }
623 let extended = |name: &str| {
624 [92u16, 92, 63, 92]
625 .into_iter()
626 .chain(
627 self.path
628 .join(name)
629 .as_os_str()
630 .encode_wide()
631 .map(|unit| if unit == 47 { 92 } else { unit }),
632 )
633 .chain(Some(0))
634 .collect::<Vec<_>>()
635 };
636 let from = extended(from);
637 let to = extended(to);
638 // 같은 부모의 이름만 교체하고 복사나 사전 삭제는 하지 않음.
639 if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 1) } != 0 {
640 Ok(())
641 } else {
642 Err(std::io::Error::last_os_error())
643 }
644 }
645 pub fn create(&self, n: &str) -> std::io::Result<File> {
646 OpenOptions::new()
647 .write(true)
648 .create_new(true)
649 .share_mode(0)
650 .custom_flags(0x00200000)
651 .open(self.path.join(n))
652 }
653 /// 이 폴더 안에 닫으면 지워지는 숨김 임시 파일을 만듦.
654 pub(crate) fn temporary(&self) -> Result<File> {
655 crate::spool::windows_temporary(&self.path, ".zipelo-", true)
656 }
657 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
658 std::fs::hard_link(self.path.join(a), self.path.join(b))
659 }
660 pub fn remove(&self, n: &str) -> bool {
661 std::fs::remove_file(self.path.join(n)).is_ok()
662 }
663 pub fn sync(&self) -> Durability {
664 Durability::Unconfirmed
665 }
666 pub(crate) fn sync_checked(&self) -> Result<Durability> {
667 Ok(Durability::Unconfirmed)
668 }
669 }
670}
671#[cfg(not(any(target_os = "linux", windows)))]
672compile_error!("Archive worker supports Linux and Windows only");
673pub use platform::Dir;
674fn parent_with(
675 root: &Dir,
676 name: &str,
677 create: bool,
678 check: &mut impl Monitor,
679) -> Result<Option<(Dir, String)>> {
680 let mut parts = name.split('/').collect::<Vec<_>>();
681 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
682 let mut d = root.duplicate()?;
683 for p in parts {
684 match completed(d.child(p, create), check)? {
685 Some(child) => d = child,
686 None => return Ok(None),
687 }
688 }
689 Ok(Some((d, leaf.to_owned())))
690}
691pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> {
692 existing_with(root, name, &mut || Ok(()))
693}
694pub(crate) fn existing_with(
695 root: &Dir,
696 name: &str,
697 check: &mut impl Monitor,
698) -> Result<Option<Existing>> {
699 valid_name(name, false)?;
700 let result = match parent_with(root, name, false, check)? {
701 Some((dir, leaf)) => dir.existing(&leaf),
702 None => Ok(None),
703 };
704 completed(result, check)
705}
706pub fn unused(root: &Dir, name: &str) -> Result<bool> {
707 unused_with(root, name, &mut || Ok(()))
708}
709pub(crate) fn unused_with(root: &Dir, name: &str, check: &mut impl Monitor) -> Result<bool> {
710 valid_name(name, false)?;
711 let result = match parent_with(root, name, false, check)? {
712 Some((dir, leaf)) => dir.absent(&leaf),
713 None => Ok(true),
714 };
715 completed(result, check)
716}
717pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
718 preflight_mode(root, names, false)
719}
720pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> {
721 preflight_mode_with(root, names, interactive, &mut || Ok(()))
722}
723pub(crate) fn preflight_mode_with(
724 root: &Dir,
725 names: &[(String, EntryKind)],
726 interactive: bool,
727 check: &mut impl Monitor,
728) -> Result<()> {
729 for (name, kind) in names {
730 check.check()?;
731 if let Some((d, leaf)) = parent_with(root, name, false, check)? {
732 if *kind == EntryKind::Directory {
733 let _ = d.child(&leaf, false)?;
734 } else if interactive {
735 d.existing(&leaf)?;
736 } else if !d.absent(&leaf)? {
737 return Err(ErrorCode::Conflict);
738 }
739 }
740 completed(Ok(()), check)?;
741 }
742 Ok(())
743}
744pub(crate) fn preflight_space_with(
745 root: &Dir,
746 files: &[(String, u64)],
747 staging: Option<(&File, u64)>,
748 check: &mut impl Monitor,
749) -> Result<()> {
750 let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
751 let mut charge = |file: &File, bytes: u64| -> Result<()> {
752 crate::space::ensure(file, bytes)?;
753 let volume = crate::space::volume(file)?;
754 if let Some((_, total)) = volumes.get_mut(&volume) {
755 *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?;
756 } else {
757 volumes.insert(
758 volume,
759 (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes),
760 );
761 }
762 Ok(())
763 };
764 if let Some((file, bytes)) = staging {
765 completed(charge(file, bytes), check)?;
766 }
767 for (name, size) in files {
768 valid_name(name, false)?;
769 let mut parent = root.duplicate()?;
770 let mut parts = name.split('/').collect::<Vec<_>>();
771 parts.pop();
772 for part in parts {
773 match completed(parent.child(part, false), check)? {
774 Some(child) => parent = child,
775 None => break,
776 }
777 }
778 completed(charge(parent.handle(), *size), check)?;
779 }
780 for (file, bytes) in volumes.values() {
781 completed(crate::space::ensure(file, *bytes), check)?;
782 }
783 Ok(())
784}
785pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
786 directory_with(root, name, &mut || Ok(()))
787}
788pub(crate) fn directory_with(
789 root: &Dir,
790 name: &str,
791 check: &mut impl Monitor,
792) -> Result<(bool, Durability, Option<ErrorCode>)> {
793 directory_steps(root, name, &mut |step| match step {
794 PublishStep::Check | PublishStep::Commit(_) => check.check(),
795 PublishStep::Activity => check.activity(),
796 })
797}
798pub(crate) fn directory_steps(
799 root: &Dir,
800 name: &str,
801 check: &mut impl FnMut(PublishStep) -> Result<()>,
802) -> Result<(bool, Durability, Option<ErrorCode>)> {
803 let (d, leaf) =
804 parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
805 if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() {
806 return Ok((false, Durability::NotApplicable, None));
807 }
808 check(PublishStep::Commit(None))?;
809 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
810 let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err();
811 Ok(match d.sync_checked() {
812 Ok(durability) => (
813 true,
814 durability,
815 progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()),
816 ),
817 Err(error) => (true, Durability::Failed, Some(error)),
818 })
819}
820pub struct Published {
821 pub created: bool,
822 pub uncertain: bool,
823 pub error: Option<ErrorCode>,
824 pub durability: Durability,
825 pub cleanup: Cleanup,
826 pub retained: u64,
827 pub retained_name: Option<String>,
828}
829pub fn publish(
830 root: &Dir,
831 name: &str,
832 data: &[u8],
833 check: &mut impl FnMut(bool) -> Result<()>,
834) -> Published {
835 publish_reader(
836 root,
837 name,
838 &mut std::io::Cursor::new(data),
839 data.len() as u64,
840 check,
841 )
842}
843
844pub fn publish_reader(
845 root: &Dir,
846 name: &str,
847 data: &mut impl Read,
848 length: u64,
849 check: &mut impl FnMut(bool) -> Result<()>,
850) -> Published {
851 publish_reader_mode(root, name, data, length, None, check)
852}
853pub fn publish_reader_mode(
854 root: &Dir,
855 name: &str,
856 data: &mut impl Read,
857 length: u64,
858 replace: Option<&Existing>,
859 check: &mut impl FnMut(bool) -> Result<()>,
860) -> Published {
861 publish_reader_steps(root, name, data, length, replace, &mut |step| match step {
862 PublishStep::Check => check(false),
863 PublishStep::Commit(_) => check(true),
864 PublishStep::Activity => Ok(()),
865 })
866}
867pub(crate) struct PublicationTemp {
868 pub parent: SourceObject,
869 pub name: String,
870 pub object: SourceObject,
871}
872pub(crate) enum PublishStep {
873 Check,
874 Activity,
875 Commit(Option<PublicationTemp>),
876}
877struct PublicationMonitor<'a, F>(&'a mut F);
878impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> {
879 fn check(&mut self) -> Result<()> {
880 self.0(PublishStep::Check)
881 }
882 fn activity(&mut self) -> Result<()> {
883 self.0(PublishStep::Activity)
884 }
885}
886fn publication_activity(
887 finish: &mut Result<()>,
888 check: &mut impl FnMut(PublishStep) -> Result<()>,
889) {
890 let progress = completed(Ok(()), &mut PublicationMonitor(check));
891 if finish.is_ok() {
892 *finish = progress;
893 }
894}
895pub(crate) fn publish_reader_steps(
896 root: &Dir,
897 name: &str,
898 data: &mut impl Read,
899 length: u64,
900 replace: Option<&Existing>,
901 check: &mut impl FnMut(PublishStep) -> Result<()>,
902) -> Published {
903 let mut result = Published {
904 created: false,
905 uncertain: false,
906 error: None,
907 durability: Durability::NotApplicable,
908 cleanup: Cleanup::Complete,
909 retained: 0,
910 retained_name: None,
911 };
912 let prepared = (|| {
913 valid_name(name, false)?;
914 let (dir, leaf) =
915 parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
916 let temp = format!(
917 ".zipelo-{}-{}.tmp",
918 std::process::id(),
919 TEMP.fetch_add(1, Ordering::Relaxed)
920 );
921 let mut file = dir.create(&temp).map_err(|e| {
922 if e.kind() == std::io::ErrorKind::AlreadyExists {
923 ErrorCode::Conflict
924 } else {
925 crate::space::io_error(e)
926 }
927 })?;
928 let mut temporary = None;
929 let written = (|| {
930 temporary = Some(PublicationTemp {
931 parent: object(dir.handle())?,
932 name: temp.clone(),
933 object: object(&file)?,
934 });
935 completed(Ok(()), &mut PublicationMonitor(check))?;
936 completed(
937 crate::space::ensure(&file, length),
938 &mut PublicationMonitor(check),
939 )?;
940 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
941 let mut remaining = length;
942 while remaining != 0 {
943 check(PublishStep::Check)?;
944 let count = remaining.min(buffer.len() as u64) as usize;
945 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
946 if n == 0 {
947 return Err(ErrorCode::Io);
948 }
949 completed(Ok(()), &mut PublicationMonitor(check))?;
950 completed(
951 crate::space::ensure(&file, n as u64),
952 &mut PublicationMonitor(check),
953 )?;
954 completed(
955 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
956 &mut PublicationMonitor(check),
957 )?;
958 remaining -= n as u64;
959 }
960 completed(
961 file.sync_all().map_err(crate::space::io_error),
962 &mut PublicationMonitor(check),
963 )
964 })();
965 let identity = temporary.as_ref().map(|temp| temp.object.clone());
966 let closed = completed(
967 close(file).map_err(crate::space::io_error),
968 &mut PublicationMonitor(check),
969 );
970 let mut finish = written.and(closed).and_then(|_| {
971 check(PublishStep::Commit(temporary))?;
972 // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 확인함.
973 if dir.existing(&temp)?.as_ref().map(|file| &file.object) != identity.as_ref() {
974 return Err(ErrorCode::Conflict);
975 }
976 // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
977 if let Some(expected) = replace {
978 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
979 != Some(expected)
980 {
981 return Err(ErrorCode::Conflict);
982 }
983 }
984 Ok(())
985 });
986 let mut temp_consumed = false;
987 if finish.is_ok() {
988 let published = if replace.is_some() {
989 dir.replace(&temp, &leaf)
990 } else {
991 dir.link(&temp, &leaf)
992 };
993 match published {
994 Ok(()) => {
995 temp_consumed = replace.is_some();
996 result.created = true;
997 publication_activity(&mut finish, check);
998 match dir.sync_checked() {
999 Ok(durability) => {
1000 result.durability = durability;
1001 publication_activity(&mut finish, check);
1002 }
1003 Err(error) => {
1004 result.durability = Durability::Failed;
1005 finish = Err(error);
1006 }
1007 }
1008 }
1009 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1010 finish = Err(ErrorCode::Conflict)
1011 }
1012 Err(error) => {
1013 result.uncertain = true;
1014 result.durability = Durability::Unconfirmed;
1015 finish = Err(crate::space::io_error(error));
1016 }
1017 }
1018 }
1019 if !temp_consumed {
1020 match dir.existing(&temp) {
1021 Ok(None) => result.cleanup = Cleanup::Unconfirmed,
1022 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => {
1023 if dir.remove(&temp) {
1024 publication_activity(&mut finish, check);
1025 } else {
1026 result.cleanup = Cleanup::Failed;
1027 result.retained = 1;
1028 result.retained_name = Some(match name.rsplit_once('/') {
1029 Some((prefix, _)) => format!("{prefix}/{temp}"),
1030 None => temp.clone(),
1031 });
1032 }
1033 }
1034 _ => {
1035 // 다른 파일은 보존하고 소유 임시 파일의 위치를 단정하지 않음.
1036 result.cleanup = Cleanup::Unconfirmed;
1037 }
1038 }
1039 if result.cleanup != Cleanup::Complete && finish.is_ok() {
1040 finish = Err(ErrorCode::Io);
1041 }
1042 }
1043 if result.created {
1044 if let Err(error) = dir.sync_checked() {
1045 result.durability = Durability::Failed;
1046 finish = Err(error);
1047 } else {
1048 publication_activity(&mut finish, check);
1049 }
1050 }
1051 if result.created {
1052 // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함.
1053 let verified = match dir.existing(&leaf) {
1054 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => Ok(()),
1055 Ok(_) => Err(ErrorCode::Conflict),
1056 Err(error) => Err(error),
1057 };
1058 if let Err(error) = verified {
1059 result.created = false;
1060 result.uncertain = true;
1061 result.durability = Durability::Unconfirmed;
1062 if result.cleanup == Cleanup::Complete {
1063 result.cleanup = Cleanup::Unconfirmed;
1064 }
1065 finish = Err(error);
1066 }
1067 }
1068 finish
1069 })();
1070 result.error = prepared.err();
1071 result
1072}