team-ljyzipelo

공개
1,344줄47 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 /// 분할 볼륨처럼 한 번에 게시하는 나머지 임시 파일 (이름, 객체).
939 pub others: Vec<(String, SourceObject)>,
940}
941pub(crate) enum PublishStep {
942 Check,
943 Activity,
944 Commit(Option<PublicationTemp>),
945}
946struct PublicationMonitor<'a, F>(&'a mut F);
947impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> {
948 fn check(&mut self) -> Result<()> {
949 self.0(PublishStep::Check)
950 }
951 fn activity(&mut self) -> Result<()> {
952 self.0(PublishStep::Activity)
953 }
954}
955fn publication_activity(
956 finish: &mut Result<()>,
957 check: &mut impl FnMut(PublishStep) -> Result<()>,
958) {
959 let progress = completed(Ok(()), &mut PublicationMonitor(check));
960 if finish.is_ok() {
961 *finish = progress;
962 }
963}
964pub(crate) fn publish_reader_steps(
965 root: &Dir,
966 name: &str,
967 data: &mut impl Read,
968 length: u64,
969 replace: Option<&Existing>,
970 check: &mut impl FnMut(PublishStep) -> Result<()>,
971) -> Published {
972 let mut result = Published {
973 created: false,
974 uncertain: false,
975 error: None,
976 durability: Durability::NotApplicable,
977 cleanup: Cleanup::Complete,
978 retained: 0,
979 retained_name: None,
980 };
981 let prepared = (|| {
982 valid_name(name, false)?;
983 let (dir, leaf) =
984 parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
985 let temp = format!(
986 ".zipelo-{}-{}.tmp",
987 std::process::id(),
988 TEMP.fetch_add(1, Ordering::Relaxed)
989 );
990 let mut file = dir.create(&temp).map_err(|e| {
991 if e.kind() == std::io::ErrorKind::AlreadyExists {
992 ErrorCode::Conflict
993 } else {
994 crate::space::io_error(e)
995 }
996 })?;
997 let mut temporary = None;
998 let written = (|| {
999 temporary = Some(PublicationTemp {
1000 parent: object(dir.handle())?,
1001 name: temp.clone(),
1002 object: object(&file)?,
1003 others: Vec::new(),
1004 });
1005 completed(Ok(()), &mut PublicationMonitor(check))?;
1006 completed(
1007 crate::space::ensure(&file, length),
1008 &mut PublicationMonitor(check),
1009 )?;
1010 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
1011 let mut remaining = length;
1012 while remaining != 0 {
1013 check(PublishStep::Check)?;
1014 let count = remaining.min(buffer.len() as u64) as usize;
1015 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
1016 if n == 0 {
1017 return Err(ErrorCode::Io);
1018 }
1019 completed(Ok(()), &mut PublicationMonitor(check))?;
1020 completed(
1021 crate::space::ensure(&file, n as u64),
1022 &mut PublicationMonitor(check),
1023 )?;
1024 completed(
1025 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
1026 &mut PublicationMonitor(check),
1027 )?;
1028 remaining -= n as u64;
1029 }
1030 completed(
1031 file.sync_all().map_err(crate::space::io_error),
1032 &mut PublicationMonitor(check),
1033 )
1034 })();
1035 let identity = temporary.as_ref().map(|temp| temp.object.clone());
1036 let closed = completed(
1037 close(file).map_err(crate::space::io_error),
1038 &mut PublicationMonitor(check),
1039 );
1040 let mut finish = written.and(closed).and_then(|_| {
1041 check(PublishStep::Commit(temporary))?;
1042 // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 확인함.
1043 if dir.existing(&temp)?.as_ref().map(|file| &file.object) != identity.as_ref() {
1044 return Err(ErrorCode::Conflict);
1045 }
1046 // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함.
1047 if let Some(expected) = replace {
1048 if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref()
1049 != Some(expected)
1050 {
1051 return Err(ErrorCode::Conflict);
1052 }
1053 }
1054 Ok(())
1055 });
1056 let mut temp_consumed = false;
1057 if finish.is_ok() {
1058 let published = if replace.is_some() {
1059 dir.replace(&temp, &leaf)
1060 } else {
1061 dir.link(&temp, &leaf)
1062 };
1063 match published {
1064 Ok(()) => {
1065 temp_consumed = replace.is_some();
1066 result.created = true;
1067 publication_activity(&mut finish, check);
1068 match dir.sync_checked() {
1069 Ok(durability) => {
1070 result.durability = durability;
1071 publication_activity(&mut finish, check);
1072 }
1073 Err(error) => {
1074 result.durability = Durability::Failed;
1075 finish = Err(error);
1076 }
1077 }
1078 }
1079 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1080 finish = Err(ErrorCode::Conflict)
1081 }
1082 Err(error) => {
1083 result.uncertain = true;
1084 result.durability = Durability::Unconfirmed;
1085 finish = Err(crate::space::io_error(error));
1086 }
1087 }
1088 }
1089 if !temp_consumed {
1090 match dir.existing(&temp) {
1091 Ok(None) => result.cleanup = Cleanup::Unconfirmed,
1092 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => {
1093 if dir.remove(&temp) {
1094 publication_activity(&mut finish, check);
1095 } else {
1096 result.cleanup = Cleanup::Failed;
1097 result.retained = 1;
1098 result.retained_name = Some(match name.rsplit_once('/') {
1099 Some((prefix, _)) => format!("{prefix}/{temp}"),
1100 None => temp.clone(),
1101 });
1102 }
1103 }
1104 _ => {
1105 // 다른 파일은 보존하고 소유 임시 파일의 위치를 단정하지 않음.
1106 result.cleanup = Cleanup::Unconfirmed;
1107 }
1108 }
1109 if result.cleanup != Cleanup::Complete && finish.is_ok() {
1110 finish = Err(ErrorCode::Io);
1111 }
1112 }
1113 if result.created {
1114 if let Err(error) = dir.sync_checked() {
1115 result.durability = Durability::Failed;
1116 finish = Err(error);
1117 } else {
1118 publication_activity(&mut finish, check);
1119 }
1120 }
1121 if result.created {
1122 // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함.
1123 let verified = match dir.existing(&leaf) {
1124 Ok(Some(current)) if Some(&current.object) == identity.as_ref() => Ok(()),
1125 Ok(_) => Err(ErrorCode::Conflict),
1126 Err(error) => Err(error),
1127 };
1128 if let Err(error) = verified {
1129 result.created = false;
1130 result.uncertain = true;
1131 result.durability = Durability::Unconfirmed;
1132 if result.cleanup == Cleanup::Complete {
1133 result.cleanup = Cleanup::Unconfirmed;
1134 }
1135 finish = Err(error);
1136 }
1137 }
1138 finish
1139 })();
1140 result.error = prepared.err();
1141 result
1142}
1143
1144/// 여러 파일을 한 묶음으로 게시한 결과. `created`는 게시된 채 남은 이름.
1145pub(crate) struct PublishedSet {
1146 pub created: Vec<String>,
1147 pub uncertain: bool,
1148 pub error: Option<ErrorCode>,
1149 pub durability: Durability,
1150 pub cleanup: Cleanup,
1151 pub retained: Vec<String>,
1152}
1153struct Staged {
1154 temp: String,
1155 object: Option<SourceObject>,
1156}
1157/// 분할 볼륨을 같은 폴더에 모두 임시 파일로 쓴 뒤 한 번의 확정 단계로 게시함.
1158/// 쓰기 중 실패나 취소는 임시 파일만 지우고, 게시 중 실패는 이미 게시한 볼륨을 되돌림.
1159/// 이름은 `root` 바로 아래 파일 이름이어야 하고 기존 이름은 덮어쓰지 않음.
1160pub(crate) fn publish_set_steps(
1161 root: &Dir,
1162 files: &[(String, u64)],
1163 data: &mut impl Read,
1164 check: &mut impl FnMut(PublishStep) -> Result<()>,
1165) -> PublishedSet {
1166 let mut result = PublishedSet {
1167 created: Vec::new(),
1168 uncertain: false,
1169 error: None,
1170 durability: Durability::NotApplicable,
1171 cleanup: Cleanup::Complete,
1172 retained: Vec::new(),
1173 };
1174 let mut staged: Vec<Staged> = Vec::new();
1175 let mut linked = 0usize;
1176 let mut finish = (|| {
1177 if files.is_empty() {
1178 return Err(ErrorCode::InvalidRequest);
1179 }
1180 for (name, _) in files {
1181 valid_name(name, false)?;
1182 if name.contains('/') {
1183 return Err(ErrorCode::InvalidRequest);
1184 }
1185 }
1186 let parent = object(root.handle())?;
1187 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
1188 for (_, length) in files {
1189 check(PublishStep::Check)?;
1190 let temp = format!(
1191 ".zipelo-{}-{}.tmp",
1192 std::process::id(),
1193 TEMP.fetch_add(1, Ordering::Relaxed)
1194 );
1195 let mut file = root.create(&temp).map_err(|e| {
1196 if e.kind() == std::io::ErrorKind::AlreadyExists {
1197 ErrorCode::Conflict
1198 } else {
1199 crate::space::io_error(e)
1200 }
1201 })?;
1202 staged.push(Staged { temp, object: None });
1203 let written = (|| {
1204 staged.last_mut().ok_or(ErrorCode::Internal)?.object = Some(object(&file)?);
1205 completed(
1206 crate::space::ensure(&file, *length),
1207 &mut PublicationMonitor(check),
1208 )?;
1209 let mut remaining = *length;
1210 while remaining != 0 {
1211 check(PublishStep::Check)?;
1212 let count = remaining.min(buffer.len() as u64) as usize;
1213 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
1214 if n == 0 {
1215 return Err(ErrorCode::Io);
1216 }
1217 completed(
1218 crate::space::ensure(&file, n as u64),
1219 &mut PublicationMonitor(check),
1220 )?;
1221 completed(
1222 file.write_all(&buffer[..n]).map_err(crate::space::io_error),
1223 &mut PublicationMonitor(check),
1224 )?;
1225 remaining -= n as u64;
1226 }
1227 completed(
1228 file.sync_all().map_err(crate::space::io_error),
1229 &mut PublicationMonitor(check),
1230 )
1231 })();
1232 let closed = completed(
1233 close(file).map_err(crate::space::io_error),
1234 &mut PublicationMonitor(check),
1235 );
1236 written.and(closed)?;
1237 }
1238 let mut owned = staged
1239 .iter()
1240 .map(|s| Ok((s.temp.clone(), s.object.clone().ok_or(ErrorCode::Internal)?)))
1241 .collect::<Result<Vec<_>>>()?;
1242 let (name, first) = owned.remove(0);
1243 check(PublishStep::Commit(Some(PublicationTemp {
1244 parent,
1245 name,
1246 object: first,
1247 others: owned,
1248 })))?;
1249 // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 모두 확인함.
1250 for s in &staged {
1251 if root.existing(&s.temp)?.as_ref().map(|file| &file.object) != s.object.as_ref() {
1252 return Err(ErrorCode::Conflict);
1253 }
1254 }
1255 for ((name, _), s) in files.iter().zip(&staged) {
1256 match root.link(&s.temp, name) {
1257 Ok(()) => linked += 1,
1258 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1259 return Err(ErrorCode::Conflict);
1260 }
1261 Err(error) => {
1262 // 실패한 이름도 되돌리기 대상으로 보고 아래에서 소유 여부를 확인함.
1263 linked += 1;
1264 return Err(crate::space::io_error(error));
1265 }
1266 }
1267 }
1268 Ok(())
1269 })();
1270 if finish.is_err() {
1271 // 게시한 볼륨 중 이 작업이 만든 것만 지움. 다른 파일은 보존함.
1272 for ((name, _), s) in files.iter().zip(&staged).take(linked) {
1273 match root.existing(name) {
1274 Ok(Some(current)) if Some(&current.object) == s.object.as_ref() => {
1275 if !root.remove(name) {
1276 result.created.push(name.clone());
1277 }
1278 }
1279 Ok(_) => {}
1280 Err(_) => result.uncertain = true,
1281 }
1282 }
1283 } else {
1284 result.created = files.iter().map(|(name, _)| name.clone()).collect();
1285 publication_activity(&mut finish, check);
1286 }
1287 for s in &staged {
1288 match root.existing(&s.temp) {
1289 Ok(None) => result.cleanup = Cleanup::Unconfirmed,
1290 Ok(Some(current)) if s.object.as_ref() == Some(&current.object) => {
1291 if root.remove(&s.temp) {
1292 publication_activity(&mut finish, check);
1293 } else {
1294 result.cleanup = Cleanup::Failed;
1295 result.retained.push(s.temp.clone());
1296 }
1297 }
1298 // 이름만 만들고 객체를 확인하지 못한 임시 파일이나 다른 파일은 보존함.
1299 _ => {
1300 if s.object.is_none() && root.remove(&s.temp) {
1301 continue;
1302 }
1303 result.cleanup = Cleanup::Unconfirmed;
1304 }
1305 }
1306 }
1307 if result.cleanup != Cleanup::Complete && finish.is_ok() {
1308 finish = Err(ErrorCode::Io);
1309 }
1310 if !result.created.is_empty() || linked != 0 {
1311 match root.sync_checked() {
1312 Ok(durability) => {
1313 result.durability = durability;
1314 publication_activity(&mut finish, check);
1315 }
1316 Err(error) => {
1317 result.durability = Durability::Failed;
1318 if finish.is_ok() {
1319 finish = Err(error);
1320 }
1321 }
1322 }
1323 }
1324 if finish.is_ok() {
1325 // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함.
1326 for ((name, _), s) in files.iter().zip(&staged) {
1327 let verified = match root.existing(name) {
1328 Ok(Some(current)) if s.object.as_ref() == Some(&current.object) => Ok(()),
1329 Ok(_) => Err(ErrorCode::Conflict),
1330 Err(error) => Err(error),
1331 };
1332 if let Err(error) = verified {
1333 result.created.retain(|created| created != name);
1334 result.uncertain = true;
1335 result.durability = Durability::Unconfirmed;
1336 if finish.is_ok() {
1337 finish = Err(error);
1338 }
1339 }
1340 }
1341 }
1342 result.error = finish.err();
1343 result
1344}