team-ljyzipelo

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