| 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 | fn getegid() -> u32; |
| 198 | fn dlopen(name: *const i8, flags: i32) -> *mut std::ffi::c_void; |
| 199 | fn dlsym(library: *mut std::ffi::c_void, name: *const i8) -> *mut std::ffi::c_void; |
| 200 | fn dlclose(library: *mut std::ffi::c_void) -> i32; |
| 201 | fn getgrgid_r( |
| 202 | gid: u32, |
| 203 | group: *mut Group, |
| 204 | buffer: *mut i8, |
| 205 | length: usize, |
| 206 | result: *mut *mut Group, |
| 207 | ) -> i32; |
| 208 | } |
| 209 | #[repr(C)] |
| 210 | struct Group { |
| 211 | name: *mut i8, |
| 212 | password: *mut i8, |
| 213 | gid: u32, |
| 214 | members: *mut *mut i8, |
| 215 | } |
| 216 | #[repr(C)] |
| 217 | struct Passwd { |
| 218 | name: *mut i8, |
| 219 | password: *mut i8, |
| 220 | uid: u32, |
| 221 | gid: u32, |
| 222 | gecos: *mut i8, |
| 223 | directory: *mut i8, |
| 224 | shell: *mut i8, |
| 225 | } |
| 226 | |
| 227 | // glibc는 NSS 서비스 실패도 열거 종료로 바꾸므로 모듈의 상태를 직접 확인함. |
| 228 | fn systemd_primary_group_is_private(gid: u32, uid: u32) -> bool { |
| 229 | type Set = unsafe extern "C" fn(i32) -> i32; |
| 230 | type End = unsafe extern "C" fn() -> i32; |
| 231 | type Next = unsafe extern "C" fn(*mut Passwd, *mut i8, usize, *mut i32) -> i32; |
| 232 | struct Library(*mut std::ffi::c_void); |
| 233 | impl Drop for Library { |
| 234 | fn drop(&mut self) { |
| 235 | unsafe { dlclose(self.0) }; |
| 236 | } |
| 237 | } |
| 238 | struct Enumeration(End); |
| 239 | impl Drop for Enumeration { |
| 240 | fn drop(&mut self) { |
| 241 | unsafe { (self.0)() }; |
| 242 | } |
| 243 | } |
| 244 | static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); |
| 245 | let Ok(_lock) = LOCK.lock() else { |
| 246 | return false; |
| 247 | }; |
| 248 | // RTLD_NOW로 모든 심볼을 확인하고 모듈이 없거나 열리지 않으면 거부함. |
| 249 | let handle = unsafe { dlopen(c"libnss_systemd.so.2".as_ptr(), 2) }; |
| 250 | if handle.is_null() { |
| 251 | return false; |
| 252 | } |
| 253 | let library = Library(handle); |
| 254 | let set = unsafe { dlsym(library.0, c"_nss_systemd_setpwent".as_ptr()) }; |
| 255 | let end = unsafe { dlsym(library.0, c"_nss_systemd_endpwent".as_ptr()) }; |
| 256 | let next = unsafe { dlsym(library.0, c"_nss_systemd_getpwent_r".as_ptr()) }; |
| 257 | if set.is_null() || end.is_null() || next.is_null() { |
| 258 | return false; |
| 259 | } |
| 260 | // NSS 모듈의 공개 C ABI와 일치하는 함수 포인터만 사용함. |
| 261 | let (set, end, next) = unsafe { |
| 262 | ( |
| 263 | std::mem::transmute::<*mut std::ffi::c_void, Set>(set), |
| 264 | std::mem::transmute::<*mut std::ffi::c_void, End>(end), |
| 265 | std::mem::transmute::<*mut std::ffi::c_void, Next>(next), |
| 266 | ) |
| 267 | }; |
| 268 | let _enumeration = Enumeration(end); |
| 269 | if unsafe { set(0) } != 1 { |
| 270 | return false; |
| 271 | } |
| 272 | let mut buffer = vec![0i8; 16 * 1024]; |
| 273 | loop { |
| 274 | let mut account = Passwd { |
| 275 | name: std::ptr::null_mut(), |
| 276 | password: std::ptr::null_mut(), |
| 277 | uid: 0, |
| 278 | gid: 0, |
| 279 | gecos: std::ptr::null_mut(), |
| 280 | directory: std::ptr::null_mut(), |
| 281 | shell: std::ptr::null_mut(), |
| 282 | }; |
| 283 | let mut error = 0; |
| 284 | let status = |
| 285 | unsafe { next(&mut account, buffer.as_mut_ptr(), buffer.len(), &mut error) }; |
| 286 | if status == -2 && error == 34 && buffer.len() < 1024 * 1024 { |
| 287 | buffer.resize(buffer.len() * 2, 0); |
| 288 | continue; |
| 289 | } |
| 290 | // NSS_STATUS_NOTFOUND만 정상 종료이며 UNAVAIL과 TRYAGAIN은 거부함. |
| 291 | if status == 0 { |
| 292 | return true; |
| 293 | } |
| 294 | if status != 1 || account.name.is_null() || unsafe { *account.name } == 0 { |
| 295 | return false; |
| 296 | } |
| 297 | if account.gid == gid && account.uid != uid { |
| 298 | return false; |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | // files와 systemd만 열거하며 원격 계정 소스와 임의의 NSS 제어 규칙은 거부함. |
| 304 | fn primary_group_is_private(gid: u32) -> bool { |
| 305 | let Ok(policy) = std::fs::read_to_string("/etc/nsswitch.conf") else { |
| 306 | return false; |
| 307 | }; |
| 308 | let mut sources = policy.lines().filter_map(|line| { |
| 309 | let line = line.split('#').next().unwrap_or_default(); |
| 310 | let (database, sources) = line.split_once(':')?; |
| 311 | (database.trim() == "passwd").then_some(sources) |
| 312 | }); |
| 313 | let Some(source) = sources.next() else { |
| 314 | return false; |
| 315 | }; |
| 316 | if sources.next().is_some() |
| 317 | || !(source.split_whitespace().eq(["files"]) |
| 318 | || source.split_whitespace().eq(["files", "systemd"])) |
| 319 | { |
| 320 | return false; |
| 321 | } |
| 322 | let Ok(accounts) = std::fs::read_to_string("/etc/passwd") else { |
| 323 | return false; |
| 324 | }; |
| 325 | let current_uid = unsafe { geteuid() }; |
| 326 | let mut found_current = false; |
| 327 | for account in accounts.lines() { |
| 328 | if account.trim().is_empty() || account.starts_with('#') { |
| 329 | continue; |
| 330 | } |
| 331 | let fields: Vec<_> = account.split(':').collect(); |
| 332 | if fields.len() != 7 || fields[0].is_empty() { |
| 333 | return false; |
| 334 | } |
| 335 | let (Ok(uid), Ok(primary_gid)) = (fields[2].parse::<u32>(), fields[3].parse::<u32>()) |
| 336 | else { |
| 337 | return false; |
| 338 | }; |
| 339 | if primary_gid == gid { |
| 340 | if uid != current_uid { |
| 341 | return false; |
| 342 | } |
| 343 | found_current = true; |
| 344 | } |
| 345 | } |
| 346 | found_current |
| 347 | && (!source.split_whitespace().any(|source| source == "systemd") |
| 348 | || systemd_primary_group_is_private(gid, current_uid)) |
| 349 | } |
| 350 | |
| 351 | // 기본 구성원과 보조 구성원을 모두 확인함. |
| 352 | fn private_group(gid: u32) -> bool { |
| 353 | if gid != unsafe { getegid() } || !primary_group_is_private(gid) { |
| 354 | return false; |
| 355 | } |
| 356 | let mut group = Group { |
| 357 | name: std::ptr::null_mut(), |
| 358 | password: std::ptr::null_mut(), |
| 359 | gid: 0, |
| 360 | members: std::ptr::null_mut(), |
| 361 | }; |
| 362 | let mut result = std::ptr::null_mut(); |
| 363 | let mut buffer = vec![0i8; 16 * 1024]; |
| 364 | let status = unsafe { |
| 365 | getgrgid_r( |
| 366 | gid, |
| 367 | &mut group, |
| 368 | buffer.as_mut_ptr(), |
| 369 | buffer.len(), |
| 370 | &mut result, |
| 371 | ) |
| 372 | }; |
| 373 | // 그룹 정보를 읽지 못하면 안전하다고 볼 근거가 없으므로 거부함. |
| 374 | status == 0 |
| 375 | && !result.is_null() |
| 376 | && group.gid == gid |
| 377 | && !group.members.is_null() |
| 378 | && unsafe { *group.members }.is_null() |
| 379 | } |
| 380 | pub struct Dir { |
| 381 | file: File, |
| 382 | } |
| 383 | fn name(s: &std::ffi::OsStr) -> Result<CString> { |
| 384 | CString::new(s.as_bytes()).map_err(|_| ErrorCode::UnsafePath) |
| 385 | } |
| 386 | fn open(parent: &File, s: &std::ffi::OsStr, flags: i32) -> std::io::Result<File> { |
| 387 | let n = name(s).map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidInput))?; |
| 388 | // 부모 핸들 기준으로 심볼릭 링크를 따르지 않고 열음. |
| 389 | let fd = unsafe { |
| 390 | openat( |
| 391 | parent.as_raw_fd(), |
| 392 | n.as_ptr(), |
| 393 | flags | 0x80000 | 0x20000, |
| 394 | 0o600u32, |
| 395 | ) |
| 396 | }; |
| 397 | if fd < 0 { |
| 398 | return Err(std::io::Error::last_os_error()); |
| 399 | } |
| 400 | Ok(unsafe { File::from_raw_fd(fd) }) |
| 401 | } |
| 402 | impl Dir { |
| 403 | pub fn root(path: &Path) -> Result<Self> { |
| 404 | if !path.is_absolute() { |
| 405 | return Err(ErrorCode::InvalidRequest); |
| 406 | } |
| 407 | let mut d = Self { |
| 408 | file: File::open("/").map_err(|_| ErrorCode::Io)?, |
| 409 | }; |
| 410 | for c in path.components() { |
| 411 | match c { |
| 412 | Component::RootDir => {} |
| 413 | Component::Normal(n) => { |
| 414 | d = Self { |
| 415 | file: open(&d.file, n, 0x10000).map_err(|_| ErrorCode::UnsafePath)?, |
| 416 | } |
| 417 | } |
| 418 | _ => return Err(ErrorCode::UnsafePath), |
| 419 | } |
| 420 | } |
| 421 | d.trusted()?; |
| 422 | Ok(d) |
| 423 | } |
| 424 | fn trusted(&self) -> Result<()> { |
| 425 | let m = self.file.metadata().map_err(|_| ErrorCode::Io)?; |
| 426 | // 다른 계정이 바꿀 수 있는 출력 폴더를 거부함. |
| 427 | // 그룹 쓰기는 그 그룹이 현재 계정만의 개인 그룹일 때만 허용함. |
| 428 | let group_writable = m.mode() & 0o020 != 0; |
| 429 | if !m.is_dir() |
| 430 | || m.uid() != unsafe { geteuid() } |
| 431 | || m.mode() & 0o002 != 0 |
| 432 | || (group_writable && !private_group(m.gid())) |
| 433 | { |
| 434 | return Err(ErrorCode::UnsafePath); |
| 435 | } |
| 436 | Ok(()) |
| 437 | } |
| 438 | pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> { |
| 439 | match open(&self.file, std::ffi::OsStr::new(n), 0x10000) { |
| 440 | Ok(file) => { |
| 441 | let d = Self { file }; |
| 442 | d.trusted()?; |
| 443 | Ok(Some(d)) |
| 444 | } |
| 445 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 446 | if !create { |
| 447 | return Ok(None); |
| 448 | } |
| 449 | let n = CString::new(n).map_err(|_| ErrorCode::UnsafePath)?; |
| 450 | // 고정 부모 안에 새 전용 디렉터리를 생성함. |
| 451 | if unsafe { mkdirat(self.file.as_raw_fd(), n.as_ptr(), 0o700) } != 0 { |
| 452 | return Err(crate::space::io_error(std::io::Error::last_os_error())); |
| 453 | } |
| 454 | let file = open( |
| 455 | &self.file, |
| 456 | std::ffi::OsStr::new(n.to_str().unwrap()), |
| 457 | 0x10000, |
| 458 | ) |
| 459 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 460 | let d = Self { file }; |
| 461 | d.trusted()?; |
| 462 | Ok(Some(d)) |
| 463 | } |
| 464 | Err(_) => Err(ErrorCode::UnsafePath), |
| 465 | } |
| 466 | } |
| 467 | pub(crate) fn handle(&self) -> &File { |
| 468 | &self.file |
| 469 | } |
| 470 | pub fn duplicate(&self) -> Result<Self> { |
| 471 | Ok(Self { |
| 472 | file: self.file.try_clone().map_err(|_| ErrorCode::Io)?, |
| 473 | }) |
| 474 | } |
| 475 | pub fn absent(&self, n: &str) -> Result<bool> { |
| 476 | match open(&self.file, std::ffi::OsStr::new(n), 0x200000) { |
| 477 | Ok(_) => Ok(false), |
| 478 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), |
| 479 | Err(_) => Err(ErrorCode::Io), |
| 480 | } |
| 481 | } |
| 482 | pub fn existing(&self, n: &str) -> Result<Option<Existing>> { |
| 483 | match open(&self.file, std::ffi::OsStr::new(n), 0x200000) { |
| 484 | Ok(file) => existing_file(&self.file, file).map(Some), |
| 485 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 486 | Err(_) => Err(ErrorCode::Io), |
| 487 | } |
| 488 | } |
| 489 | pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> { |
| 490 | let from = CString::new(from).unwrap(); |
| 491 | let to = CString::new(to).unwrap(); |
| 492 | // 고정 부모 안에서 완성된 임시 파일로 원본 이름을 교체함. |
| 493 | if unsafe { |
| 494 | renameat( |
| 495 | self.file.as_raw_fd(), |
| 496 | from.as_ptr(), |
| 497 | self.file.as_raw_fd(), |
| 498 | to.as_ptr(), |
| 499 | ) |
| 500 | } == 0 |
| 501 | { |
| 502 | Ok(()) |
| 503 | } else { |
| 504 | Err(std::io::Error::last_os_error()) |
| 505 | } |
| 506 | } |
| 507 | pub fn create(&self, n: &str) -> std::io::Result<File> { |
| 508 | open(&self.file, std::ffi::OsStr::new(n), 1 | 0x40 | 0x80) |
| 509 | } |
| 510 | /// 이 폴더 안에 이름 없는 읽기/쓰기 임시 파일을 만듦. 마지막 핸들을 닫으면 제거됨. |
| 511 | pub(crate) fn temporary(&self) -> Result<File> { |
| 512 | // O_TMPFILE | O_EXCL: 이름이 생기지 않고 나중에 링크할 수도 없음. |
| 513 | match open(&self.file, std::ffi::OsStr::new("."), 2 | 0x410000 | 0x80) { |
| 514 | Ok(file) => return Ok(file), |
| 515 | Err(e) => { |
| 516 | if crate::space::io_error(e) == ErrorCode::DiskFull { |
| 517 | return Err(ErrorCode::DiskFull); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | // O_TMPFILE을 지원하지 않는 파일 시스템은 숨김 이름으로 만든 즉시 이름을 지움. |
| 522 | let n = format!(".zipelo-{}.tmp", crate::spool::random_name()?); |
| 523 | let file = open(&self.file, std::ffi::OsStr::new(&n), 2 | 0x40 | 0x80) |
| 524 | .map_err(crate::space::io_error)?; |
| 525 | if !self.remove(&n) { |
| 526 | // 핸들을 닫고 한 번 더 지움. 그래도 남으면 정리 실패로 기록해 결과에 알림. |
| 527 | drop(file); |
| 528 | if !self.remove(&n) && !self.absent(&n).unwrap_or(false) { |
| 529 | crate::spool::note_leftover(); |
| 530 | } |
| 531 | return Err(ErrorCode::Io); |
| 532 | } |
| 533 | if file.metadata().map_err(|_| ErrorCode::Io)?.nlink() != 0 { |
| 534 | return Err(ErrorCode::Io); |
| 535 | } |
| 536 | Ok(file) |
| 537 | } |
| 538 | pub fn link(&self, from: &str, to: &str) -> std::io::Result<()> { |
| 539 | let a = CString::new(from).unwrap(); |
| 540 | let b = CString::new(to).unwrap(); |
| 541 | // 배타적 hard link 게시로 기존 이름을 보존함. |
| 542 | if unsafe { |
| 543 | linkat( |
| 544 | self.file.as_raw_fd(), |
| 545 | a.as_ptr(), |
| 546 | self.file.as_raw_fd(), |
| 547 | b.as_ptr(), |
| 548 | 0, |
| 549 | ) |
| 550 | } == 0 |
| 551 | { |
| 552 | Ok(()) |
| 553 | } else { |
| 554 | Err(std::io::Error::last_os_error()) |
| 555 | } |
| 556 | } |
| 557 | pub fn remove(&self, n: &str) -> bool { |
| 558 | let n = CString::new(n).unwrap(); |
| 559 | unsafe { unlinkat(self.file.as_raw_fd(), n.as_ptr(), 0) == 0 } |
| 560 | } |
| 561 | pub fn sync(&self) -> Durability { |
| 562 | self.sync_checked().unwrap_or(Durability::Failed) |
| 563 | } |
| 564 | pub(crate) fn sync_checked(&self) -> Result<Durability> { |
| 565 | self.file.sync_all().map_err(crate::space::io_error)?; |
| 566 | Ok(Durability::Synced) |
| 567 | } |
| 568 | } |
| 569 | } |
| 570 | #[cfg(windows)] |
| 571 | mod platform { |
| 572 | use super::*; |
| 573 | use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; |
| 574 | pub struct Dir { |
| 575 | path: PathBuf, |
| 576 | locks: Vec<File>, |
| 577 | } |
| 578 | fn lock(path: &Path) -> Result<File> { |
| 579 | let f = OpenOptions::new() |
| 580 | .access_mode(0x80) |
| 581 | .share_mode(3) |
| 582 | .custom_flags(0x02000000 | 0x00200000) |
| 583 | .open(path) |
| 584 | .map_err(|_| ErrorCode::UnsafePath)?; |
| 585 | let m = f.metadata().map_err(|_| ErrorCode::Io)?; |
| 586 | if !m.is_dir() || m.file_attributes() & 0x400 != 0 { |
| 587 | return Err(ErrorCode::UnsafePath); |
| 588 | } |
| 589 | Ok(f) |
| 590 | } |
| 591 | impl Dir { |
| 592 | pub fn root(path: &Path) -> Result<Self> { |
| 593 | let mut p = PathBuf::new(); |
| 594 | let mut locks = Vec::new(); |
| 595 | for c in path.components() { |
| 596 | match c { |
| 597 | Component::Prefix(_) | Component::RootDir => p.push(c.as_os_str()), |
| 598 | Component::Normal(n) => { |
| 599 | if locks.is_empty() { |
| 600 | locks.push(lock(&p)?); |
| 601 | } |
| 602 | p.push(n); |
| 603 | locks.push(lock(&p)?); |
| 604 | } |
| 605 | _ => return Err(ErrorCode::UnsafePath), |
| 606 | } |
| 607 | } |
| 608 | if locks.is_empty() { |
| 609 | locks.push(lock(&p)?); |
| 610 | } |
| 611 | Ok(Self { path: p, locks }) |
| 612 | } |
| 613 | pub(crate) fn handle(&self) -> &File { |
| 614 | self.locks.last().unwrap() |
| 615 | } |
| 616 | pub fn duplicate(&self) -> Result<Self> { |
| 617 | Ok(Self { |
| 618 | path: self.path.clone(), |
| 619 | locks: self |
| 620 | .locks |
| 621 | .iter() |
| 622 | .map(|f| f.try_clone().map_err(|_| ErrorCode::Io)) |
| 623 | .collect::<Result<_>>()?, |
| 624 | }) |
| 625 | } |
| 626 | pub fn child(&self, n: &str, create: bool) -> Result<Option<Self>> { |
| 627 | let p = self.path.join(n); |
| 628 | match std::fs::symlink_metadata(&p) { |
| 629 | Ok(_) => {} |
| 630 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 631 | if !create { |
| 632 | return Ok(None); |
| 633 | } |
| 634 | std::fs::create_dir(&p).map_err(crate::space::io_error)?; |
| 635 | } |
| 636 | Err(_) => return Err(ErrorCode::Io), |
| 637 | } |
| 638 | let mut d = self.duplicate()?; |
| 639 | d.locks.push(lock(&p)?); |
| 640 | d.path = p; |
| 641 | Ok(Some(d)) |
| 642 | } |
| 643 | pub fn absent(&self, n: &str) -> Result<bool> { |
| 644 | match std::fs::symlink_metadata(self.path.join(n)) { |
| 645 | Ok(_) => Ok(false), |
| 646 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), |
| 647 | Err(_) => Err(ErrorCode::Io), |
| 648 | } |
| 649 | } |
| 650 | pub fn existing(&self, n: &str) -> Result<Option<Existing>> { |
| 651 | match OpenOptions::new() |
| 652 | .access_mode(0x80) |
| 653 | .share_mode(7) |
| 654 | .custom_flags(0x02000000 | 0x00200000) |
| 655 | .open(self.path.join(n)) |
| 656 | { |
| 657 | Ok(file) => existing_file(self.handle(), file).map(Some), |
| 658 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 659 | Err(_) => Err(ErrorCode::Io), |
| 660 | } |
| 661 | } |
| 662 | pub fn replace(&self, from: &str, to: &str) -> std::io::Result<()> { |
| 663 | use std::os::windows::ffi::OsStrExt; |
| 664 | unsafe extern "system" { |
| 665 | fn MoveFileExW(from: *const u16, to: *const u16, flags: u32) -> i32; |
| 666 | } |
| 667 | let extended = |name: &str| { |
| 668 | [92u16, 92, 63, 92] |
| 669 | .into_iter() |
| 670 | .chain( |
| 671 | self.path |
| 672 | .join(name) |
| 673 | .as_os_str() |
| 674 | .encode_wide() |
| 675 | .map(|unit| if unit == 47 { 92 } else { unit }), |
| 676 | ) |
| 677 | .chain(Some(0)) |
| 678 | .collect::<Vec<_>>() |
| 679 | }; |
| 680 | let from = extended(from); |
| 681 | let to = extended(to); |
| 682 | // 같은 부모의 이름만 교체하고 복사나 사전 삭제는 하지 않음. |
| 683 | if unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), 1) } != 0 { |
| 684 | Ok(()) |
| 685 | } else { |
| 686 | Err(std::io::Error::last_os_error()) |
| 687 | } |
| 688 | } |
| 689 | pub fn create(&self, n: &str) -> std::io::Result<File> { |
| 690 | OpenOptions::new() |
| 691 | .write(true) |
| 692 | .create_new(true) |
| 693 | .share_mode(0) |
| 694 | .custom_flags(0x00200000) |
| 695 | .open(self.path.join(n)) |
| 696 | } |
| 697 | /// 이 폴더 안에 닫으면 지워지는 숨김 임시 파일을 만듦. |
| 698 | pub(crate) fn temporary(&self) -> Result<File> { |
| 699 | crate::spool::windows_temporary(&self.path, ".zipelo-", true) |
| 700 | } |
| 701 | pub fn link(&self, a: &str, b: &str) -> std::io::Result<()> { |
| 702 | std::fs::hard_link(self.path.join(a), self.path.join(b)) |
| 703 | } |
| 704 | pub fn remove(&self, n: &str) -> bool { |
| 705 | std::fs::remove_file(self.path.join(n)).is_ok() |
| 706 | } |
| 707 | pub fn sync(&self) -> Durability { |
| 708 | Durability::Unconfirmed |
| 709 | } |
| 710 | pub(crate) fn sync_checked(&self) -> Result<Durability> { |
| 711 | Ok(Durability::Unconfirmed) |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | #[cfg(not(any(target_os = "linux", windows)))] |
| 716 | compile_error!("Archive worker supports Linux and Windows only"); |
| 717 | pub use platform::Dir; |
| 718 | fn parent_with( |
| 719 | root: &Dir, |
| 720 | name: &str, |
| 721 | create: bool, |
| 722 | check: &mut impl Monitor, |
| 723 | ) -> Result<Option<(Dir, String)>> { |
| 724 | let mut parts = name.split('/').collect::<Vec<_>>(); |
| 725 | let leaf = parts.pop().ok_or(ErrorCode::UnsafePath)?; |
| 726 | let mut d = root.duplicate()?; |
| 727 | for p in parts { |
| 728 | match completed(d.child(p, create), check)? { |
| 729 | Some(child) => d = child, |
| 730 | None => return Ok(None), |
| 731 | } |
| 732 | } |
| 733 | Ok(Some((d, leaf.to_owned()))) |
| 734 | } |
| 735 | pub fn existing(root: &Dir, name: &str) -> Result<Option<Existing>> { |
| 736 | existing_with(root, name, &mut || Ok(())) |
| 737 | } |
| 738 | pub(crate) fn existing_with( |
| 739 | root: &Dir, |
| 740 | name: &str, |
| 741 | check: &mut impl Monitor, |
| 742 | ) -> Result<Option<Existing>> { |
| 743 | valid_name(name, false)?; |
| 744 | let result = match parent_with(root, name, false, check)? { |
| 745 | Some((dir, leaf)) => dir.existing(&leaf), |
| 746 | None => Ok(None), |
| 747 | }; |
| 748 | completed(result, check) |
| 749 | } |
| 750 | pub fn unused(root: &Dir, name: &str) -> Result<bool> { |
| 751 | unused_with(root, name, &mut || Ok(())) |
| 752 | } |
| 753 | pub(crate) fn unused_with(root: &Dir, name: &str, check: &mut impl Monitor) -> Result<bool> { |
| 754 | valid_name(name, false)?; |
| 755 | let result = match parent_with(root, name, false, check)? { |
| 756 | Some((dir, leaf)) => dir.absent(&leaf), |
| 757 | None => Ok(true), |
| 758 | }; |
| 759 | completed(result, check) |
| 760 | } |
| 761 | pub fn preflight(root: &Dir, names: &[(String, EntryKind)]) -> Result<()> { |
| 762 | preflight_mode(root, names, false) |
| 763 | } |
| 764 | pub fn preflight_mode(root: &Dir, names: &[(String, EntryKind)], interactive: bool) -> Result<()> { |
| 765 | preflight_mode_with(root, names, interactive, &mut || Ok(())) |
| 766 | } |
| 767 | pub(crate) fn preflight_mode_with( |
| 768 | root: &Dir, |
| 769 | names: &[(String, EntryKind)], |
| 770 | interactive: bool, |
| 771 | check: &mut impl Monitor, |
| 772 | ) -> Result<()> { |
| 773 | for (name, kind) in names { |
| 774 | check.check()?; |
| 775 | if let Some((d, leaf)) = parent_with(root, name, false, check)? { |
| 776 | if *kind == EntryKind::Directory { |
| 777 | let _ = d.child(&leaf, false)?; |
| 778 | } else if interactive { |
| 779 | d.existing(&leaf)?; |
| 780 | } else if !d.absent(&leaf)? { |
| 781 | return Err(ErrorCode::Conflict); |
| 782 | } |
| 783 | } |
| 784 | completed(Ok(()), check)?; |
| 785 | } |
| 786 | Ok(()) |
| 787 | } |
| 788 | pub(crate) fn preflight_space_with( |
| 789 | root: &Dir, |
| 790 | files: &[(String, u64)], |
| 791 | staging: Option<(&File, u64)>, |
| 792 | check: &mut impl Monitor, |
| 793 | ) -> Result<()> { |
| 794 | let mut volumes = std::collections::BTreeMap::<u64, (File, u64)>::new(); |
| 795 | let mut charge = |file: &File, bytes: u64| -> Result<()> { |
| 796 | crate::space::ensure(file, bytes)?; |
| 797 | let volume = crate::space::volume(file)?; |
| 798 | if let Some((_, total)) = volumes.get_mut(&volume) { |
| 799 | *total = total.checked_add(bytes).ok_or(ErrorCode::Limit)?; |
| 800 | } else { |
| 801 | volumes.insert( |
| 802 | volume, |
| 803 | (file.try_clone().map_err(|_| ErrorCode::Io)?, bytes), |
| 804 | ); |
| 805 | } |
| 806 | Ok(()) |
| 807 | }; |
| 808 | if let Some((file, bytes)) = staging { |
| 809 | completed(charge(file, bytes), check)?; |
| 810 | } |
| 811 | for (name, size) in files { |
| 812 | valid_name(name, false)?; |
| 813 | let mut parent = root.duplicate()?; |
| 814 | let mut parts = name.split('/').collect::<Vec<_>>(); |
| 815 | parts.pop(); |
| 816 | for part in parts { |
| 817 | match completed(parent.child(part, false), check)? { |
| 818 | Some(child) => parent = child, |
| 819 | None => break, |
| 820 | } |
| 821 | } |
| 822 | completed(charge(parent.handle(), *size), check)?; |
| 823 | } |
| 824 | for (file, bytes) in volumes.values() { |
| 825 | completed(crate::space::ensure(file, *bytes), check)?; |
| 826 | } |
| 827 | Ok(()) |
| 828 | } |
| 829 | pub fn directory(root: &Dir, name: &str) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 830 | directory_with(root, name, &mut || Ok(())) |
| 831 | } |
| 832 | pub(crate) fn directory_with( |
| 833 | root: &Dir, |
| 834 | name: &str, |
| 835 | check: &mut impl Monitor, |
| 836 | ) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 837 | directory_steps(root, name, &mut |step| match step { |
| 838 | PublishStep::Check | PublishStep::Commit(_) => check.check(), |
| 839 | PublishStep::Activity => check.activity(), |
| 840 | }) |
| 841 | } |
| 842 | pub(crate) fn directory_steps( |
| 843 | root: &Dir, |
| 844 | name: &str, |
| 845 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 846 | ) -> Result<(bool, Durability, Option<ErrorCode>)> { |
| 847 | let (d, leaf) = |
| 848 | parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?; |
| 849 | if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() { |
| 850 | return Ok((false, Durability::NotApplicable, None)); |
| 851 | } |
| 852 | check(PublishStep::Commit(None))?; |
| 853 | d.child(&leaf, true)?.ok_or(ErrorCode::Io)?; |
| 854 | let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err(); |
| 855 | Ok(match d.sync_checked() { |
| 856 | Ok(durability) => ( |
| 857 | true, |
| 858 | durability, |
| 859 | progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()), |
| 860 | ), |
| 861 | Err(error) => (true, Durability::Failed, Some(error)), |
| 862 | }) |
| 863 | } |
| 864 | pub struct Published { |
| 865 | pub created: bool, |
| 866 | pub uncertain: bool, |
| 867 | pub error: Option<ErrorCode>, |
| 868 | pub durability: Durability, |
| 869 | pub cleanup: Cleanup, |
| 870 | pub retained: u64, |
| 871 | pub retained_name: Option<String>, |
| 872 | } |
| 873 | pub fn publish( |
| 874 | root: &Dir, |
| 875 | name: &str, |
| 876 | data: &[u8], |
| 877 | check: &mut impl FnMut(bool) -> Result<()>, |
| 878 | ) -> Published { |
| 879 | publish_reader( |
| 880 | root, |
| 881 | name, |
| 882 | &mut std::io::Cursor::new(data), |
| 883 | data.len() as u64, |
| 884 | check, |
| 885 | ) |
| 886 | } |
| 887 | |
| 888 | pub fn publish_reader( |
| 889 | root: &Dir, |
| 890 | name: &str, |
| 891 | data: &mut impl Read, |
| 892 | length: u64, |
| 893 | check: &mut impl FnMut(bool) -> Result<()>, |
| 894 | ) -> Published { |
| 895 | publish_reader_mode(root, name, data, length, None, check) |
| 896 | } |
| 897 | pub fn publish_reader_mode( |
| 898 | root: &Dir, |
| 899 | name: &str, |
| 900 | data: &mut impl Read, |
| 901 | length: u64, |
| 902 | replace: Option<&Existing>, |
| 903 | check: &mut impl FnMut(bool) -> Result<()>, |
| 904 | ) -> Published { |
| 905 | publish_reader_steps(root, name, data, length, replace, &mut |step| match step { |
| 906 | PublishStep::Check => check(false), |
| 907 | PublishStep::Commit(_) => check(true), |
| 908 | PublishStep::Activity => Ok(()), |
| 909 | }) |
| 910 | } |
| 911 | pub(crate) struct PublicationTemp { |
| 912 | pub parent: SourceObject, |
| 913 | pub name: String, |
| 914 | pub object: SourceObject, |
| 915 | } |
| 916 | pub(crate) enum PublishStep { |
| 917 | Check, |
| 918 | Activity, |
| 919 | Commit(Option<PublicationTemp>), |
| 920 | } |
| 921 | struct PublicationMonitor<'a, F>(&'a mut F); |
| 922 | impl<F: FnMut(PublishStep) -> Result<()>> Monitor for PublicationMonitor<'_, F> { |
| 923 | fn check(&mut self) -> Result<()> { |
| 924 | self.0(PublishStep::Check) |
| 925 | } |
| 926 | fn activity(&mut self) -> Result<()> { |
| 927 | self.0(PublishStep::Activity) |
| 928 | } |
| 929 | } |
| 930 | fn publication_activity( |
| 931 | finish: &mut Result<()>, |
| 932 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 933 | ) { |
| 934 | let progress = completed(Ok(()), &mut PublicationMonitor(check)); |
| 935 | if finish.is_ok() { |
| 936 | *finish = progress; |
| 937 | } |
| 938 | } |
| 939 | pub(crate) fn publish_reader_steps( |
| 940 | root: &Dir, |
| 941 | name: &str, |
| 942 | data: &mut impl Read, |
| 943 | length: u64, |
| 944 | replace: Option<&Existing>, |
| 945 | check: &mut impl FnMut(PublishStep) -> Result<()>, |
| 946 | ) -> Published { |
| 947 | let mut result = Published { |
| 948 | created: false, |
| 949 | uncertain: false, |
| 950 | error: None, |
| 951 | durability: Durability::NotApplicable, |
| 952 | cleanup: Cleanup::Complete, |
| 953 | retained: 0, |
| 954 | retained_name: None, |
| 955 | }; |
| 956 | let prepared = (|| { |
| 957 | valid_name(name, false)?; |
| 958 | let (dir, leaf) = |
| 959 | parent_with(root, name, true, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?; |
| 960 | let temp = format!( |
| 961 | ".zipelo-{}-{}.tmp", |
| 962 | std::process::id(), |
| 963 | TEMP.fetch_add(1, Ordering::Relaxed) |
| 964 | ); |
| 965 | let mut file = dir.create(&temp).map_err(|e| { |
| 966 | if e.kind() == std::io::ErrorKind::AlreadyExists { |
| 967 | ErrorCode::Conflict |
| 968 | } else { |
| 969 | crate::space::io_error(e) |
| 970 | } |
| 971 | })?; |
| 972 | let mut temporary = None; |
| 973 | let written = (|| { |
| 974 | temporary = Some(PublicationTemp { |
| 975 | parent: object(dir.handle())?, |
| 976 | name: temp.clone(), |
| 977 | object: object(&file)?, |
| 978 | }); |
| 979 | completed(Ok(()), &mut PublicationMonitor(check))?; |
| 980 | completed( |
| 981 | crate::space::ensure(&file, length), |
| 982 | &mut PublicationMonitor(check), |
| 983 | )?; |
| 984 | let mut buffer = zeroize::Zeroizing::new([0; 65536]); |
| 985 | let mut remaining = length; |
| 986 | while remaining != 0 { |
| 987 | check(PublishStep::Check)?; |
| 988 | let count = remaining.min(buffer.len() as u64) as usize; |
| 989 | let n = data.read(&mut buffer[..count]).map_err(|_| ErrorCode::Io)?; |
| 990 | if n == 0 { |
| 991 | return Err(ErrorCode::Io); |
| 992 | } |
| 993 | completed(Ok(()), &mut PublicationMonitor(check))?; |
| 994 | completed( |
| 995 | crate::space::ensure(&file, n as u64), |
| 996 | &mut PublicationMonitor(check), |
| 997 | )?; |
| 998 | completed( |
| 999 | file.write_all(&buffer[..n]).map_err(crate::space::io_error), |
| 1000 | &mut PublicationMonitor(check), |
| 1001 | )?; |
| 1002 | remaining -= n as u64; |
| 1003 | } |
| 1004 | completed( |
| 1005 | file.sync_all().map_err(crate::space::io_error), |
| 1006 | &mut PublicationMonitor(check), |
| 1007 | ) |
| 1008 | })(); |
| 1009 | let identity = temporary.as_ref().map(|temp| temp.object.clone()); |
| 1010 | let closed = completed( |
| 1011 | close(file).map_err(crate::space::io_error), |
| 1012 | &mut PublicationMonitor(check), |
| 1013 | ); |
| 1014 | let mut finish = written.and(closed).and_then(|_| { |
| 1015 | check(PublishStep::Commit(temporary))?; |
| 1016 | // 생성한 임시 파일과 이름이 가리키는 파일이 같은지 확인함. |
| 1017 | if dir.existing(&temp)?.as_ref().map(|file| &file.object) != identity.as_ref() { |
| 1018 | return Err(ErrorCode::Conflict); |
| 1019 | } |
| 1020 | // 긴 원본 재검증 중 바뀐 대상은 교체 직전에 거부함. |
| 1021 | if let Some(expected) = replace { |
| 1022 | if completed(dir.existing(&leaf), &mut PublicationMonitor(check))?.as_ref() |
| 1023 | != Some(expected) |
| 1024 | { |
| 1025 | return Err(ErrorCode::Conflict); |
| 1026 | } |
| 1027 | } |
| 1028 | Ok(()) |
| 1029 | }); |
| 1030 | let mut temp_consumed = false; |
| 1031 | if finish.is_ok() { |
| 1032 | let published = if replace.is_some() { |
| 1033 | dir.replace(&temp, &leaf) |
| 1034 | } else { |
| 1035 | dir.link(&temp, &leaf) |
| 1036 | }; |
| 1037 | match published { |
| 1038 | Ok(()) => { |
| 1039 | temp_consumed = replace.is_some(); |
| 1040 | result.created = true; |
| 1041 | publication_activity(&mut finish, check); |
| 1042 | match dir.sync_checked() { |
| 1043 | Ok(durability) => { |
| 1044 | result.durability = durability; |
| 1045 | publication_activity(&mut finish, check); |
| 1046 | } |
| 1047 | Err(error) => { |
| 1048 | result.durability = Durability::Failed; |
| 1049 | finish = Err(error); |
| 1050 | } |
| 1051 | } |
| 1052 | } |
| 1053 | Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { |
| 1054 | finish = Err(ErrorCode::Conflict) |
| 1055 | } |
| 1056 | Err(error) => { |
| 1057 | result.uncertain = true; |
| 1058 | result.durability = Durability::Unconfirmed; |
| 1059 | finish = Err(crate::space::io_error(error)); |
| 1060 | } |
| 1061 | } |
| 1062 | } |
| 1063 | if !temp_consumed { |
| 1064 | match dir.existing(&temp) { |
| 1065 | Ok(None) => result.cleanup = Cleanup::Unconfirmed, |
| 1066 | Ok(Some(current)) if Some(¤t.object) == identity.as_ref() => { |
| 1067 | if dir.remove(&temp) { |
| 1068 | publication_activity(&mut finish, check); |
| 1069 | } else { |
| 1070 | result.cleanup = Cleanup::Failed; |
| 1071 | result.retained = 1; |
| 1072 | result.retained_name = Some(match name.rsplit_once('/') { |
| 1073 | Some((prefix, _)) => format!("{prefix}/{temp}"), |
| 1074 | None => temp.clone(), |
| 1075 | }); |
| 1076 | } |
| 1077 | } |
| 1078 | _ => { |
| 1079 | // 다른 파일은 보존하고 소유 임시 파일의 위치를 단정하지 않음. |
| 1080 | result.cleanup = Cleanup::Unconfirmed; |
| 1081 | } |
| 1082 | } |
| 1083 | if result.cleanup != Cleanup::Complete && finish.is_ok() { |
| 1084 | finish = Err(ErrorCode::Io); |
| 1085 | } |
| 1086 | } |
| 1087 | if result.created { |
| 1088 | if let Err(error) = dir.sync_checked() { |
| 1089 | result.durability = Durability::Failed; |
| 1090 | finish = Err(error); |
| 1091 | } else { |
| 1092 | publication_activity(&mut finish, check); |
| 1093 | } |
| 1094 | } |
| 1095 | if result.created { |
| 1096 | // 이름 기반 게시 뒤에도 결과가 생성한 파일인지 확인함. |
| 1097 | let verified = match dir.existing(&leaf) { |
| 1098 | Ok(Some(current)) if Some(¤t.object) == identity.as_ref() => Ok(()), |
| 1099 | Ok(_) => Err(ErrorCode::Conflict), |
| 1100 | Err(error) => Err(error), |
| 1101 | }; |
| 1102 | if let Err(error) = verified { |
| 1103 | result.created = false; |
| 1104 | result.uncertain = true; |
| 1105 | result.durability = Durability::Unconfirmed; |
| 1106 | if result.cleanup == Cleanup::Complete { |
| 1107 | result.cleanup = Cleanup::Unconfirmed; |
| 1108 | } |
| 1109 | finish = Err(error); |
| 1110 | } |
| 1111 | } |
| 1112 | finish |
| 1113 | })(); |
| 1114 | result.error = prepared.err(); |
| 1115 | result |
| 1116 | } |