team-ljyzipelo

공개
597줄20 KB
1use crate::archive::valid_name;
2use crate::protocol::*;
3use sha2::{Digest, Sha256};
4use std::fs::{File, OpenOptions};
5use std::io::{Read, Write};
6#[cfg(windows)]
7use std::path::PathBuf;
8use std::path::{Component, Path};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11type Result<T> = std::result::Result<T, ErrorCode>;
12static TEMP: AtomicU64 = AtomicU64::new(0);
13pub struct Snapshot {
14 pub bytes: Vec<u8>,
15 pub object: SourceObject,
16 pub hash: [u8; 32],
17}
18#[cfg(unix)]
19pub fn object(file: &File) -> Result<SourceObject> {
20 use std::os::unix::fs::MetadataExt;
21 let m = file.metadata().map_err(|_| ErrorCode::Io)?;
22 Ok(SourceObject::Unix {
23 device: m.dev(),
24 inode: m.ino(),
25 })
26}
27#[cfg(windows)]
28pub fn object(file: &File) -> Result<SourceObject> {
29 use std::os::windows::io::AsRawHandle;
30 #[repr(C)]
31 struct Info {
32 volume: u64,
33 id: [u8; 16],
34 }
35 unsafe extern "system" {
36 fn GetFileInformationByHandleEx(
37 h: *mut std::ffi::c_void,
38 class: u32,
39 info: *mut std::ffi::c_void,
40 size: u32,
41 ) -> i32;
42 }
43 let mut info = Info {
44 volume: 0,
45 id: [0; 16],
46 };
47 // 열린 핸들에 대해 고정 크기의 파일 식별 정보를 조회함.
48 if unsafe {
49 GetFileInformationByHandleEx(
50 file.as_raw_handle(),
51 18,
52 (&mut info as *mut Info).cast(),
53 size_of::<Info>() as u32,
54 )
55 } == 0
56 {
57 return Err(ErrorCode::UnsupportedFeature);
58 }
59 Ok(SourceObject::Windows {
60 volume_serial: info.volume,
61 file_id: info.id,
62 })
63}
64pub fn snapshot(
65 path: &Path,
66 limit: u64,
67 check: &mut impl FnMut() -> Result<()>,
68) -> Result<Snapshot> {
69 let mut options = OpenOptions::new();
70 options.read(true);
71 #[cfg(unix)]
72 {
73 use std::os::unix::fs::OpenOptionsExt;
74 options.custom_flags(0x20000 | 0x800);
75 }
76 #[cfg(windows)]
77 {
78 use std::os::windows::fs::OpenOptionsExt;
79 options.share_mode(1);
80 }
81 let mut file = options.open(path).map_err(|_| ErrorCode::Io)?;
82 let before = file.metadata().map_err(|_| ErrorCode::Io)?;
83 if !before.is_file() {
84 return Err(ErrorCode::InvalidRequest);
85 }
86 if before.len() > limit {
87 return Err(ErrorCode::Limit);
88 }
89 let identity = object(&file)?;
90 let mut bytes = Vec::new();
91 let mut hash = Sha256::new();
92 let mut buffer = [0; 65536];
93 loop {
94 check()?;
95 let n = file.read(&mut buffer).map_err(|_| ErrorCode::Io)?;
96 if n == 0 {
97 break;
98 }
99 if bytes.len() as u64 + n as u64 > limit {
100 return Err(ErrorCode::Limit);
101 }
102 bytes.try_reserve(n).map_err(|_| ErrorCode::Limit)?;
103 bytes.extend_from_slice(&buffer[..n]);
104 hash.update(&buffer[..n]);
105 }
106 let after = file.metadata().map_err(|_| ErrorCode::Io)?;
107 let named = options.open(path).map_err(|_| ErrorCode::SourceChanged)?;
108 if !named
109 .metadata()
110 .map_err(|_| ErrorCode::SourceChanged)?
111 .is_file()
112 || object(&named)? != identity
113 || object(&file)? != identity
114 || before.len() != after.len()
115 || after.len() != bytes.len() as u64
116 || before.modified().ok() != after.modified().ok()
117 {
118 return Err(ErrorCode::SourceChanged);
119 }
120 close(file).map_err(|_| ErrorCode::Io)?;
121 Ok(Snapshot {
122 bytes,
123 object: identity,
124 hash: hash.finalize().into(),
125 })
126}
127#[cfg(unix)]
128fn close(file: File) -> std::io::Result<()> {
129 use std::os::unix::io::IntoRawFd;
130 unsafe extern "C" {
131 fn close(fd: i32) -> i32;
132 }
133 // 소유한 파일 디스크립터를 한 번만 닫음.
134 if unsafe { close(file.into_raw_fd()) } == 0 {
135 Ok(())
136 } else {
137 Err(std::io::Error::last_os_error())
138 }
139}
140#[cfg(windows)]
141fn close(file: File) -> std::io::Result<()> {
142 use std::os::windows::io::IntoRawHandle;
143 unsafe extern "system" {
144 fn CloseHandle(h: *mut std::ffi::c_void) -> i32;
145 }
146 // 소유한 핸들을 한 번만 닫음.
147 if unsafe { CloseHandle(file.into_raw_handle()) } != 0 {
148 Ok(())
149 } else {
150 Err(std::io::Error::last_os_error())
151 }
152}
153#[cfg(target_os = "linux")]
154mod platform {
155 use super::*;
156 use std::ffi::CString;
157 use std::os::unix::{
158 ffi::OsStrExt,
159 fs::MetadataExt,
160 io::{AsRawFd, FromRawFd},
161 };
162 unsafe extern "C" {
163 fn openat(fd: i32, path: *const i8, flags: i32, ...) -> i32;
164 fn mkdirat(fd: i32, path: *const i8, mode: u32) -> i32;
165 fn linkat(fd: i32, path: *const i8, newfd: i32, newpath: *const i8, flags: i32) -> i32;
166 fn unlinkat(fd: i32, path: *const i8, flags: i32) -> i32;
167 fn geteuid() -> u32;
168 }
169 pub struct Dir {
170 file: File,
171 }
172 fn name(s: &std::ffi::OsStr) -> Result<CString> {
173 CString::new(s.as_bytes()).map_err(|_| ErrorCode::UnsafePath)
174 }
175 fn open(parent: &File, s: &std::ffi::OsStr, flags: i32) -> std::io::Result<File> {
176 let n = name(s).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
177 // 부모 핸들 기준으로 심볼릭 링크를 따르지 않고 열음.
178 let fd = unsafe {
179 openat(
180 parent.as_raw_fd(),
181 n.as_ptr(),
182 flags | 0x80000 | 0x20000,
183 0o600u32,
184 )
185 };
186 if fd < 0 {
187 return Err(std::io::Error::last_os_error());
188 }
189 Ok(unsafe { File::from_raw_fd(fd) })
190 }
191 impl Dir {
192 pub fn root(path: &Path) -> Result<Self> {
193 if !path.is_absolute() {
194 return Err(ErrorCode::InvalidRequest);
195 }
196 let mut d = Self {
197 file: File::open("/").map_err(|_| ErrorCode::Io)?,
198 };
199 for c in path.components() {
200 match c {
201 Component::RootDir => {}
202 Component::Normal(n) => {
203 d = Self {
204 file: open(&d.file, n, 0x10000).map_err(|_| ErrorCode::UnsafePath)?,
205 }
206 }
207 _ => return Err(ErrorCode::UnsafePath),
208 }
209 }
210 d.trusted()?;
211 Ok(d)
212 }
213 fn trusted(&self) -> Result<()> {
214 let m = self.file.metadata().map_err(|_| ErrorCode::Io)?;
215 // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함.
216 if !m.is_dir() || m.uid() != unsafe { geteuid() } || m.mode() & 0o022 != 0 {
217 return Err(ErrorCode::UnsafePath);
218 }
219 Ok(())
220 }
221 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
222 match open(&self.file, std::ffi::OsStr::new(n), 0x10000) {
223 Ok(file) => {
224 let d = Self { file };
225 d.trusted()?;
226 Ok(Some(d))
227 }
228 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
229 if !create {
230 return Ok(None);
231 }
232 let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?;
233 // 고정 부모 안에 새 전용 디렉터리를 생성함.
234 if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 {
235 return Err(crate::space::io_error(std::io::Error::last_os_error()));
236 }
237 let file = open(
238 &self.file,
239 std::ffi::OsStr::new(n.to_str().unwrap()),
240 0x10000,
241 )
242 .map_err(|_| ErrorCode::UnsafePath)?;
243 let d = Self { file };
244 d.trusted()?;
245 Ok(Some(d))
246 }
247 Err(_) => Err(ErrorCode::UnsafePath),
248 }
249 }
250 pub(crate) fn handle(&self) -> &File {
251 &self.file
252 }
253 pub fn duplicate(&self) -> Result<Self> {
254 Ok(Self {
255 file: self.file.try_clone().map_err(|_| ErrorCode::Io)?,
256 })
257 }
258 pub fn absent(&self, n: &str) -> Result<bool> {
259 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
260 Ok(_) => Ok(false),
261 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
262 Err(_) => Err(ErrorCode::Io),
263 }
264 }
265 pub fn create(&self, n: &str) -> std::io::Result<File> {
266 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
267 }
268 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
269 let a = CString::new(from).unwrap();
270 let b = CString::new(to).unwrap();
271 // 배타적 hard link 게시로 기존 이름을 보존함.
272 if unsafe {
273 linkat(
274 self.file.as_raw_fd(),
275 a.as_ptr(),
276 self.file.as_raw_fd(),
277 b.as_ptr(),
278 0,
279 )
280 } == 0
281 {
282 Ok(())
283 } else {
284 Err(std::io::Error::last_os_error())
285 }
286 }
287 pub fn remove(&self, n: &str) -> bool {
288 let n = CString::new(n).unwrap();
289 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
290 }
291 pub fn sync(&self) -> Durability {
292 self.sync_checked().unwrap_or(Durability::Failed)
293 }
294 pub(crate) fn sync_checked(&self) -> Result<Durability> {
295 self.file.sync_all().map_err(crate::space::io_error)?;
296 Ok(Durability::Synced)
297 }
298 }
299}
300#[cfg(windows)]
301mod platform {
302 use super::*;
303 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
304 pub struct Dir {
305 path: PathBuf,
306 locks: Vec<File>,
307 }
308 fn lock(path: &Path) -> Result<File> {
309 let f = OpenOptions::new()
310 .access_mode(0x80)
311 .share_mode(3)
312 .custom_flags(0x02000000 | 0x00200000)
313 .open(path)
314 .map_err(|_| ErrorCode::UnsafePath)?;
315 let m = f.metadata().map_err(|_| ErrorCode::Io)?;
316 if !m.is_dir() || m.file_attributes() & 0x400 != 0 {
317 return Err(ErrorCode::UnsafePath);
318 }
319 Ok(f)
320 }
321 impl Dir {
322 pub fn root(path: &Path) -> Result<Self> {
323 let mut p = PathBuf::new();
324 let mut locks = Vec::new();
325 for c in path.components() {
326 match c {
327 Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()),
328 Component::Normal(n) => {
329 if locks.is_empty() {
330 locks.push(lock(&p)?);
331 }
332 p.push(n);
333 locks.push(lock(&p)?);
334 }
335 _ => return Err(ErrorCode::UnsafePath),
336 }
337 }
338 if locks.is_empty() {
339 locks.push(lock(&p)?);
340 }
341 Ok(Self { path: p, locks })
342 }
343 pub(crate) fn handle(&self) -> &File {
344 self.locks.last().unwrap()
345 }
346 pub fn duplicate(&self) -> Result<Self> {
347 Ok(Self {
348 path: self.path.clone(),
349 locks: self
350 .locks
351 .iter()
352 .map(|f| f.try_clone().map_err(|_| ErrorCode::Io))
353 .collect::<Result<_>>()?,
354 })
355 }
356 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
357 let p = self.path.join(n);
358 match std::fs::symlink_metadata(&p) {
359 Ok(_) => {}
360 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
361 if !create {
362 return Ok(None);
363 }
364 std::fs::create_dir(&p).map_err(crate::space::io_error)?;
365 }
366 Err(_) => return Err(ErrorCode::Io),
367 }
368 let mut d = self.duplicate()?;
369 d.locks.push(lock(&p)?);
370 d.path = p;
371 Ok(Some(d))
372 }
373 pub fn absent(&self, n: &str) -> Result<bool> {
374 match std::fs::symlink_metadata(self.path.join(n)) {
375 Ok(_) => Ok(false),
376 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
377 Err(_) => Err(ErrorCode::Io),
378 }
379 }
380 pub fn create(&self, n: &str) -> std::io::Result<File> {
381 OpenOptions::new()
382 .write(true)
383 .create_new(true)
384 .share_mode(0)
385 .custom_flags(0x00200000)
386 .open(self.path.join(n))
387 }
388 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
389 std::fs::hard_link(self.path.join(a), self.path.join(b))
390 }
391 pub fn remove(&self, n: &str) -> bool {
392 std::fs::remove_file(self.path.join(n)).is_ok()
393 }
394 pub fn sync(&self) -> Durability {
395 Durability::Unconfirmed
396 }
397 pub(crate) fn sync_checked(&self) -> Result<Durability> {
398 Ok(Durability::Unconfirmed)
399 }
400 }
401}
402#[cfg(not(any(target_os = "linux", windows)))]
403compile_error!("Archive worker supports Linux and Windows only");
404pub use platform::Dir;
405fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> {
406 let mut parts = name.split('/').collect::<Vec<_>>();
407 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
408 let mut d = root.duplicate()?;
409 for p in parts {
410 match d.child(p, create)? {
411 Some(child) => d = child,
412 None => return Ok(None),
413 }
414 }
415 Ok(Some((d, leaf.to_owned())))
416}
417pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
418 for (name, kind) in names {
419 if let Some((d, leaf)) = parent(root, name, false)? {
420 if *kind == EntryKind::Directory {
421 let _ = d.child(&leaf, false)?;
422 } else if !d.absent(&leaf)? {
423 return Err(ErrorCode::Conflict);
424 }
425 }
426 }
427 Ok(())
428}
429pub(crate) fn preflight_space(
430 root: &Dir,
431 files: &[(String, u64)],
432 staging: Option<(&File, u64)>,
433) -> Result<()> {
434 let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
435 let mut charge = |file: &File, bytes: u64| -> Result<()> {
436 crate::space::ensure(file, bytes)?;
437 let volume = crate::space::volume(file)?;
438 if let Some((_, total)) = volumes.get_mut(&volume) {
439 *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?;
440 } else {
441 volumes.insert(
442 volume,
443 (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes),
444 );
445 }
446 Ok(())
447 };
448 if let Some((file, bytes)) = staging {
449 charge(file, bytes)?;
450 }
451 for (name, size) in files {
452 valid_name(name, false)?;
453 let mut parent = root.duplicate()?;
454 let mut parts = name.split('/').collect::<Vec<_>>();
455 parts.pop();
456 for part in parts {
457 match parent.child(part, false)? {
458 Some(child) => parent = child,
459 None => break,
460 }
461 }
462 charge(parent.handle(), *size)?;
463 }
464 for (file, bytes) in volumes.values() {
465 crate::space::ensure(file, *bytes)?;
466 }
467 Ok(())
468}
469pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> {
470 let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
471 if d.child(&leaf, false)?.is_some() {
472 return Ok((false, Durability::NotApplicable, None));
473 }
474 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
475 Ok(match d.sync_checked() {
476 Ok(durability) => (true, durability, None),
477 Err(error) => (true, Durability::Failed, Some(error)),
478 })
479}
480pub struct Published {
481 pub created: bool,
482 pub uncertain: bool,
483 pub error: Option<ErrorCode>,
484 pub durability: Durability,
485 pub cleanup: Cleanup,
486 pub retained: u64,
487 pub retained_name: Option<String>,
488}
489pub fn publish(
490 root: &Dir,
491 name: &str,
492 data: &[u8],
493 check: &mut impl FnMut(bool) -> Result<()>,
494) -> Published {
495 publish_reader(
496 root,
497 name,
498 &mut std::io::Cursor::new(data),
499 data.len() as u64,
500 check,
501 )
502}
503
504pub fn publish_reader(
505 root: &Dir,
506 name: &str,
507 data: &mut impl Read,
508 length: u64,
509 check: &mut impl FnMut(bool) -> Result<()>,
510) -> Published {
511 let mut result = Published {
512 created: false,
513 uncertain: false,
514 error: None,
515 durability: Durability::NotApplicable,
516 cleanup: Cleanup::Complete,
517 retained: 0,
518 retained_name: None,
519 };
520 let prepared = (|| {
521 valid_name(name, false)?;
522 let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?;
523 let temp = format!(
524 ".zipelo-{}-{}.tmp",
525 std::process::id(),
526 TEMP.fetch_add(1, Ordering::Relaxed)
527 );
528 let mut file = dir.create(&temp).map_err(|e| {
529 if e.kind() == std::io::ErrorKind::AlreadyExists {
530 ErrorCode::Conflict
531 } else {
532 crate::space::io_error(e)
533 }
534 })?;
535 let written = (|| {
536 crate::space::ensure(&file, length)?;
537 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
538 let mut remaining = length;
539 while remaining != 0 {
540 check(false)?;
541 let count = remaining.min(buffer.len() as u64) as usize;
542 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
543 if n == 0 {
544 return Err(ErrorCode::Io);
545 }
546 file.write_all(&buffer[..n])
547 .map_err(crate::space::io_error)?;
548 remaining -= n as u64;
549 }
550 file.sync_all().map_err(crate::space::io_error)
551 })();
552 let closed = close(file).map_err(crate::space::io_error);
553 let mut finish = written.and(closed).and_then(|_| check(true));
554 if finish.is_ok() {
555 match dir.link(&temp, &leaf) {
556 Ok(()) => {
557 result.created = true;
558 match dir.sync_checked() {
559 Ok(durability) => result.durability = durability,
560 Err(error) => {
561 result.durability = Durability::Failed;
562 finish = Err(error);
563 }
564 }
565 }
566 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
567 finish = Err(ErrorCode::Conflict)
568 }
569 Err(error) => {
570 result.uncertain = true;
571 result.durability = Durability::Unconfirmed;
572 finish = Err(crate::space::io_error(error));
573 }
574 }
575 }
576 if !dir.remove(&temp) {
577 result.cleanup = Cleanup::Failed;
578 result.retained = 1;
579 result.retained_name = Some(match name.rsplit_once('/') {
580 Some((prefix, _)) => format!("{prefix}/{temp}"),
581 None => temp.clone(),
582 });
583 if finish.is_ok() {
584 finish = Err(ErrorCode::Io);
585 }
586 }
587 if result.created {
588 if let Err(error) = dir.sync_checked() {
589 result.durability = Durability::Failed;
590 finish = Err(error);
591 }
592 }
593 finish
594 })();
595 result.error = prepared.err();
596 result
597}