team-ljyzipelo

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