| 1 | use crate::archive::valid_name; |
| 2 | use crate::protocol::*; |
| 3 | use crate::resources::{Monitor, completed}; |
| 4 | use sha2::{Digest, Sha256}; |
| 5 | use std::fs::{File, OpenOptions}; |
| 6 | use std::io::{Read, Write}; |
| 7 | #[cfg(windows)] |
| 8 | use std::path::PathBuf; |
| 9 | use std::path::{Component, Path}; |
| 10 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 11 | |
| 12 | type Result<T> = std::result::Result<T, ErrorCode>; |
| 13 | static TEMP: AtomicU64 = AtomicU64::new(0); |
| 14 | #[derive(Debug, PartialEq, Eq)] |
| 15 | pub struct Existing { |
| 16 | parent: SourceObject, |
| 17 | object: SourceObject, |
| 18 | pub size: u64, |
| 19 | modified: std::time::SystemTime, |
| 20 | } |
| 21 | fn 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 | } |
| 40 | pub struct Snapshot { |
| 41 | pub bytes: Vec<u8>, |
| 42 | pub object: SourceObject, |
| 43 | pub hash: [u8; 32], |
| 44 | } |
| 45 | #[cfg(unix)] |
| 46 | pub 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)] |
| 55 | pub 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 | } |
| 91 | pub 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)] |
| 156 | fn 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)] |
| 169 | fn 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")] |
| 182 | mod 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)] |
| 355 | mod 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)))] |
| 496 | compile_error!("Archive worker supports Linux and Windows only"); |
| 497 | pub use platform::Dir; |
| 498 | fn 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 | } |
| 515 | pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> { |
| 516 | existing_with(root, name, &mut || Ok(())) |
| 517 | } |
| 518 | pub(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 | } |
| 530 | pub fn unused(root: &Dir, name: &str) -> Result<bool> { |
| 531 | unused_with(root, name, &mut || Ok(())) |
| 532 | } |
| 533 | pub(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 | } |
| 541 | pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { |
| 542 | preflight_mode(root, names, false) |
| 543 | } |
| 544 | pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> { |
| 545 | preflight_mode_with(root, names, interactive, &mut || Ok(())) |
| 546 | } |
| 547 | pub(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 | } |
| 568 | pub(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 | } |
| 609 | pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 610 | directory_with(root, name, &mut || Ok(())) |
| 611 | } |
| 612 | pub(crate) fn directory_with( |
| 613 | root: &Dir, |
| 614 | name: &str, |
| 615 | check: &mut impl Monitor, |
| 616 | ) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 617 | directory_steps(root, name, &mut |step| match step { |
| 618 | PublishStep::Check | PublishStep::Commit(_) => check.check(), |
| 619 | PublishStep::Activity => check.activity(), |
| 620 | }) |
| 621 | } |
| 622 | pub(crate) fn directory_steps( |
| 623 | root: &Dir, |
| 624 | name: &str, |
| 625 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 626 | ) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 627 | let (d, leaf) = |
| 628 | parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?; |
| 629 | if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() { |
| 630 | return Ok((false, Durability::NotApplicable, None)); |
| 631 | } |
| 632 | check(PublishStep::Commit(None))?; |
| 633 | d.child(&leaf, true)?.ok_or(ErrorCode::Io)?; |
| 634 | let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err(); |
| 635 | Ok(match d.sync_checked() { |
| 636 | Ok(durability) => ( |
| 637 | true, |
| 638 | durability, |
| 639 | progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()), |
| 640 | ), |
| 641 | Err(error) => (true, Durability::Failed, Some(error)), |
| 642 | }) |
| 643 | } |
| 644 | pub struct Published { |
| 645 | pub created: bool, |
| 646 | pub uncertain: bool, |
| 647 | pub error: Option<ErrorCode>, |
| 648 | pub durability: Durability, |
| 649 | pub cleanup: Cleanup, |
| 650 | pub retained: u64, |
| 651 | pub retained_name: Option<String>, |
| 652 | } |
| 653 | pub fn publish( |
| 654 | root: &Dir, |
| 655 | name: &str, |
| 656 | data: &[u8], |
| 657 | check: &mut impl FnMut(bool) -> Result<()>, |
| 658 | ) -> Published { |
| 659 | publish_reader( |
| 660 | root, |
| 661 | name, |
| 662 | &mut std::io::Cursor::new(data), |
| 663 | data.len() as u64, |
| 664 | check, |
| 665 | ) |
| 666 | } |
| 667 | |
| 668 | pub fn publish_reader( |
| 669 | root: &Dir, |
| 670 | name: &str, |
| 671 | data: &mut impl Read, |
| 672 | length: u64, |
| 673 | check: &mut impl FnMut(bool) -> Result<()>, |
| 674 | ) -> Published { |
| 675 | publish_reader_mode(root, name, data, length, None, check) |
| 676 | } |
| 677 | pub fn publish_reader_mode( |
| 678 | root: &Dir, |
| 679 | name: &str, |
| 680 | data: &mut impl Read, |
| 681 | length: u64, |
| 682 | replace: Option<&Existing>, |
| 683 | check: &mut impl FnMut(bool) -> Result<()>, |
| 684 | ) -> Published { |
| 685 | publish_reader_steps(root, name, data, length, replace, &mut |step| match step { |
| 686 | PublishStep::Check => check(false), |
| 687 | PublishStep::Commit(_) => check(true), |
| 688 | PublishStep::Activity => Ok(()), |
| 689 | }) |
| 690 | } |
| 691 | pub(crate) struct PublicationTemp { |
| 692 | pub parent: SourceObject, |
| 693 | pub name: String, |
| 694 | pub object: SourceObject, |
| 695 | } |
| 696 | pub(crate) enum PublishStep { |
| 697 | Check, |
| 698 | Activity, |
| 699 | Commit(Option<PublicationTemp>), |
| 700 | } |
| 701 | struct PublicationMonitor<'a, F>(&'a mut F); |
| 702 | impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> { |
| 703 | fn check(&mut self) -> Result<()> { |
| 704 | self.0(PublishStep::Check) |
| 705 | } |
| 706 | fn activity(&mut self) -> Result<()> { |
| 707 | self.0(PublishStep::Activity) |
| 708 | } |
| 709 | } |
| 710 | fn publication_activity( |
| 711 | finish: &mut Result<()>, |
| 712 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 713 | ) { |
| 714 | let progress = completed(Ok(()), &mut PublicationMonitor(check)); |
| 715 | if finish.is_ok() { |
| 716 | *finish = progress; |
| 717 | } |
| 718 | } |
| 719 | pub(crate) fn publish_reader_steps( |
| 720 | root: &Dir, |
| 721 | name: &str, |
| 722 | data: &mut impl Read, |
| 723 | length: u64, |
| 724 | replace: Option<&Existing>, |
| 725 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 726 | ) -> Published { |
| 727 | let mut result = Published { |
| 728 | created: false, |
| 729 | uncertain: false, |
| 730 | error: None, |
| 731 | durability: Durability::NotApplicable, |
| 732 | cleanup: Cleanup::Complete, |
| 733 | retained: 0, |
| 734 | retained_name: None, |
| 735 | }; |
| 736 | let prepared = (|| { |
| 737 | valid_name(name, false)?; |
| 738 | let (dir, leaf) = |
| 739 | parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?; |
| 740 | let temp = format!( |
| 741 | ".zipelo-{}-{}.tmp", |
| 742 | std::process::id(), |
| 743 | TEMP.fetch_add(1, Ordering::Relaxed) |
| 744 | ); |
| 745 | let mut file = dir.create(&temp).map_err(|e| { |
| 746 | if e.kind() == std::io::ErrorKind::AlreadyExists { |
| 747 | ErrorCode::Conflict |
| 748 | } else { |
| 749 | crate::space::io_error(e) |
| 750 | } |
| 751 | })?; |
| 752 | let mut temporary = None; |
| 753 | let written = (|| { |
| 754 | temporary = Some(PublicationTemp { |
| 755 | parent: object(dir.handle())?, |
| 756 | name: temp.clone(), |
| 757 | object: object(&file)?, |
| 758 | }); |
| 759 | completed(Ok(()), &mut PublicationMonitor(check))?; |
| 760 | completed( |
| 761 | crate::space::ensure(&file, length), |
| 762 | &mut PublicationMonitor(check), |
| 763 | )?; |
| 764 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 765 | let mut remaining = length; |
| 766 | while remaining != 0 { |
| 767 | check(PublishStep::Check)?; |
| 768 | let count = remaining.min(buffer.len() as u64) as usize; |
| 769 | let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?; |
| 770 | if n == 0 { |
| 771 | return Err(ErrorCode::Io); |
| 772 | } |
| 773 | completed(Ok(()), &mut PublicationMonitor(check))?; |
| 774 | completed( |
| 775 | crate::space::ensure(&file, n as u64), |
| 776 | &mut PublicationMonitor(check), |
| 777 | )?; |
| 778 | completed( |
| 779 | file.write_all(&buffer[..n]).map_err(crate::space::io_error), |
| 780 | &mut PublicationMonitor(check), |
| 781 | )?; |
| 782 | remaining -= n as u64; |
| 783 | } |
| 784 | completed( |
| 785 | file.sync_all().map_err(crate::space::io_error), |
| 786 | &mut PublicationMonitor(check), |
| 787 | ) |
| 788 | })(); |
| 789 | let closed = completed( |
| 790 | close(file).map_err(crate::space::io_error), |
| 791 | &mut PublicationMonitor(check), |
| 792 | ); |
| 793 | let mut finish = written.and(closed).and_then(|_| { |
| 794 | check(PublishStep::Commit(temporary))?; |
| 795 | // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함. |
| 796 | if let Some(expected) = replace { |
| 797 | if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref() |
| 798 | != Some(expected) |
| 799 | { |
| 800 | return Err(ErrorCode::Conflict); |
| 801 | } |
| 802 | } |
| 803 | Ok(()) |
| 804 | }); |
| 805 | let mut temp_consumed = false; |
| 806 | if finish.is_ok() { |
| 807 | let published = if replace.is_some() { |
| 808 | dir.replace(&temp, &leaf) |
| 809 | } else { |
| 810 | dir.link(&temp, &leaf) |
| 811 | }; |
| 812 | match published { |
| 813 | Ok(()) => { |
| 814 | temp_consumed = replace.is_some(); |
| 815 | result.created = true; |
| 816 | publication_activity(&mut finish, check); |
| 817 | match dir.sync_checked() { |
| 818 | Ok(durability) => { |
| 819 | result.durability = durability; |
| 820 | publication_activity(&mut finish, check); |
| 821 | } |
| 822 | Err(error) => { |
| 823 | result.durability = Durability::Failed; |
| 824 | finish = Err(error); |
| 825 | } |
| 826 | } |
| 827 | } |
| 828 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { |
| 829 | finish = Err(ErrorCode::Conflict) |
| 830 | } |
| 831 | Err(error) => { |
| 832 | result.uncertain = true; |
| 833 | result.durability = Durability::Unconfirmed; |
| 834 | finish = Err(crate::space::io_error(error)); |
| 835 | } |
| 836 | } |
| 837 | } |
| 838 | if !temp_consumed { |
| 839 | if dir.remove(&temp) { |
| 840 | publication_activity(&mut finish, check); |
| 841 | } else { |
| 842 | result.cleanup = Cleanup::Failed; |
| 843 | result.retained = 1; |
| 844 | result.retained_name = Some(match name.rsplit_once('/') { |
| 845 | Some((prefix, _)) => format!("{prefix}/{temp}"), |
| 846 | None => temp.clone(), |
| 847 | }); |
| 848 | if finish.is_ok() { |
| 849 | finish = Err(ErrorCode::Io); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | if result.created { |
| 854 | if let Err(error) = dir.sync_checked() { |
| 855 | result.durability = Durability::Failed; |
| 856 | finish = Err(error); |
| 857 | } else { |
| 858 | publication_activity(&mut finish, check); |
| 859 | } |
| 860 | } |
| 861 | finish |
| 862 | })(); |
| 863 | result.error = prepared.err(); |
| 864 | result |
| 865 | } |