team-ljyzipelo

공개
585줄19 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(ErrorCode::Io);
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 if self.file.sync_all().is_ok() {
293 Durability::Synced
294 } else {
295 Durability::Failed
296 }
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(|_| ErrorCode::Io)?;
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 }
398}
399#[cfg(not(any(target_os = "linux", windows)))]
400compile_error!("Archive worker supports Linux and Windows only");
401pub use platform::Dir;
402fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> {
403 let mut parts = name.split('/').collect::<Vec<_>>();
404 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
405 let mut d = root.duplicate()?;
406 for p in parts {
407 match d.child(p, create)? {
408 Some(child) => d = child,
409 None => return Ok(None),
410 }
411 }
412 Ok(Some((d, leaf.to_owned())))
413}
414pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
415 for (name, kind) in names {
416 if let Some((d, leaf)) = parent(root, name, false)? {
417 if *kind == EntryKind::Directory {
418 let _ = d.child(&leaf, false)?;
419 } else if !d.absent(&leaf)? {
420 return Err(ErrorCode::Conflict);
421 }
422 }
423 }
424 Ok(())
425}
426pub(crate) fn preflight_space(
427 root: &Dir,
428 files: &[(String, u64)],
429 staging: Option<(&File, u64)>,
430) -> Result<()> {
431 let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new();
432 let mut charge = |file: &File, bytes: u64| -> Result<()> {
433 crate::space::ensure(file, bytes)?;
434 let volume = crate::space::volume(file)?;
435 if let Some((_, total)) = volumes.get_mut(&volume) {
436 *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?;
437 } else {
438 volumes.insert(
439 volume,
440 (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes),
441 );
442 }
443 Ok(())
444 };
445 if let Some((file, bytes)) = staging {
446 charge(file, bytes)?;
447 }
448 for (name, size) in files {
449 valid_name(name, false)?;
450 let mut parent = root.duplicate()?;
451 let mut parts = name.split('/').collect::<Vec<_>>();
452 parts.pop();
453 for part in parts {
454 match parent.child(part, false)? {
455 Some(child) => parent = child,
456 None => break,
457 }
458 }
459 charge(parent.handle(), *size)?;
460 }
461 for (file, bytes) in volumes.values() {
462 crate::space::ensure(file, *bytes)?;
463 }
464 Ok(())
465}
466pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> {
467 let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
468 if d.child(&leaf, false)?.is_some() {
469 return Ok((false, Durability::NotApplicable));
470 }
471 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
472 Ok((true, d.sync()))
473}
474pub struct Published {
475 pub created: bool,
476 pub uncertain: bool,
477 pub error: Option<ErrorCode>,
478 pub durability: Durability,
479 pub cleanup: Cleanup,
480 pub retained: u64,
481 pub retained_name: Option<String>,
482}
483pub fn publish(
484 root: &Dir,
485 name: &str,
486 data: &[u8],
487 check: &mut impl FnMut(bool) -> Result<()>,
488) -> Published {
489 publish_reader(
490 root,
491 name,
492 &mut std::io::Cursor::new(data),
493 data.len() as u64,
494 check,
495 )
496}
497
498pub fn publish_reader(
499 root: &Dir,
500 name: &str,
501 data: &mut impl Read,
502 length: u64,
503 check: &mut impl FnMut(bool) -> Result<()>,
504) -> Published {
505 let mut result = Published {
506 created: false,
507 uncertain: false,
508 error: None,
509 durability: Durability::NotApplicable,
510 cleanup: Cleanup::Complete,
511 retained: 0,
512 retained_name: None,
513 };
514 let prepared = (|| {
515 valid_name(name, false)?;
516 let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?;
517 let temp = format!(
518 ".zipelo-{}-{}.tmp",
519 std::process::id(),
520 TEMP.fetch_add(1, Ordering::Relaxed)
521 );
522 let mut file = dir.create(&temp).map_err(|e| {
523 if e.kind() == std::io::ErrorKind::AlreadyExists {
524 ErrorCode::Conflict
525 } else {
526 ErrorCode::Io
527 }
528 })?;
529 let written = (|| {
530 crate::space::ensure(&file, length)?;
531 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
532 let mut remaining = length;
533 while remaining != 0 {
534 check(false)?;
535 let count = remaining.min(buffer.len() as u64) as usize;
536 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
537 if n == 0 {
538 return Err(ErrorCode::Io);
539 }
540 file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?;
541 remaining -= n as u64;
542 }
543 file.sync_all().map_err(|_| ErrorCode::Io)
544 })();
545 let closed = close(file).map_err(|_| ErrorCode::Io);
546 let mut finish = written.and(closed).and_then(|_| check(true));
547 if finish.is_ok() {
548 match dir.link(&temp, &leaf) {
549 Ok(()) => {
550 result.created = true;
551 result.durability = dir.sync();
552 if result.durability == Durability::Failed {
553 finish = Err(ErrorCode::Io);
554 }
555 }
556 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
557 finish = Err(ErrorCode::Conflict)
558 }
559 Err(_) => {
560 result.uncertain = true;
561 result.durability = Durability::Unconfirmed;
562 finish = Err(ErrorCode::Io);
563 }
564 }
565 }
566 if !dir.remove(&temp) {
567 result.cleanup = Cleanup::Failed;
568 result.retained = 1;
569 result.retained_name = Some(match name.rsplit_once('/') {
570 Some((prefix, _)) => format!("{prefix}/{temp}"),
571 None => temp.clone(),
572 });
573 if finish.is_ok() {
574 finish = Err(ErrorCode::Io);
575 }
576 }
577 if result.created && dir.sync() == Durability::Failed {
578 result.durability = Durability::Failed;
579 finish = Err(ErrorCode::Io);
580 }
581 finish
582 })();
583 result.error = prepared.err();
584 result
585}