team-ljyzipelo

공개
278줄8.2 KB
1use super::*;
2use std::{
3 ffi::CString,
4 fs::{File, Metadata},
5 os::{
6 fd::{AsRawFd, FromRawFd},
7 unix::{
8 ffi::OsStrExt,
9 fs::{FileExt, MetadataExt},
10 },
11 },
12};
13
14#[repr(C)]
15struct OpenHow {
16 flags: u64,
17 mode: u64,
18 resolve: u64,
19}
20
21fn io_error<E>(operation: IoOperation, source: io::Error) -> Error<E> {
22 Error::Io { operation, source }
23}
24
25fn open<E>(
26 directory: i32,
27 path: &std::ffi::CStr,
28 flags: i32,
29 resolve: u64,
30 operation: IoOperation,
31 run: &mut Run,
32) -> Result<File, Error<E>> {
33 let how = OpenHow {
34 flags: flags as u64,
35 mode: 0,
36 resolve,
37 };
38 run.usage.open_calls += 1;
39 // 초기화된 구조체와 NUL 종료 문자열을 호출 동안 유지함.
40 let fd = unsafe {
41 libc::syscall(
42 libc::SYS_openat2,
43 directory,
44 path.as_ptr(),
45 &how as *const OpenHow,
46 std::mem::size_of::<OpenHow>(),
47 )
48 };
49 if fd < 0 {
50 let source = io::Error::last_os_error();
51 return Err(io_error(operation, source));
52 }
53 // 성공한 syscall의 새 fd 소유권을 한 번만 이전함.
54 Ok(unsafe { File::from_raw_fd(fd as i32) })
55}
56
57fn inspect<E>(file: &File, run: &mut Run) -> Result<Identity, Error<E>> {
58 run.usage.metadata_calls += 1;
59 let metadata = file
60 .metadata()
61 .map_err(|e| io_error(IoOperation::Inspect, e))?;
62 regular(&metadata)?;
63 Ok(Identity {
64 device: metadata.dev(),
65 inode: metadata.ino(),
66 length: metadata.len(),
67 links: metadata.nlink(),
68 mode: metadata.mode(),
69 modified: (metadata.mtime(), metadata.mtime_nsec()),
70 changed: (metadata.ctime(), metadata.ctime_nsec()),
71 })
72}
73
74fn regular<E>(metadata: &Metadata) -> Result<(), Error<E>> {
75 if !metadata.is_file() {
76 return Err(Error::Unsupported(Unsupported::FileType));
77 }
78 if metadata.nlink() != 1 {
79 return Err(Error::Unsupported(Unsupported::MultipleLinks));
80 }
81 Ok(())
82}
83
84fn same<E>(before: Identity, after: Identity) -> Result<(), Error<E>> {
85 if before.device != after.device || before.inode != after.inode {
86 return Err(Error::Changed(Changed::Identity));
87 }
88 if before.length != after.length {
89 return Err(Error::Changed(Changed::Length));
90 }
91 if before != after {
92 return Err(Error::Changed(Changed::Metadata));
93 }
94 Ok(())
95}
96
97fn read<E>(file: &File, output: &mut [u8], offset: u64, run: &mut Run) -> Result<usize, Error<E>> {
98 run.reserve_read(output.len())?;
99 // EINTR도 원래 오류로 반환하며 자동 재시도로 계수를 숨기지 않음.
100 let count = file
101 .read_at(output, offset)
102 .map_err(|e| io_error(IoOperation::Read, e))?;
103 run.usage.actual_read_bytes += count as u64;
104 Ok(count)
105}
106
107fn eof<E>(file: &File, length: u64, run: &mut Run) -> Result<(), Error<E>> {
108 if read(file, &mut [0; 1], length, run)? != 0 {
109 return Err(Error::Changed(Changed::Length));
110 }
111 Ok(())
112}
113
114pub(super) fn capture<E>(
115 path: &Path,
116 run: &mut Run,
117 callback: &mut impl FnMut(Checkpoint) -> Result<(), Stop<E>>,
118) -> Result<FileSnapshot, Error<E>> {
119 run.checkpoint(Stage::Opening, 0, None, callback)?;
120 let raw = path.as_os_str().as_bytes();
121 if raw.len() < 2
122 || raw.len() > 4096
123 || raw[0] != b'/'
124 || raw[1..]
125 .split(|b| *b == b'/')
126 .any(|part| part.is_empty() || part == b"." || part == b".." || part.len() > 255)
127 {
128 return Err(Error::InvalidPath);
129 }
130 let name = CString::new(raw).map_err(|_| Error::InvalidPath)?;
131 let pinned = open(
132 libc::AT_FDCWD,
133 &name,
134 libc::O_PATH | libc::O_CLOEXEC,
135 0x04,
136 IoOperation::PinPath,
137 run,
138 )?;
139 let identity = inspect(&pinned, run)?;
140 if identity.length > run.limits.max_bytes {
141 return Err(Error::Limit(LimitKind::Bytes));
142 }
143 run.checkpoint(Stage::Pinned, 0, Some(identity.length), callback)?;
144
145 // 검증한 procfs 디렉터리에서 보유 regular-file fd만 읽기 모드로 다시 엶.
146 let proc = open(
147 libc::AT_FDCWD,
148 c"/proc",
149 libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
150 0x04,
151 IoOperation::OpenProc,
152 run,
153 )?;
154 let mut status = std::mem::MaybeUninit::<libc::statfs>::uninit();
155 run.usage.metadata_calls += 1;
156 // 성공 반환일 때만 커널이 초기화한 statfs 값을 읽음.
157 if unsafe { libc::fstatfs(proc.as_raw_fd(), status.as_mut_ptr()) } != 0 {
158 return Err(io_error(
159 IoOperation::InspectProc,
160 io::Error::last_os_error(),
161 ));
162 }
163 if unsafe { status.assume_init() }.f_type != libc::PROC_SUPER_MAGIC {
164 return Err(Error::Unsupported(Unsupported::Procfs));
165 }
166 let directory_name =
167 CString::new(format!("{}/fd", std::process::id())).map_err(|_| Error::InvalidPath)?;
168 let descriptors = open(
169 proc.as_raw_fd(),
170 &directory_name,
171 libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
172 0x0d,
173 IoOperation::OpenProcDescriptors,
174 run,
175 )?;
176 let descriptor_name =
177 CString::new(pinned.as_raw_fd().to_string()).map_err(|_| Error::InvalidPath)?;
178 run.usage.open_calls += 1;
179 // 검증한 procfs fd 디렉터리의 보유 fd 링크만 의도적으로 따라감.
180 let descriptor = unsafe {
181 libc::openat(
182 descriptors.as_raw_fd(),
183 descriptor_name.as_ptr(),
184 libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC | libc::O_NOCTTY,
185 )
186 };
187 if descriptor < 0 {
188 return Err(io_error(
189 IoOperation::ReopenPinned,
190 io::Error::last_os_error(),
191 ));
192 }
193 // 새 읽기 fd만 소유하며 원래 경로를 다시 열지 않음.
194 let file = unsafe { File::from_raw_fd(descriptor) };
195 same(identity, inspect(&file, run)?)?;
196 drop(descriptors);
197 drop(proc);
198 drop(pinned);
199
200 let length = identity.length as usize;
201 run.checkpoint(Stage::Copying, 0, Some(identity.length), callback)?;
202 let mut bytes = Vec::new();
203 bytes.try_reserve_exact(length).map_err(Error::Allocation)?;
204 bytes.resize(length, 0);
205 let mut offset = 0;
206 while offset < length {
207 run.checkpoint(
208 Stage::Copying,
209 offset as u64,
210 Some(identity.length),
211 callback,
212 )?;
213 let end = (offset + CHUNK_BYTES).min(length);
214 let count = read(&file, &mut bytes[offset..end], offset as u64, run)?;
215 if count == 0 {
216 return Err(Error::Changed(Changed::Length));
217 }
218 offset += count;
219 }
220 run.checkpoint(
221 Stage::Copying,
222 offset as u64,
223 Some(identity.length),
224 callback,
225 )?;
226 eof(&file, identity.length, run)?;
227 same(identity, inspect(&file, run)?)?;
228
229 let mut check = [0; CHUNK_BYTES];
230 offset = 0;
231 while offset < length {
232 run.checkpoint(
233 Stage::Comparing,
234 offset as u64,
235 Some(identity.length),
236 callback,
237 )?;
238 let count = read(
239 &file,
240 &mut check[..(length - offset).min(CHUNK_BYTES)],
241 offset as u64,
242 run,
243 )?;
244 if count == 0 {
245 return Err(Error::Changed(Changed::Length));
246 }
247 run.usage.compared_bytes += count as u64;
248 if bytes[offset..offset + count] != check[..count] {
249 return Err(Error::Changed(Changed::Contents));
250 }
251 offset += count;
252 }
253 run.checkpoint(
254 Stage::Comparing,
255 offset as u64,
256 Some(identity.length),
257 callback,
258 )?;
259 eof(&file, identity.length, run)?;
260 let sha256 = digest(&bytes);
261 run.checkpoint(
262 Stage::Finalizing,
263 offset as u64,
264 Some(identity.length),
265 callback,
266 )?;
267 same(identity, inspect(&file, run)?)?;
268 // 마지막 syscall 동안 지난 기한도 확인하며 취소 callback을 재호출하지 않음.
269 if run.started.elapsed() >= run.limits.max_duration {
270 return Err(Error::Limit(LimitKind::Deadline));
271 }
272 Ok(FileSnapshot {
273 bytes,
274 identity,
275 sha256,
276 usage: run.usage,
277 })
278}