team-ljyzipelo

공개
538줄18 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 fn duplicate(&self) -> Result<Self> {
251 Ok(Self {
252 file: self.file.try_clone().map_err(|_| ErrorCode::Io)?,
253 })
254 }
255 pub fn absent(&self, n: &str) -> Result<bool> {
256 match open(&self.file, std::ffi::OsStr::new(n), 0x200000) {
257 Ok(_) => Ok(false),
258 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
259 Err(_) => Err(ErrorCode::Io),
260 }
261 }
262 pub fn create(&self, n: &str) -> std::io::Result<File> {
263 open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80)
264 }
265 pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> {
266 let a = CString::new(from).unwrap();
267 let b = CString::new(to).unwrap();
268 // 배타적 hard link 게시로 기존 이름을 보존함.
269 if unsafe {
270 linkat(
271 self.file.as_raw_fd(),
272 a.as_ptr(),
273 self.file.as_raw_fd(),
274 b.as_ptr(),
275 0,
276 )
277 } == 0
278 {
279 Ok(())
280 } else {
281 Err(std::io::Error::last_os_error())
282 }
283 }
284 pub fn remove(&self, n: &str) -> bool {
285 let n = CString::new(n).unwrap();
286 unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 }
287 }
288 pub fn sync(&self) -> Durability {
289 if self.file.sync_all().is_ok() {
290 Durability::Synced
291 } else {
292 Durability::Failed
293 }
294 }
295 }
296}
297#[cfg(windows)]
298mod platform {
299 use super::*;
300 use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
301 pub struct Dir {
302 path: PathBuf,
303 locks: Vec<File>,
304 }
305 fn lock(path: &Path) -> Result<File> {
306 let f = OpenOptions::new()
307 .access_mode(0x80)
308 .share_mode(3)
309 .custom_flags(0x02000000 | 0x00200000)
310 .open(path)
311 .map_err(|_| ErrorCode::UnsafePath)?;
312 let m = f.metadata().map_err(|_| ErrorCode::Io)?;
313 if !m.is_dir() || m.file_attributes() & 0x400 != 0 {
314 return Err(ErrorCode::UnsafePath);
315 }
316 Ok(f)
317 }
318 impl Dir {
319 pub fn root(path: &Path) -> Result<Self> {
320 let mut p = PathBuf::new();
321 let mut locks = Vec::new();
322 for c in path.components() {
323 match c {
324 Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()),
325 Component::Normal(n) => {
326 if locks.is_empty() {
327 locks.push(lock(&p)?);
328 }
329 p.push(n);
330 locks.push(lock(&p)?);
331 }
332 _ => return Err(ErrorCode::UnsafePath),
333 }
334 }
335 if locks.is_empty() {
336 locks.push(lock(&p)?);
337 }
338 Ok(Self { path: p, locks })
339 }
340 pub fn duplicate(&self) -> Result<Self> {
341 Ok(Self {
342 path: self.path.clone(),
343 locks: self
344 .locks
345 .iter()
346 .map(|f| f.try_clone().map_err(|_| ErrorCode::Io))
347 .collect::<Result<_>>()?,
348 })
349 }
350 pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> {
351 let p = self.path.join(n);
352 match std::fs::symlink_metadata(&p) {
353 Ok(_) => {}
354 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
355 if !create {
356 return Ok(None);
357 }
358 std::fs::create_dir(&p).map_err(|_| ErrorCode::Io)?;
359 }
360 Err(_) => return Err(ErrorCode::Io),
361 }
362 let mut d = self.duplicate()?;
363 d.locks.push(lock(&p)?);
364 d.path = p;
365 Ok(Some(d))
366 }
367 pub fn absent(&self, n: &str) -> Result<bool> {
368 match std::fs::symlink_metadata(self.path.join(n)) {
369 Ok(_) => Ok(false),
370 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true),
371 Err(_) => Err(ErrorCode::Io),
372 }
373 }
374 pub fn create(&self, n: &str) -> std::io::Result<File> {
375 OpenOptions::new()
376 .write(true)
377 .create_new(true)
378 .share_mode(0)
379 .custom_flags(0x00200000)
380 .open(self.path.join(n))
381 }
382 pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> {
383 std::fs::hard_link(self.path.join(a), self.path.join(b))
384 }
385 pub fn remove(&self, n: &str) -> bool {
386 std::fs::remove_file(self.path.join(n)).is_ok()
387 }
388 pub fn sync(&self) -> Durability {
389 Durability::Unconfirmed
390 }
391 }
392}
393#[cfg(not(any(target_os = "linux", windows)))]
394compile_error!("Archive worker supports Linux and Windows only");
395pub use platform::Dir;
396fn parent(root: &Dir, name: &str, create: bool) -> Result<Option<(Dir, String)>> {
397 let mut parts = name.split('/').collect::<Vec<_>>();
398 let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?;
399 let mut d = root.duplicate()?;
400 for p in parts {
401 match d.child(p, create)? {
402 Some(child) => d = child,
403 None => return Ok(None),
404 }
405 }
406 Ok(Some((d, leaf.to_owned())))
407}
408pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> {
409 for (name, kind) in names {
410 if let Some((d, leaf)) = parent(root, name, false)? {
411 if *kind == EntryKind::Directory {
412 let _ = d.child(&leaf, false)?;
413 } else if !d.absent(&leaf)? {
414 return Err(ErrorCode::Conflict);
415 }
416 }
417 }
418 Ok(())
419}
420pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability)> {
421 let (d, leaf) = parent(root, name, false)?.ok_or(ErrorCode::Io)?;
422 if d.child(&leaf, false)?.is_some() {
423 return Ok((false, Durability::NotApplicable));
424 }
425 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
426 Ok((true, d.sync()))
427}
428pub struct Published {
429 pub created: bool,
430 pub uncertain: bool,
431 pub error: Option<ErrorCode>,
432 pub durability: Durability,
433 pub cleanup: Cleanup,
434 pub retained: u64,
435 pub retained_name: Option<String>,
436}
437pub fn publish(
438 root: &Dir,
439 name: &str,
440 data: &[u8],
441 check: &mut impl FnMut(bool) -> Result<()>,
442) -> Published {
443 publish_reader(
444 root,
445 name,
446 &mut std::io::Cursor::new(data),
447 data.len() as u64,
448 check,
449 )
450}
451
452pub fn publish_reader(
453 root: &Dir,
454 name: &str,
455 data: &mut impl Read,
456 length: u64,
457 check: &mut impl FnMut(bool) -> Result<()>,
458) -> Published {
459 let mut result = Published {
460 created: false,
461 uncertain: false,
462 error: None,
463 durability: Durability::NotApplicable,
464 cleanup: Cleanup::Complete,
465 retained: 0,
466 retained_name: None,
467 };
468 let prepared = (|| {
469 valid_name(name, false)?;
470 let (dir, leaf) = parent(root, name, true)?.ok_or(ErrorCode::Io)?;
471 let temp = format!(
472 ".zipelo-{}-{}.tmp",
473 std::process::id(),
474 TEMP.fetch_add(1, Ordering::Relaxed)
475 );
476 let mut file = dir.create(&temp).map_err(|e| {
477 if e.kind() == std::io::ErrorKind::AlreadyExists {
478 ErrorCode::Conflict
479 } else {
480 ErrorCode::Io
481 }
482 })?;
483 let written = (|| {
484 let mut buffer = zeroize::Zeroizing::new([0; 65536]);
485 let mut remaining = length;
486 while remaining != 0 {
487 check(false)?;
488 let count = remaining.min(buffer.len() as u64) as usize;
489 let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?;
490 if n == 0 {
491 return Err(ErrorCode::Io);
492 }
493 file.write_all(&buffer[..n]).map_err(|_| ErrorCode::Io)?;
494 remaining -= n as u64;
495 }
496 file.sync_all().map_err(|_| ErrorCode::Io)
497 })();
498 let closed = close(file).map_err(|_| ErrorCode::Io);
499 let mut finish = written.and(closed).and_then(|_| check(true));
500 if finish.is_ok() {
501 match dir.link(&temp, &leaf) {
502 Ok(()) => {
503 result.created = true;
504 result.durability = dir.sync();
505 if result.durability == Durability::Failed {
506 finish = Err(ErrorCode::Io);
507 }
508 }
509 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
510 finish = Err(ErrorCode::Conflict)
511 }
512 Err(_) => {
513 result.uncertain = true;
514 result.durability = Durability::Unconfirmed;
515 finish = Err(ErrorCode::Io);
516 }
517 }
518 }
519 if !dir.remove(&temp) {
520 result.cleanup = Cleanup::Failed;
521 result.retained = 1;
522 result.retained_name = Some(match name.rsplit_once('/') {
523 Some((prefix, _)) => format!("{prefix}/{temp}"),
524 None => temp.clone(),
525 });
526 if finish.is_ok() {
527 finish = Err(ErrorCode::Io);
528 }
529 }
530 if result.created && dir.sync() == Durability::Failed {
531 result.durability = Durability::Failed;
532 finish = Err(ErrorCode::Io);
533 }
534 finish
535 })();
536 result.error = prepared.err();
537 result
538}