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