team-ljyzipelo

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