team-ljyzipelo

공개
408줄13 KB
1use crate::{
2 protocol::{ErrorCode, ResourceUsage},
3 space, spool,
4};
5use std::{
6 cell::RefCell,
7 fs::File,
8 io::{self, BufReader, Read, Seek, Write},
9};
10use zeroize::Zeroizing;
11
12type Result<T> = std::result::Result<T, ErrorCode>;
13const CHUNK: usize = 65_536;
14const XZ_MEMORY_KIB: u32 = 32 * 1024;
15
16#[derive(Clone, Copy)]
17pub(crate) enum Compression {
18 Bzip2,
19 Xz,
20}
21
22#[derive(Debug)]
23struct InputError(ErrorCode);
24
25impl std::fmt::Display for InputError {
26 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 write!(formatter, "{:?}", self.0)
28 }
29}
30
31impl std::error::Error for InputError {}
32
33struct CheckedInput<'a, F> {
34 file: &'a mut File,
35 check: &'a RefCell<&'a mut F>,
36}
37
38impl<F: crate::resources::Monitor> Read for CheckedInput<'_, F> {
39 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
40 self.check
41 .borrow_mut()
42 .check()
43 .map_err(|error| io::Error::other(InputError(error)))?;
44 let count = buffer.len().min(CHUNK);
45 let n = self
46 .file
47 .read(&mut buffer[..count])
48 .map_err(|_| io::Error::other(InputError(ErrorCode::Io)))?;
49 if n != 0 {
50 self.check
51 .borrow_mut()
52 .activity()
53 .map_err(|e| io::Error::other(InputError(e)))?;
54 }
55 Ok(n)
56 }
57}
58
59fn decode_error(error: io::Error) -> ErrorCode {
60 if let Some(error) = error
61 .get_ref()
62 .and_then(|error| error.downcast_ref::<InputError>())
63 {
64 return error.0;
65 }
66 match error.kind() {
67 io::ErrorKind::OutOfMemory => ErrorCode::Limit,
68 io::ErrorKind::Unsupported => ErrorCode::UnsupportedFeature,
69 _ => ErrorCode::Integrity,
70 }
71}
72
73pub(crate) fn decode(
74 source: &mut File,
75 compression: Compression,
76 limit: u64,
77 check: &mut impl crate::resources::Monitor,
78) -> Result<(File, u64)> {
79 check.check()?;
80 let expected = if matches!(compression, Compression::Xz) {
81 Some(xz_layout(source, limit, check)?)
82 } else {
83 None
84 };
85 let packed_length = source.metadata().map_err(space::io_error)?.len();
86 if let Some(expected) = expected {
87 check.observe(
88 ResourceUsage {
89 estimated_bytes: Some(expected),
90 compressed_bytes: Some(packed_length),
91 ratio_output_bytes: Some(expected),
92 ..ResourceUsage::default()
93 },
94 Some(source),
95 )?;
96 }
97 source.rewind().map_err(space::io_error)?;
98 let mut output = spool::temporary()?;
99 let check = RefCell::new(check);
100 let input = CheckedInput {
101 file: source,
102 check: &check,
103 };
104 let mut reader: Box<dyn Read + '_> = match compression {
105 Compression::Bzip2 => Box::new(bzip2::bufread::MultiBzDecoder::new(
106 BufReader::with_capacity(CHUNK, input),
107 )),
108 Compression::Xz => Box::new(lzma_rust2::XzReader::new_mem_limit(
109 input,
110 true,
111 XZ_MEMORY_KIB,
112 )),
113 };
114 let mut buffer = Zeroizing::new([0; CHUNK]);
115 let mut total = 0u64;
116 loop {
117 check.borrow_mut().check()?;
118 let count = reader.read(&mut buffer[..]).map_err(decode_error)?;
119 if count == 0 {
120 break;
121 }
122 total = total
123 .checked_add(count as u64)
124 .filter(|total| *total <= limit)
125 .ok_or(ErrorCode::Limit)?;
126 check.borrow_mut().observe(
127 ResourceUsage {
128 actual_bytes: Some(total),
129 compressed_bytes: Some(packed_length),
130 ratio_output_bytes: Some(total),
131 ..ResourceUsage::default()
132 },
133 Some(&output),
134 )?;
135 check.borrow_mut().activity()?;
136 // 전체 검증 전에는 비공개 임시 파일에만 기록함.
137 space::ensure(&output, count as u64)?;
138 output
139 .write_all(&buffer[..count])
140 .map_err(space::io_error)?;
141 }
142 check.borrow_mut().check()?;
143 if expected.is_some_and(|expected| expected != total) {
144 return Err(ErrorCode::Integrity);
145 }
146 Ok((output, total))
147}
148
149fn read_at(
150 source: &mut File,
151 offset: u64,
152 bytes: &mut [u8],
153 check: &mut impl crate::resources::Monitor,
154) -> Result<()> {
155 check.check()?;
156 source
157 .seek(std::io::SeekFrom::Start(offset))
158 .map_err(space::io_error)?;
159 source.read_exact(bytes).map_err(|error| {
160 if error.kind() == io::ErrorKind::UnexpectedEof {
161 ErrorCode::Integrity
162 } else {
163 ErrorCode::Io
164 }
165 })?;
166 check.activity()
167}
168
169fn vli(bytes: &[u8], cursor: &mut usize) -> Result<u64> {
170 let mut value = 0u64;
171 for shift in (0..63).step_by(7) {
172 let byte = *bytes.get(*cursor).ok_or(ErrorCode::Integrity)?;
173 *cursor += 1;
174 value |= u64::from(byte & 127) << shift;
175 if byte & 128 == 0 {
176 if shift != 0 && byte == 0 {
177 return Err(ErrorCode::Integrity);
178 }
179 return Ok(value);
180 }
181 }
182 Err(ErrorCode::Integrity)
183}
184
185fn lzma2_size(
186 source: &mut File,
187 mut at: u64,
188 end: u64,
189 expected: u64,
190 check: &mut impl crate::resources::Monitor,
191) -> Result<()> {
192 let mut size = 0u64;
193 while at < end {
194 let mut control = [0];
195 read_at(source, at, &mut control, check)?;
196 at += 1;
197 if control[0] == 0 {
198 return if at == end && size == expected {
199 Ok(())
200 } else {
201 Err(ErrorCode::Integrity)
202 };
203 }
204 let header_len = match control[0] {
205 1 | 2 => 2,
206 128..=255 => 4 + usize::from(control[0] >= 192),
207 _ => return Err(ErrorCode::Integrity),
208 };
209 if end - at < header_len as u64 {
210 return Err(ErrorCode::Integrity);
211 }
212 let mut header = [0; 5];
213 read_at(source, at, &mut header[..header_len], check)?;
214 at += header_len as u64;
215 let unpacked = u64::from(u16::from_be_bytes(header[..2].try_into().unwrap())) + 1;
216 let (packed, unpacked) = if control[0] >= 128 {
217 (
218 u64::from(u16::from_be_bytes(header[2..4].try_into().unwrap())) + 1,
219 (u64::from(control[0] & 31) << 16) + unpacked,
220 )
221 } else {
222 (unpacked, unpacked)
223 };
224 at = at
225 .checked_add(packed)
226 .filter(|at| *at <= end)
227 .ok_or(ErrorCode::Integrity)?;
228 size = size
229 .checked_add(unpacked)
230 .filter(|size| *size <= expected)
231 .ok_or(ErrorCode::Integrity)?;
232 }
233 Err(ErrorCode::Integrity)
234}
235
236fn xz_block(
237 source: &mut File,
238 start: u64,
239 unpadded: u64,
240 size: u64,
241 check_size: u64,
242 check: &mut impl crate::resources::Monitor,
243) -> Result<()> {
244 let mut header = [0; 1024];
245 read_at(source, start, &mut header[..1], check)?;
246 if header[0] == 0 {
247 return Err(ErrorCode::Integrity);
248 }
249 let header_len = (usize::from(header[0]) + 1) * 4;
250 let packed = unpadded
251 .checked_sub(header_len as u64 + check_size)
252 .filter(|packed| *packed != 0)
253 .ok_or(ErrorCode::Integrity)?;
254 read_at(source, start, &mut header[..header_len], check)?;
255 let data = &header[..header_len - 4];
256 if zlib_rs::crc32::crc32(0, data)
257 != u32::from_le_bytes(header[header_len - 4..header_len].try_into().unwrap())
258 {
259 return Err(ErrorCode::Integrity);
260 }
261 let flags = header[1];
262 if flags & 0x3c != 0 {
263 return Err(ErrorCode::UnsupportedFeature);
264 }
265 let mut cursor = 2;
266 if flags & 0x40 != 0 && vli(data, &mut cursor)? != packed {
267 return Err(ErrorCode::Integrity);
268 }
269 if flags & 0x80 != 0 && vli(data, &mut cursor)? != size {
270 return Err(ErrorCode::Integrity);
271 }
272 let filters = usize::from(flags & 3) + 1;
273 for number in 0..filters {
274 let id = vli(data, &mut cursor)?;
275 // 지원 필터는 길이를 보존하며 마지막 필터는 LZMA2임.
276 let supported = if number + 1 == filters {
277 id == 0x21
278 } else {
279 (0x03..=0x0b).contains(&id)
280 };
281 if !supported {
282 return Err(ErrorCode::UnsupportedFeature);
283 }
284 let properties = vli(data, &mut cursor)?;
285 cursor = cursor
286 .checked_add(usize::try_from(properties).map_err(|_| ErrorCode::Integrity)?)
287 .filter(|cursor| *cursor <= data.len())
288 .ok_or(ErrorCode::Integrity)?;
289 }
290 if data[cursor..].iter().any(|byte| *byte != 0) {
291 return Err(ErrorCode::Integrity);
292 }
293 let data_start = start
294 .checked_add(header_len as u64)
295 .ok_or(ErrorCode::Integrity)?;
296 let data_end = data_start.checked_add(packed).ok_or(ErrorCode::Integrity)?;
297 // 청크 경계와 해제량을 블록별로 대조한 뒤 기존 디코더가 내용과 체크섬을 검증함.
298 lzma2_size(source, data_start, data_end, size, check)
299}
300
301// 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함.
302fn xz_layout(
303 source: &mut File,
304 limit: u64,
305 check: &mut impl crate::resources::Monitor,
306) -> Result<u64> {
307 use zlib_rs::crc32::crc32;
308 let mut end = source.metadata().map_err(space::io_error)?.len();
309 let mut total = 0u64;
310 let mut streams = 0usize;
311 while end != 0 {
312 let mut tail = [0; 4];
313 loop {
314 let at = end.checked_sub(4).ok_or(ErrorCode::Integrity)?;
315 read_at(source, at, &mut tail, check)?;
316 if tail != [0; 4] {
317 break;
318 }
319 end = at;
320 }
321 streams += 1;
322 if streams > check.metadata_limits().nodes {
323 return Err(ErrorCode::Limit);
324 }
325 let footer_at = end.checked_sub(12).ok_or(ErrorCode::Integrity)?;
326 let mut footer = [0; 12];
327 read_at(source, footer_at, &mut footer, check)?;
328 if &footer[10..] != b"YZ"
329 || crc32(0, &footer[4..10]) != u32::from_le_bytes(footer[..4].try_into().unwrap())
330 {
331 return Err(ErrorCode::Integrity);
332 }
333 let index_len = (u64::from(u32::from_le_bytes(footer[4..8].try_into().unwrap())) + 1) * 4;
334 if index_len > check.metadata_limits().bytes as u64 {
335 return Err(ErrorCode::Limit);
336 }
337 if index_len < 8 {
338 return Err(ErrorCode::Integrity);
339 }
340 let index_at = footer_at
341 .checked_sub(index_len)
342 .ok_or(ErrorCode::Integrity)?;
343 let mut index = vec![0; index_len as usize];
344 read_at(source, index_at, &mut index, check)?;
345 let data_end = index.len() - 4;
346 if index[0] != 0
347 || crc32(0, &index[..data_end])
348 != u32::from_le_bytes(index[data_end..].try_into().unwrap())
349 {
350 return Err(ErrorCode::Integrity);
351 }
352 let mut cursor = 1;
353 let count = vli(&index[..data_end], &mut cursor)?;
354 if count > check.metadata_limits().nodes as u64 {
355 return Err(ErrorCode::Limit);
356 }
357 let mut blocks = 0u64;
358 let mut records = Vec::new();
359 for _ in 0..count {
360 check.check()?;
361 let unpadded = vli(&index[..data_end], &mut cursor)?;
362 let size = vli(&index[..data_end], &mut cursor)?;
363 if unpadded == 0 {
364 return Err(ErrorCode::Integrity);
365 }
366 blocks = blocks
367 .checked_add(unpadded.checked_add(3).ok_or(ErrorCode::Integrity)? & !3)
368 .ok_or(ErrorCode::Integrity)?;
369 total = total
370 .checked_add(size)
371 .filter(|total| *total <= limit)
372 .ok_or(ErrorCode::Limit)?;
373 records.push((unpadded, size));
374 }
375 if data_end - cursor > 3 || index[cursor..data_end].iter().any(|byte| *byte != 0) {
376 return Err(ErrorCode::Integrity);
377 }
378 let start = index_at
379 .checked_sub(blocks)
380 .and_then(|at| at.checked_sub(12))
381 .ok_or(ErrorCode::Integrity)?;
382 let mut header = [0; 12];
383 read_at(source, start, &mut header, check)?;
384 if &header[..6] != b"\xfd7zXZ\0"
385 || header[6..8] != footer[8..10]
386 || crc32(0, &header[6..8]) != u32::from_le_bytes(header[8..].try_into().unwrap())
387 {
388 return Err(ErrorCode::Integrity);
389 }
390 let check_size = match header[7] {
391 0 => 0,
392 1 => 4,
393 4 => 8,
394 10 => 32,
395 _ => return Err(ErrorCode::UnsupportedFeature),
396 };
397 let mut block_at = start + 12;
398 for (unpadded, size) in records {
399 xz_block(source, block_at, unpadded, size, check_size, check)?;
400 block_at += (unpadded + 3) & !3;
401 }
402 end = start;
403 }
404 if streams == 0 {
405 return Err(ErrorCode::Integrity);
406 }
407 Ok(total)
408}