team-ljyzipelo

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