team-ljyzipelo

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