team-ljyzipelo

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