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