| 1 | #![deny(unsafe_op_in_unsafe_fn)] |
| 2 | |
| 3 | use sha2::{Digest, Sha256}; |
| 4 | use std::{ |
| 5 | collections::TryReserveError, |
| 6 | io, |
| 7 | path::Path, |
| 8 | time::{Duration, Instant}, |
| 9 | }; |
| 10 | |
| 11 | #[cfg(target_os = "linux")] |
| 12 | mod linux; |
| 13 | |
| 14 | pub const MAX_BYTES: u64 = 16 * 1024 * 1024; |
| 15 | pub const MAX_IO_BYTES: u64 = 128 * 1024 * 1024; |
| 16 | pub const MAX_READ_CALLS: u64 = 131_072; |
| 17 | pub const CHUNK_BYTES: usize = 65_536; |
| 18 | |
| 19 | #[derive(Clone, Copy, Debug)] |
| 20 | pub struct Limits { |
| 21 | pub max_bytes: u64, |
| 22 | pub max_io_bytes: u64, |
| 23 | pub max_read_calls: u64, |
| 24 | pub max_duration: Duration, |
| 25 | } |
| 26 | |
| 27 | impl Default for Limits { |
| 28 | fn default() -> Self { |
| 29 | Self { |
| 30 | max_bytes: MAX_BYTES, |
| 31 | max_io_bytes: MAX_IO_BYTES, |
| 32 | max_read_calls: MAX_READ_CALLS, |
| 33 | max_duration: Duration::from_secs(30), |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 39 | pub struct Usage { |
| 40 | pub open_calls: u64, |
| 41 | pub metadata_calls: u64, |
| 42 | pub read_calls: u64, |
| 43 | pub reserved_read_bytes: u64, |
| 44 | pub actual_read_bytes: u64, |
| 45 | pub compared_bytes: u64, |
| 46 | } |
| 47 | |
| 48 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 49 | pub enum Stage { |
| 50 | Opening, |
| 51 | Pinned, |
| 52 | Copying, |
| 53 | Comparing, |
| 54 | Finalizing, |
| 55 | } |
| 56 | |
| 57 | #[derive(Clone, Copy, Debug)] |
| 58 | pub struct Checkpoint { |
| 59 | pub stage: Stage, |
| 60 | pub offset: u64, |
| 61 | pub length: Option<u64>, |
| 62 | pub usage: Usage, |
| 63 | } |
| 64 | |
| 65 | #[derive(Debug)] |
| 66 | pub enum Stop<E> { |
| 67 | Cancelled, |
| 68 | Callback(E), |
| 69 | } |
| 70 | |
| 71 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 72 | pub enum LimitKind { |
| 73 | Bytes, |
| 74 | IoBytes, |
| 75 | ReadCalls, |
| 76 | Deadline, |
| 77 | } |
| 78 | |
| 79 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 80 | pub enum Changed { |
| 81 | Metadata, |
| 82 | Contents, |
| 83 | Length, |
| 84 | Identity, |
| 85 | } |
| 86 | |
| 87 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 88 | pub enum Unsupported { |
| 89 | Platform, |
| 90 | Procfs, |
| 91 | FileType, |
| 92 | MultipleLinks, |
| 93 | } |
| 94 | |
| 95 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 96 | pub enum IoOperation { |
| 97 | PinPath, |
| 98 | Inspect, |
| 99 | OpenProc, |
| 100 | InspectProc, |
| 101 | OpenProcDescriptors, |
| 102 | ReopenPinned, |
| 103 | Read, |
| 104 | } |
| 105 | |
| 106 | #[derive(Debug)] |
| 107 | pub enum Error<E> { |
| 108 | InvalidLimits, |
| 109 | InvalidPath, |
| 110 | Unsupported(Unsupported), |
| 111 | Limit(LimitKind), |
| 112 | Changed(Changed), |
| 113 | Cancelled, |
| 114 | Callback(E), |
| 115 | Allocation(TryReserveError), |
| 116 | Io { |
| 117 | operation: IoOperation, |
| 118 | source: io::Error, |
| 119 | }, |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug)] |
| 123 | pub struct Failure<E> { |
| 124 | pub cause: Error<E>, |
| 125 | pub usage: Usage, |
| 126 | } |
| 127 | |
| 128 | /// 열린 파일의 관측값임. 경로 지속성이나 원자적 snapshot 증거가 아님. |
| 129 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 130 | pub struct Identity { |
| 131 | device: u64, |
| 132 | inode: u64, |
| 133 | length: u64, |
| 134 | links: u64, |
| 135 | mode: u32, |
| 136 | modified: (i64, i64), |
| 137 | changed: (i64, i64), |
| 138 | } |
| 139 | |
| 140 | impl Identity { |
| 141 | pub fn device(&self) -> u64 { |
| 142 | self.device |
| 143 | } |
| 144 | pub fn inode(&self) -> u64 { |
| 145 | self.inode |
| 146 | } |
| 147 | pub fn length(&self) -> u64 { |
| 148 | self.length |
| 149 | } |
| 150 | pub fn links(&self) -> u64 { |
| 151 | self.links |
| 152 | } |
| 153 | pub fn mode(&self) -> u32 { |
| 154 | self.mode |
| 155 | } |
| 156 | pub fn modified(&self) -> (i64, i64) { |
| 157 | self.modified |
| 158 | } |
| 159 | pub fn changed(&self) -> (i64, i64) { |
| 160 | self.changed |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | /// 두 번 읽어 일치한 메모리 사본임. 동시 변경 전체 탐지나 게시 증거가 아님. |
| 165 | pub struct FileSnapshot { |
| 166 | bytes: Vec<u8>, |
| 167 | identity: Identity, |
| 168 | sha256: [u8; 32], |
| 169 | usage: Usage, |
| 170 | } |
| 171 | |
| 172 | impl FileSnapshot { |
| 173 | pub fn bytes(&self) -> &[u8] { |
| 174 | &self.bytes |
| 175 | } |
| 176 | pub fn identity(&self) -> Identity { |
| 177 | self.identity |
| 178 | } |
| 179 | pub fn sha256(&self) -> [u8; 32] { |
| 180 | self.sha256 |
| 181 | } |
| 182 | pub fn usage(&self) -> Usage { |
| 183 | self.usage |
| 184 | } |
| 185 | /// 원본 bytes를 이동하며 snapshot 증명 객체는 소비함. |
| 186 | pub fn into_bytes(self) -> Vec<u8> { |
| 187 | self.bytes |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | impl std::fmt::Debug for FileSnapshot { |
| 192 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 193 | f.debug_struct("FileSnapshot") |
| 194 | .field("length", &self.bytes.len()) |
| 195 | .field("usage", &self.usage) |
| 196 | .finish_non_exhaustive() |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | pub struct Request<'a> { |
| 201 | pub path: &'a Path, |
| 202 | pub limits: Limits, |
| 203 | } |
| 204 | |
| 205 | struct Run { |
| 206 | limits: Limits, |
| 207 | usage: Usage, |
| 208 | started: Instant, |
| 209 | } |
| 210 | |
| 211 | impl Run { |
| 212 | fn checkpoint<E>( |
| 213 | &self, |
| 214 | stage: Stage, |
| 215 | offset: u64, |
| 216 | length: Option<u64>, |
| 217 | callback: &mut impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 218 | ) -> Result<(), Error<E>> { |
| 219 | callback(Checkpoint { |
| 220 | stage, |
| 221 | offset, |
| 222 | length, |
| 223 | usage: self.usage, |
| 224 | }) |
| 225 | .map_err(|stop| match stop { |
| 226 | Stop::Cancelled => Error::Cancelled, |
| 227 | Stop::Callback(error) => Error::Callback(error), |
| 228 | })?; |
| 229 | if self.started.elapsed() >= self.limits.max_duration { |
| 230 | return Err(Error::Limit(LimitKind::Deadline)); |
| 231 | } |
| 232 | Ok(()) |
| 233 | } |
| 234 | |
| 235 | fn reserve_read<E>(&mut self, count: usize) -> Result<(), Error<E>> { |
| 236 | if self.usage.read_calls >= self.limits.max_read_calls { |
| 237 | return Err(Error::Limit(LimitKind::ReadCalls)); |
| 238 | } |
| 239 | if count as u64 > self.limits.max_io_bytes - self.usage.reserved_read_bytes { |
| 240 | return Err(Error::Limit(LimitKind::IoBytes)); |
| 241 | } |
| 242 | self.usage.read_calls += 1; |
| 243 | self.usage.reserved_read_bytes += count as u64; |
| 244 | Ok(()) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | /// 일반 파일을 처음부터 캡처함. callback과 파일 I/O의 강제 종료 시간은 보장하지 않음. |
| 249 | pub fn capture<E>( |
| 250 | request: Request<'_>, |
| 251 | mut checkpoint: impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 252 | ) -> Result<FileSnapshot, Failure<E>> { |
| 253 | let mut run = Run { |
| 254 | limits: request.limits, |
| 255 | usage: Usage::default(), |
| 256 | started: Instant::now(), |
| 257 | }; |
| 258 | let limits = request.limits; |
| 259 | if limits.max_bytes > MAX_BYTES |
| 260 | || limits.max_io_bytes > MAX_IO_BYTES |
| 261 | || limits.max_read_calls == 0 |
| 262 | || limits.max_read_calls > MAX_READ_CALLS |
| 263 | || limits.max_duration.is_zero() |
| 264 | || limits.max_duration > Duration::from_secs(300) |
| 265 | { |
| 266 | return Err(Failure { |
| 267 | cause: Error::InvalidLimits, |
| 268 | usage: run.usage, |
| 269 | }); |
| 270 | } |
| 271 | #[cfg(target_os = "linux")] |
| 272 | let result = linux::capture(request.path, &mut run, &mut checkpoint); |
| 273 | #[cfg(not(target_os = "linux"))] |
| 274 | let result: Result<FileSnapshot, Error<E>> = { |
| 275 | let _ = (&request.path, &mut checkpoint); |
| 276 | Err(Error::Unsupported(Unsupported::Platform)) |
| 277 | }; |
| 278 | result.map_err(|cause| Failure { |
| 279 | cause, |
| 280 | usage: run.usage, |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | fn digest(bytes: &[u8]) -> [u8; 32] { |
| 285 | Sha256::digest(bytes).into() |
| 286 | } |