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