| 1 | use super::*; |
| 2 | use std::{ |
| 3 | ffi::{CStr, CString}, |
| 4 | fs::{File, Metadata}, |
| 5 | mem::MaybeUninit, |
| 6 | os::{ |
| 7 | fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd}, |
| 8 | unix::{ffi::OsStrExt, fs::MetadataExt}, |
| 9 | }, |
| 10 | }; |
| 11 | |
| 12 | const NO_SYMLINKS: u64 = 0x04; |
| 13 | const BENEATH: u64 = 0x08; |
| 14 | const NO_XDEV: u64 = 0x01; |
| 15 | |
| 16 | #[repr(C)] |
| 17 | struct OpenHow { |
| 18 | flags: u64, |
| 19 | mode: u64, |
| 20 | resolve: u64, |
| 21 | } |
| 22 | |
| 23 | #[derive(Default)] |
| 24 | struct Handles { |
| 25 | parent: Option<File>, |
| 26 | temp: Option<File>, |
| 27 | proc_root: Option<File>, |
| 28 | proc_fds: Option<File>, |
| 29 | } |
| 30 | |
| 31 | impl Handles { |
| 32 | fn close_all(&mut self) -> Cleanup { |
| 33 | let mut cleanup = Cleanup::empty(); |
| 34 | for (resource, file) in [ |
| 35 | (Resource::TemporaryFile, self.temp.take()), |
| 36 | (Resource::ProcFdDirectory, self.proc_fds.take()), |
| 37 | (Resource::ProcRoot, self.proc_root.take()), |
| 38 | (Resource::ParentDirectory, self.parent.take()), |
| 39 | ] { |
| 40 | if let Some(file) = file { |
| 41 | let fd = file.into_raw_fd(); |
| 42 | let index = cleanup.attempted as usize; |
| 43 | cleanup.attempted += 1; |
| 44 | // 소유 fd를 한 번만 닫으며 Linux close 오류를 재시도하지 않음. |
| 45 | if unsafe { libc::close(fd) } != 0 { |
| 46 | cleanup.failures[index] = Some(CloseFailure { |
| 47 | resource, |
| 48 | source: io::Error::last_os_error(), |
| 49 | }); |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | cleanup |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub(super) fn publish<E>( |
| 58 | request: Request<'_>, |
| 59 | run: &mut Run<'_>, |
| 60 | callback: &mut impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 61 | ) -> Report<E> { |
| 62 | let mut handles = Handles::default(); |
| 63 | let outcome = match perform(request, run, callback, &mut handles) { |
| 64 | Ok(outcome) => outcome, |
| 65 | Err(error) => Outcome::NotCommitted(error), |
| 66 | }; |
| 67 | let cleanup = handles.close_all(); |
| 68 | Report { |
| 69 | outcome, |
| 70 | usage: run.usage, |
| 71 | cleanup, |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | fn io_error<E>(operation: &'static str, source: io::Error) -> Error<E> { |
| 76 | Error::Io { operation, source } |
| 77 | } |
| 78 | |
| 79 | fn opened<E>(fd: libc::c_long, operation: &'static str) -> Result<File, Error<E>> { |
| 80 | if fd < 0 { |
| 81 | return Err(io_error(operation, io::Error::last_os_error())); |
| 82 | } |
| 83 | // 성공한 open 계열 호출의 새 fd 소유권을 정확히 한 번 인수함. |
| 84 | Ok(unsafe { File::from_raw_fd(fd as RawFd) }) |
| 85 | } |
| 86 | |
| 87 | fn open2<E>( |
| 88 | dir: RawFd, |
| 89 | path: &CStr, |
| 90 | flags: i32, |
| 91 | resolve: u64, |
| 92 | run: &mut Run<'_>, |
| 93 | ) -> Result<File, Error<E>> { |
| 94 | let how = OpenHow { |
| 95 | flags: flags as u64, |
| 96 | mode: 0, |
| 97 | resolve, |
| 98 | }; |
| 99 | run.usage.open_calls += 1; |
| 100 | // NUL 종료 경로와 초기화한 구조체를 호출 동안 유지함. |
| 101 | let fd = unsafe { |
| 102 | libc::syscall( |
| 103 | libc::SYS_openat2, |
| 104 | dir, |
| 105 | path.as_ptr(), |
| 106 | &how as *const OpenHow, |
| 107 | std::mem::size_of::<OpenHow>(), |
| 108 | ) |
| 109 | }; |
| 110 | opened(fd, "openat2") |
| 111 | } |
| 112 | |
| 113 | fn metadata<E>(file: &File, run: &mut Run<'_>) -> Result<Metadata, Error<E>> { |
| 114 | run.usage.metadata_calls += 1; |
| 115 | file.metadata().map_err(|error| io_error("fstat", error)) |
| 116 | } |
| 117 | |
| 118 | fn filesystem<E>(file: &File, run: &mut Run<'_>) -> Result<u64, Error<E>> { |
| 119 | let mut value = MaybeUninit::<libc::statfs>::uninit(); |
| 120 | run.usage.metadata_calls += 1; |
| 121 | // 성공한 fstatfs만 초기화된 구조체로 읽음. |
| 122 | if unsafe { libc::fstatfs(file.as_raw_fd(), value.as_mut_ptr()) } != 0 { |
| 123 | return Err(io_error("fstatfs", io::Error::last_os_error())); |
| 124 | } |
| 125 | Ok(unsafe { value.assume_init() }.f_type as u64) |
| 126 | } |
| 127 | |
| 128 | fn identity(value: &Metadata) -> Identity { |
| 129 | Identity { |
| 130 | device: value.dev(), |
| 131 | inode: value.ino(), |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | fn paths<E>(request: &Request<'_>) -> Result<(CString, CString), Error<E>> { |
| 136 | let parent = request.parent.as_os_str().as_bytes(); |
| 137 | let leaf = request.leaf.as_bytes(); |
| 138 | if parent.first() != Some(&b'/') |
| 139 | || parent.len() > 4095 |
| 140 | || (parent != b"/" |
| 141 | && parent[1..] |
| 142 | .split(|v| *v == b'/') |
| 143 | .any(|v| v.is_empty() || v == b"." || v == b"..")) |
| 144 | || leaf.is_empty() |
| 145 | || leaf.len() > 255 |
| 146 | || leaf == b"." |
| 147 | || leaf == b".." |
| 148 | || leaf.contains(&b'/') |
| 149 | { |
| 150 | return Err(Error::InvalidPath); |
| 151 | } |
| 152 | Ok(( |
| 153 | CString::new(parent).map_err(|_| Error::InvalidPath)?, |
| 154 | CString::new(leaf).map_err(|_| Error::InvalidPath)?, |
| 155 | )) |
| 156 | } |
| 157 | |
| 158 | fn perform<E>( |
| 159 | request: Request<'_>, |
| 160 | run: &mut Run<'_>, |
| 161 | callback: &mut impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 162 | handles: &mut Handles, |
| 163 | ) -> Result<Outcome<E>, Error<E>> { |
| 164 | let (parent_path, leaf) = paths(&request)?; |
| 165 | run.check(Stage::Opening, 0, callback)?; |
| 166 | handles.parent = Some(open2( |
| 167 | libc::AT_FDCWD, |
| 168 | &parent_path, |
| 169 | libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC | libc::O_NONBLOCK | libc::O_NOCTTY, |
| 170 | NO_SYMLINKS, |
| 171 | run, |
| 172 | )?); |
| 173 | let parent = handles.parent.as_ref().expect("owned parent"); |
| 174 | let parent_meta = metadata(parent, run)?; |
| 175 | // 유효 UID를 읽을 뿐 권한이나 신원을 변경하지 않음. |
| 176 | let uid = unsafe { libc::geteuid() }; |
| 177 | if !parent_meta.is_dir() || parent_meta.uid() != uid || parent_meta.mode() & 0o022 != 0 { |
| 178 | return Err(Error::UntrustedParent); |
| 179 | } |
| 180 | match filesystem(parent, run)? { |
| 181 | 0xef53 | 0x58465342 => {} |
| 182 | _ => return Err(Error::UnsupportedFilesystem), |
| 183 | } |
| 184 | run.check(Stage::Opening, 0, callback)?; |
| 185 | run.usage.open_calls += 1; |
| 186 | // 고정 부모 아래 이름 없는 파일을 만들며 O_EXCL을 사용하지 않음. |
| 187 | handles.temp = Some(opened( |
| 188 | unsafe { |
| 189 | libc::openat( |
| 190 | parent.as_raw_fd(), |
| 191 | c".".as_ptr(), |
| 192 | libc::O_TMPFILE | libc::O_RDWR | libc::O_CLOEXEC, |
| 193 | 0o600 as libc::mode_t, |
| 194 | ) |
| 195 | } as libc::c_long, |
| 196 | "openat_tmpfile", |
| 197 | )?); |
| 198 | let temp = handles.temp.as_mut().expect("owned temporary file"); |
| 199 | let initial = metadata(temp, run)?; |
| 200 | if !initial.is_file() |
| 201 | || initial.nlink() != 0 |
| 202 | || initial.uid() != uid |
| 203 | || initial.dev() != parent_meta.dev() |
| 204 | { |
| 205 | return Err(Error::InvalidTemporaryFile); |
| 206 | } |
| 207 | let mut offset = 0; |
| 208 | while offset < request.bytes.len() { |
| 209 | run.check(Stage::Writing, offset, callback)?; |
| 210 | let end = (offset + CHUNK_BYTES).min(request.bytes.len()); |
| 211 | run.reserve(end - offset, true)?; |
| 212 | // 읽기 전용 입력 슬라이스의 유효 범위만 커널에 전달함. |
| 213 | let result = unsafe { |
| 214 | libc::write( |
| 215 | temp.as_raw_fd(), |
| 216 | request.bytes[offset..end].as_ptr().cast(), |
| 217 | end - offset, |
| 218 | ) |
| 219 | }; |
| 220 | if result < 0 { |
| 221 | return Err(io_error("write", io::Error::last_os_error())); |
| 222 | } |
| 223 | let count = result as usize; |
| 224 | run.usage.actual_written_bytes += count as u64; |
| 225 | if count == 0 { |
| 226 | return Err(io_error("write", io::Error::from(io::ErrorKind::WriteZero))); |
| 227 | } |
| 228 | offset += count; |
| 229 | } |
| 230 | run.check(Stage::Verifying, 0, callback)?; |
| 231 | run.usage.sync_calls += 1; |
| 232 | sync(temp).map_err(|error| io_error("fsync_file", error))?; |
| 233 | // 소유한 임시 파일의 읽기 위치만 이동함. |
| 234 | if unsafe { libc::lseek(temp.as_raw_fd(), 0, libc::SEEK_SET) } < 0 { |
| 235 | return Err(io_error("lseek", io::Error::last_os_error())); |
| 236 | } |
| 237 | let mut scratch = [0_u8; CHUNK_BYTES]; |
| 238 | offset = 0; |
| 239 | while offset < request.bytes.len() { |
| 240 | run.check(Stage::Verifying, offset, callback)?; |
| 241 | let count = CHUNK_BYTES.min(request.bytes.len() - offset); |
| 242 | run.reserve(count, false)?; |
| 243 | let read = |
| 244 | read_once(temp, &mut scratch[..count]).map_err(|error| io_error("read", error))?; |
| 245 | run.usage.actual_read_bytes += read as u64; |
| 246 | if read == 0 || scratch[..read] != request.bytes[offset..offset + read] { |
| 247 | return Err(Error::VerificationMismatch); |
| 248 | } |
| 249 | offset += read; |
| 250 | } |
| 251 | run.check(Stage::Verifying, offset, callback)?; |
| 252 | run.reserve(1, false)?; |
| 253 | let extra = read_once(temp, &mut scratch[..1]).map_err(|error| io_error("read_eof", error))?; |
| 254 | run.usage.actual_read_bytes += extra as u64; |
| 255 | if extra != 0 { |
| 256 | return Err(Error::VerificationMismatch); |
| 257 | } |
| 258 | let final_meta = metadata(temp, run)?; |
| 259 | if identity(&final_meta) != identity(&initial) |
| 260 | || !final_meta.is_file() |
| 261 | || final_meta.nlink() != 0 |
| 262 | || final_meta.len() != request.bytes.len() as u64 |
| 263 | { |
| 264 | return Err(Error::VerificationMismatch); |
| 265 | } |
| 266 | // procfs 연결 방식은 파일 계층용이며 worker 실행 우회가 아님. |
| 267 | handles.proc_root = Some(open2( |
| 268 | libc::AT_FDCWD, |
| 269 | c"/proc", |
| 270 | libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC, |
| 271 | NO_SYMLINKS, |
| 272 | run, |
| 273 | )?); |
| 274 | let proc_root = handles.proc_root.as_ref().expect("owned proc root"); |
| 275 | if filesystem(proc_root, run)? != 0x9fa0 { |
| 276 | return Err(Error::UnsupportedFilesystem); |
| 277 | } |
| 278 | // 현재 프로세스의 숫자 경로를 사용해 self 심볼릭 링크를 피함. |
| 279 | let pid = unsafe { libc::getpid() }; |
| 280 | let proc_path = CString::new(format!("{pid}/fd")).map_err(|_| Error::InvalidPath)?; |
| 281 | handles.proc_fds = Some(open2( |
| 282 | proc_root.as_raw_fd(), |
| 283 | &proc_path, |
| 284 | libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC, |
| 285 | BENEATH | NO_SYMLINKS | NO_XDEV, |
| 286 | run, |
| 287 | )?); |
| 288 | let proc_fds = handles.proc_fds.as_ref().expect("owned proc fd directory"); |
| 289 | let fd_name = CString::new(temp.as_raw_fd().to_string()).map_err(|_| Error::InvalidPath)?; |
| 290 | run.check(Stage::BeforeCommit, offset, callback)?; |
| 291 | run.begin_commit()?; |
| 292 | run.usage.link_calls += 1; |
| 293 | // CAS 이후 callback 없이 소유 fd와 고정 부모 사이의 원자적 링크를 한 번 시도함. |
| 294 | let linked = unsafe { |
| 295 | libc::linkat( |
| 296 | proc_fds.as_raw_fd(), |
| 297 | fd_name.as_ptr(), |
| 298 | parent.as_raw_fd(), |
| 299 | leaf.as_ptr(), |
| 300 | libc::AT_SYMLINK_FOLLOW, |
| 301 | ) |
| 302 | }; |
| 303 | if linked != 0 { |
| 304 | let source = io::Error::last_os_error(); |
| 305 | if source.raw_os_error() == Some(libc::EEXIST) { |
| 306 | return Err(io_error("linkat_conflict", source)); |
| 307 | } |
| 308 | return Ok(Outcome::CommitUncertain { source }); |
| 309 | } |
| 310 | let receipt = FileCommitReceipt { |
| 311 | parent: identity(&parent_meta), |
| 312 | file: identity(&initial), |
| 313 | length: run.length, |
| 314 | }; |
| 315 | run.usage.sync_calls += 1; |
| 316 | let durability = match sync(parent) { |
| 317 | Ok(()) => Durability::FileAndParentSynced, |
| 318 | Err(error) => Durability::ParentSyncFailed(error), |
| 319 | }; |
| 320 | Ok(Outcome::Committed { |
| 321 | receipt, |
| 322 | durability, |
| 323 | }) |
| 324 | } |
| 325 | |
| 326 | fn read_once(file: &File, buffer: &mut [u8]) -> io::Result<usize> { |
| 327 | // 독점 대여한 버퍼의 길이 안에서만 읽으며 EINTR도 원형으로 반환함. |
| 328 | let result = unsafe { libc::read(file.as_raw_fd(), buffer.as_mut_ptr().cast(), buffer.len()) }; |
| 329 | if result < 0 { |
| 330 | Err(io::Error::last_os_error()) |
| 331 | } else { |
| 332 | Ok(result as usize) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | fn sync(file: &File) -> io::Result<()> { |
| 337 | // 소유 fd에 한 번만 fsync를 호출함. |
| 338 | if unsafe { libc::fsync(file.as_raw_fd()) } == 0 { |
| 339 | Ok(()) |
| 340 | } else { |
| 341 | Err(io::Error::last_os_error()) |
| 342 | } |
| 343 | } |