| 1 | #![forbid(unsafe_code)] |
| 2 | |
| 3 | mod budget; |
| 4 | pub use budget::{Budget, CHUNK_SIZE, Limits, Usage}; |
| 5 | pub use zlib_rs::InflateError; |
| 6 | use zlib_rs::{Inflate, InflateFlush, Status, crc32::crc32}; |
| 7 | |
| 8 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 9 | pub enum Failure { |
| 10 | InvalidRequest, |
| 11 | Header, |
| 12 | Truncated, |
| 13 | Boundary, |
| 14 | Crc, |
| 15 | Size, |
| 16 | TrailingData, |
| 17 | Budget, |
| 18 | NoProgress, |
| 19 | Allocation, |
| 20 | Cancelled, |
| 21 | } |
| 22 | |
| 23 | #[derive(Debug)] |
| 24 | pub enum Error<E> { |
| 25 | Reader(Failure), |
| 26 | Backend(InflateError), |
| 27 | Callback(E), |
| 28 | } |
| 29 | |
| 30 | impl<E> From<Failure> for Error<E> { |
| 31 | fn from(value: Failure) -> Self { |
| 32 | Self::Reader(value) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | #[derive(Debug)] |
| 37 | pub enum Stop<E> { |
| 38 | Cancelled, |
| 39 | Deadline, |
| 40 | Callback(E), |
| 41 | } |
| 42 | |
| 43 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 44 | pub enum Stage { |
| 45 | Start, |
| 46 | Header, |
| 47 | BeforeInflate, |
| 48 | AfterInflate, |
| 49 | AfterOutput, |
| 50 | Trailer, |
| 51 | BeforeReturn, |
| 52 | } |
| 53 | |
| 54 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 55 | pub struct Checkpoint { |
| 56 | pub stage: Stage, |
| 57 | pub usage: Usage, |
| 58 | } |
| 59 | |
| 60 | pub struct Request { |
| 61 | pub input: Box<[u8]>, |
| 62 | pub selected: bool, |
| 63 | } |
| 64 | |
| 65 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 66 | pub struct Boundary { |
| 67 | pub header_bytes: usize, |
| 68 | pub deflate_bytes: u64, |
| 69 | pub read_ahead_bytes: usize, |
| 70 | pub inflated_bytes: u64, |
| 71 | pub crc32: u32, |
| 72 | pub member_bytes: usize, |
| 73 | pub offered_bytes: u64, |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug)] |
| 77 | pub struct Completed { |
| 78 | pub boundary: Boundary, |
| 79 | pub bytes: Option<Vec<u8>>, |
| 80 | pub usage: Usage, |
| 81 | } |
| 82 | |
| 83 | pub fn read<E>( |
| 84 | request: Request, |
| 85 | budget: &mut Budget, |
| 86 | mut checkpoint: impl FnMut(Checkpoint) -> Result<(), Stop<E>>, |
| 87 | ) -> Result<Completed, Error<E>> { |
| 88 | let mut context = Context { |
| 89 | budget, |
| 90 | checkpoint: &mut checkpoint, |
| 91 | }; |
| 92 | context.check(Stage::Start)?; |
| 93 | if request.input.len() as u64 > context.budget.limits().input { |
| 94 | return Err(Failure::Budget.into()); |
| 95 | } |
| 96 | let mut cursor = Cursor { |
| 97 | input: &request.input, |
| 98 | position: 0, |
| 99 | high_water: 0, |
| 100 | }; |
| 101 | let header_bytes = header(&mut cursor, &mut context)?; |
| 102 | let mut bytes = request.selected.then(Vec::new); |
| 103 | let boundary = { |
| 104 | let mut decoder = Inflate::new(false, 15); |
| 105 | decode( |
| 106 | &mut decoder, |
| 107 | &mut cursor, |
| 108 | &mut context, |
| 109 | header_bytes, |
| 110 | &mut bytes, |
| 111 | )? |
| 112 | }; |
| 113 | // decoder 정리 이후에만 완료 결과를 노출함. |
| 114 | context.check(Stage::BeforeReturn)?; |
| 115 | Ok(Completed { |
| 116 | boundary, |
| 117 | bytes, |
| 118 | usage: context.budget.usage(), |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | struct Context<'a, F> { |
| 123 | budget: &'a mut Budget, |
| 124 | checkpoint: &'a mut F, |
| 125 | } |
| 126 | |
| 127 | impl<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>> Context<'_, F> { |
| 128 | fn check(&mut self, stage: Stage) -> Result<(), Error<E>> { |
| 129 | (self.checkpoint)(Checkpoint { |
| 130 | stage, |
| 131 | usage: self.budget.usage(), |
| 132 | }) |
| 133 | .map_err(|stop| match stop { |
| 134 | Stop::Cancelled => Error::Reader(Failure::Cancelled), |
| 135 | Stop::Deadline => Error::Reader(Failure::Budget), |
| 136 | Stop::Callback(error) => Error::Callback(error), |
| 137 | })?; |
| 138 | self.budget.check()?; |
| 139 | Ok(()) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | struct Cursor<'a> { |
| 144 | input: &'a [u8], |
| 145 | position: usize, |
| 146 | high_water: usize, |
| 147 | } |
| 148 | |
| 149 | impl Cursor<'_> { |
| 150 | fn account(&mut self, end: usize, budget: &mut Budget) -> Result<(), Failure> { |
| 151 | if end > self.input.len() { |
| 152 | return Err(Failure::Boundary); |
| 153 | } |
| 154 | if end > self.high_water { |
| 155 | budget.input(end - self.high_water)?; |
| 156 | self.high_water = end; |
| 157 | } |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | fn byte<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>( |
| 162 | &mut self, |
| 163 | context: &mut Context<'_, F>, |
| 164 | stage: Stage, |
| 165 | ) -> Result<u8, Error<E>> { |
| 166 | context.check(stage)?; |
| 167 | let value = *self.input.get(self.position).ok_or(Failure::Truncated)?; |
| 168 | let end = self.position.checked_add(1).ok_or(Failure::Boundary)?; |
| 169 | self.account(end, context.budget)?; |
| 170 | self.position = end; |
| 171 | Ok(value) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | fn header<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>( |
| 176 | cursor: &mut Cursor<'_>, |
| 177 | context: &mut Context<'_, F>, |
| 178 | ) -> Result<usize, Error<E>> { |
| 179 | let mut crc = 0; |
| 180 | fn next<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>( |
| 181 | cursor: &mut Cursor<'_>, |
| 182 | context: &mut Context<'_, F>, |
| 183 | crc: &mut u32, |
| 184 | ) -> Result<u8, Error<E>> { |
| 185 | context.check(Stage::Header)?; |
| 186 | context.budget.metadata()?; |
| 187 | let value = cursor.byte(context, Stage::Header)?; |
| 188 | *crc = crc32(*crc, &[value]); |
| 189 | Ok(value) |
| 190 | } |
| 191 | for expected in [0x1f, 0x8b, 8] { |
| 192 | if next(cursor, context, &mut crc)? != expected { |
| 193 | return Err(Failure::Header.into()); |
| 194 | } |
| 195 | } |
| 196 | let flags = next(cursor, context, &mut crc)?; |
| 197 | if flags & 0xe0 != 0 { |
| 198 | return Err(Failure::Header.into()); |
| 199 | } |
| 200 | for _ in 0..6 { |
| 201 | next(cursor, context, &mut crc)?; |
| 202 | } |
| 203 | if flags & 4 != 0 { |
| 204 | let low = next(cursor, context, &mut crc)?; |
| 205 | let high = next(cursor, context, &mut crc)?; |
| 206 | for _ in 0..u16::from_le_bytes([low, high]) { |
| 207 | next(cursor, context, &mut crc)?; |
| 208 | } |
| 209 | } |
| 210 | for mask in [8, 16] { |
| 211 | if flags & mask != 0 { |
| 212 | while next(cursor, context, &mut crc)? != 0 {} |
| 213 | } |
| 214 | } |
| 215 | if flags & 2 != 0 { |
| 216 | context.budget.metadata()?; |
| 217 | let low = cursor.byte(context, Stage::Header)?; |
| 218 | context.budget.metadata()?; |
| 219 | let high = cursor.byte(context, Stage::Header)?; |
| 220 | if u16::from_le_bytes([low, high]) != crc as u16 { |
| 221 | return Err(Failure::Header.into()); |
| 222 | } |
| 223 | } |
| 224 | Ok(cursor.position) |
| 225 | } |
| 226 | |
| 227 | fn decode<E, F: FnMut(Checkpoint) -> Result<(), Stop<E>>>( |
| 228 | decoder: &mut Inflate, |
| 229 | cursor: &mut Cursor<'_>, |
| 230 | context: &mut Context<'_, F>, |
| 231 | header_bytes: usize, |
| 232 | bytes: &mut Option<Vec<u8>>, |
| 233 | ) -> Result<Boundary, Error<E>> { |
| 234 | let mut output = [0; CHUNK_SIZE]; |
| 235 | let mut consumed_position = header_bytes; |
| 236 | let mut offered_end = header_bytes; |
| 237 | let mut crc = 0; |
| 238 | loop { |
| 239 | context.check(Stage::BeforeInflate)?; |
| 240 | if consumed_position == offered_end && offered_end < cursor.input.len() { |
| 241 | offered_end = offered_end |
| 242 | .checked_add(CHUNK_SIZE) |
| 243 | .ok_or(Failure::Boundary)? |
| 244 | .min(cursor.input.len()); |
| 245 | cursor.account(offered_end, context.budget)?; |
| 246 | cursor.position = offered_end; |
| 247 | } |
| 248 | let before_in = decoder.total_in(); |
| 249 | let before_out = decoder.total_out(); |
| 250 | let result = decoder.decompress( |
| 251 | &cursor.input[consumed_position..offered_end], |
| 252 | &mut output, |
| 253 | InflateFlush::NoFlush, |
| 254 | ); |
| 255 | // backend 오류보다 실제 출력 증가분 검증과 과금을 먼저 수행함. |
| 256 | let produced = decoder |
| 257 | .total_out() |
| 258 | .checked_sub(before_out) |
| 259 | .ok_or(Failure::Boundary)?; |
| 260 | context.budget.decoded(produced)?; |
| 261 | let status = result.map_err(Error::Backend)?; |
| 262 | context.check(Stage::AfterInflate)?; |
| 263 | let consumed = decoder |
| 264 | .total_in() |
| 265 | .checked_sub(before_in) |
| 266 | .ok_or(Failure::Boundary)?; |
| 267 | let consumed = usize::try_from(consumed).map_err(|_| Failure::Boundary)?; |
| 268 | if consumed > offered_end - consumed_position { |
| 269 | return Err(Failure::Boundary.into()); |
| 270 | } |
| 271 | consumed_position = consumed_position |
| 272 | .checked_add(consumed) |
| 273 | .ok_or(Failure::Boundary)?; |
| 274 | if decoder.total_in() != (consumed_position - header_bytes) as u64 { |
| 275 | return Err(Failure::Boundary.into()); |
| 276 | } |
| 277 | let produced = produced as usize; |
| 278 | if produced != 0 { |
| 279 | crc = crc32(crc, &output[..produced]); |
| 280 | if let Some(saved) = bytes { |
| 281 | context.budget.output(produced)?; |
| 282 | saved |
| 283 | .try_reserve_exact(produced) |
| 284 | .map_err(|_| Failure::Allocation)?; |
| 285 | saved.extend_from_slice(&output[..produced]); |
| 286 | context.check(Stage::AfterOutput)?; |
| 287 | } |
| 288 | } |
| 289 | if status == Status::StreamEnd { |
| 290 | break; |
| 291 | } |
| 292 | if consumed == 0 && produced == 0 { |
| 293 | return Err(if consumed_position == cursor.input.len() { |
| 294 | Failure::Truncated |
| 295 | } else { |
| 296 | Failure::NoProgress |
| 297 | } |
| 298 | .into()); |
| 299 | } |
| 300 | } |
| 301 | context.check(Stage::Trailer)?; |
| 302 | let read_ahead_bytes = offered_end |
| 303 | .checked_sub(consumed_position) |
| 304 | .ok_or(Failure::Boundary)?; |
| 305 | cursor.position = consumed_position; |
| 306 | let mut trailer = [0; 8]; |
| 307 | for byte in &mut trailer { |
| 308 | *byte = cursor.byte(context, Stage::Trailer)?; |
| 309 | } |
| 310 | let expected_crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]); |
| 311 | let expected_size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]); |
| 312 | if expected_crc != crc { |
| 313 | return Err(Failure::Crc.into()); |
| 314 | } |
| 315 | if expected_size != decoder.total_out() as u32 { |
| 316 | return Err(Failure::Size.into()); |
| 317 | } |
| 318 | if cursor.position != cursor.input.len() { |
| 319 | return Err(Failure::TrailingData.into()); |
| 320 | } |
| 321 | context.check(Stage::Trailer)?; |
| 322 | Ok(Boundary { |
| 323 | header_bytes, |
| 324 | deflate_bytes: decoder.total_in(), |
| 325 | read_ahead_bytes, |
| 326 | inflated_bytes: decoder.total_out(), |
| 327 | crc32: crc, |
| 328 | member_bytes: cursor.position, |
| 329 | offered_bytes: (offered_end - header_bytes) as u64, |
| 330 | }) |
| 331 | } |