| 1 | use std::{ |
| 2 | cell::{Cell, RefCell}, |
| 3 | fmt, |
| 4 | io::Write, |
| 5 | time::{Duration, Instant}, |
| 6 | }; |
| 7 | |
| 8 | use zip::{CompressionMethod, DateTime, ZipWriter, result::ZipError, write::SimpleFileOptions}; |
| 9 | |
| 10 | mod storage; |
| 11 | |
| 12 | pub const MAX_BYTES: u64 = 16 * 1024 * 1024; |
| 13 | pub const MAX_INPUTS: usize = 1024; |
| 14 | pub const MAX_NAME_BYTES: usize = 1024; |
| 15 | pub const CHUNK: usize = 65_536; |
| 16 | pub const MAX_DURATION: Duration = Duration::from_secs(300); |
| 17 | |
| 18 | #[derive(Debug)] |
| 19 | pub struct Entry { |
| 20 | pub name: String, |
| 21 | pub bytes: Box<[u8]>, |
| 22 | } |
| 23 | |
| 24 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| 25 | pub enum Method { |
| 26 | Stored, |
| 27 | #[default] |
| 28 | Deflate, |
| 29 | } |
| 30 | |
| 31 | #[derive(Clone, Copy, Debug, Default)] |
| 32 | pub struct Options { |
| 33 | pub method: Method, |
| 34 | pub encrypted: bool, |
| 35 | pub split: bool, |
| 36 | pub zip64: bool, |
| 37 | } |
| 38 | |
| 39 | #[derive(Clone, Copy, Debug)] |
| 40 | pub struct Limits { |
| 41 | pub input: u64, |
| 42 | pub output: u64, |
| 43 | pub entries: usize, |
| 44 | pub processed: u64, |
| 45 | } |
| 46 | |
| 47 | impl Default for Limits { |
| 48 | fn default() -> Self { |
| 49 | Self { |
| 50 | input: MAX_BYTES, |
| 51 | output: MAX_BYTES, |
| 52 | entries: MAX_INPUTS + 1, |
| 53 | processed: 2 * MAX_BYTES, |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | #[derive(Debug)] |
| 59 | pub struct Request { |
| 60 | pub entries: Vec<Entry>, |
| 61 | pub options: Options, |
| 62 | pub limits: Limits, |
| 63 | pub timeout: Duration, |
| 64 | } |
| 65 | |
| 66 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 67 | pub enum Stop { |
| 68 | Cancelled, |
| 69 | Deadline, |
| 70 | } |
| 71 | |
| 72 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 73 | pub enum Failure { |
| 74 | InvalidRequest, |
| 75 | Unsupported, |
| 76 | UnsafeName, |
| 77 | Conflict, |
| 78 | Budget, |
| 79 | Cancelled, |
| 80 | Deadline, |
| 81 | Allocation, |
| 82 | Engine, |
| 83 | } |
| 84 | |
| 85 | impl fmt::Display for Failure { |
| 86 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 87 | write!(f, "{self:?}") |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | impl std::error::Error for Failure {} |
| 92 | |
| 93 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 94 | pub enum Checkpoint { |
| 95 | Start, |
| 96 | Validate { |
| 97 | index: usize, |
| 98 | }, |
| 99 | Entry { |
| 100 | index: usize, |
| 101 | }, |
| 102 | Input { |
| 103 | index: usize, |
| 104 | offset: usize, |
| 105 | len: usize, |
| 106 | }, |
| 107 | Write { |
| 108 | offset: u64, |
| 109 | len: usize, |
| 110 | extent: u64, |
| 111 | }, |
| 112 | Seek { |
| 113 | from: u64, |
| 114 | to: u64, |
| 115 | }, |
| 116 | Flush, |
| 117 | Finish, |
| 118 | Return, |
| 119 | } |
| 120 | |
| 121 | pub(crate) struct Gate<C> { |
| 122 | control: RefCell<C>, |
| 123 | deadline: Instant, |
| 124 | first: Cell<Option<Failure>>, |
| 125 | } |
| 126 | |
| 127 | impl<C: FnMut(Checkpoint) -> Result<(), Stop>> Gate<C> { |
| 128 | pub(crate) fn fail(&self, failure: Failure) -> Failure { |
| 129 | match self.first.get() { |
| 130 | Some(first) => first, |
| 131 | None => { |
| 132 | self.first.set(Some(failure)); |
| 133 | failure |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub(crate) fn check(&self, point: Checkpoint) -> Result<(), Failure> { |
| 139 | if let Some(first) = self.first.get() { |
| 140 | return Err(first); |
| 141 | } |
| 142 | if Instant::now() >= self.deadline { |
| 143 | return Err(self.fail(Failure::Deadline)); |
| 144 | } |
| 145 | if let Err(stop) = (self.control.borrow_mut())(point) { |
| 146 | return Err(self.fail(match stop { |
| 147 | Stop::Cancelled => Failure::Cancelled, |
| 148 | Stop::Deadline => Failure::Deadline, |
| 149 | })); |
| 150 | } |
| 151 | if Instant::now() >= self.deadline { |
| 152 | return Err(self.fail(Failure::Deadline)); |
| 153 | } |
| 154 | Ok(()) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | // 파일 접근 없이 이전 OS 정책의 공통 ASCII 범위만 허용함. |
| 159 | fn validate_name(name: &str) -> Result<(), Failure> { |
| 160 | if name.is_empty() || name.len() > MAX_NAME_BYTES || !name.is_ascii() { |
| 161 | return Err(Failure::UnsafeName); |
| 162 | } |
| 163 | for segment in name.split('/') { |
| 164 | if segment.is_empty() |
| 165 | || segment.len() > 255 |
| 166 | || segment == "." |
| 167 | || segment == ".." |
| 168 | || segment.ends_with([' ', '.']) |
| 169 | || segment.bytes().all(|b| b == b' ') |
| 170 | || segment |
| 171 | .bytes() |
| 172 | .any(|b| b < 32 || b == 127 || b"\\<>:\"|?*".contains(&b)) |
| 173 | { |
| 174 | return Err(Failure::UnsafeName); |
| 175 | } |
| 176 | let stem = segment |
| 177 | .split('.') |
| 178 | .next() |
| 179 | .unwrap_or("") |
| 180 | .trim_end_matches(' ') |
| 181 | .to_ascii_uppercase(); |
| 182 | if matches!( |
| 183 | stem.as_str(), |
| 184 | "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" |
| 185 | ) || (stem.len() == 4 |
| 186 | && (stem.starts_with("COM") || stem.starts_with("LPT")) |
| 187 | && (b'1'..=b'9').contains(&stem.as_bytes()[3])) |
| 188 | { |
| 189 | return Err(Failure::UnsafeName); |
| 190 | } |
| 191 | } |
| 192 | Ok(()) |
| 193 | } |
| 194 | |
| 195 | fn io_failure(error: std::io::Error) -> Failure { |
| 196 | error |
| 197 | .get_ref() |
| 198 | .and_then(|e| e.downcast_ref::<Failure>()) |
| 199 | .copied() |
| 200 | .unwrap_or(Failure::Engine) |
| 201 | } |
| 202 | |
| 203 | fn zip_failure(error: ZipError) -> Failure { |
| 204 | match error { |
| 205 | ZipError::Io(error) => io_failure(error), |
| 206 | _ => Failure::Engine, |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | // 소유권을 받은 메모리만 읽음. 성공 전 ZIP bytes를 외부에 노출하지 않음. |
| 211 | pub fn create<C>(request: Request, control: C) -> Result<Vec<u8>, Failure> |
| 212 | where |
| 213 | C: FnMut(Checkpoint) -> Result<(), Stop>, |
| 214 | { |
| 215 | if request.timeout.is_zero() || request.timeout > MAX_DURATION { |
| 216 | return Err(Failure::InvalidRequest); |
| 217 | } |
| 218 | let deadline = Instant::now() |
| 219 | .checked_add(request.timeout) |
| 220 | .ok_or(Failure::InvalidRequest)?; |
| 221 | let gate = Gate { |
| 222 | control: RefCell::new(control), |
| 223 | deadline, |
| 224 | first: Cell::new(None), |
| 225 | }; |
| 226 | gate.check(Checkpoint::Start)?; |
| 227 | if request.options.encrypted || request.options.split || request.options.zip64 { |
| 228 | return Err(gate.fail(Failure::Unsupported)); |
| 229 | } |
| 230 | if request.entries.is_empty() { |
| 231 | return Err(gate.fail(Failure::InvalidRequest)); |
| 232 | } |
| 233 | let count = request.entries.len(); |
| 234 | let limits = Limits { |
| 235 | input: request.limits.input.min(MAX_BYTES), |
| 236 | output: request.limits.output.min(MAX_BYTES), |
| 237 | entries: request.limits.entries.min(MAX_INPUTS + 1), |
| 238 | processed: request.limits.processed.min(2 * MAX_BYTES), |
| 239 | }; |
| 240 | if count > MAX_INPUTS || count.checked_add(1).ok_or(Failure::Budget)? > limits.entries { |
| 241 | return Err(gate.fail(Failure::Budget)); |
| 242 | } |
| 243 | let mut input = 0u64; |
| 244 | for (index, entry) in request.entries.iter().enumerate() { |
| 245 | gate.check(Checkpoint::Validate { index })?; |
| 246 | validate_name(&entry.name).map_err(|e| gate.fail(e))?; |
| 247 | input = input |
| 248 | .checked_add(entry.bytes.len() as u64) |
| 249 | .ok_or(Failure::Budget)?; |
| 250 | if input > limits.input || input > limits.processed { |
| 251 | return Err(gate.fail(Failure::Budget)); |
| 252 | } |
| 253 | for prior in &request.entries[..index] { |
| 254 | let a = prior.name.as_bytes(); |
| 255 | let b = entry.name.as_bytes(); |
| 256 | let n = a.len().min(b.len()); |
| 257 | if a[..n].eq_ignore_ascii_case(&b[..n]) |
| 258 | && (a.len() == b.len() || a.get(n) == Some(&b'/') || b.get(n) == Some(&b'/')) |
| 259 | { |
| 260 | return Err(gate.fail(Failure::Conflict)); |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | let mut output = storage::Bounded::new(&gate, limits.output, limits.processed, input); |
| 265 | let mut writer = ZipWriter::new(&mut output); |
| 266 | let method = match request.options.method { |
| 267 | Method::Stored => CompressionMethod::Stored, |
| 268 | Method::Deflate => CompressionMethod::Deflated, |
| 269 | }; |
| 270 | let options = SimpleFileOptions::default() |
| 271 | .compression_method(method) |
| 272 | .compression_level(if request.options.method == Method::Deflate { |
| 273 | Some(6) |
| 274 | } else { |
| 275 | None |
| 276 | }) |
| 277 | .large_file(false) |
| 278 | .last_modified_time(DateTime::DEFAULT) |
| 279 | .unix_permissions(0o644); |
| 280 | let writing = (|| -> Result<(), Failure> { |
| 281 | for (index, entry) in request.entries.iter().enumerate() { |
| 282 | gate.check(Checkpoint::Entry { index })?; |
| 283 | writer |
| 284 | .start_file(&entry.name, options) |
| 285 | .map_err(zip_failure)?; |
| 286 | for (part, bytes) in entry.bytes.chunks(CHUNK).enumerate() { |
| 287 | gate.check(Checkpoint::Input { |
| 288 | index, |
| 289 | offset: part * CHUNK, |
| 290 | len: bytes.len(), |
| 291 | })?; |
| 292 | writer.write_all(bytes).map_err(io_failure)?; |
| 293 | } |
| 294 | } |
| 295 | gate.check(Checkpoint::Finish) |
| 296 | })(); |
| 297 | if let Err(error) = writing { |
| 298 | let first = gate.fail(error); |
| 299 | drop(writer); |
| 300 | return Err(first); |
| 301 | } |
| 302 | // finish 내부 Drop의 뒤늦은 정리 오류 대신 원래 반환 오류를 보존함. |
| 303 | if let Err(error) = writer.finish() { |
| 304 | return Err(zip_failure(error)); |
| 305 | } |
| 306 | gate.check(Checkpoint::Return)?; |
| 307 | Ok(output.into_bytes()) |
| 308 | } |