team-ljyzipelo

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