team-ljyzipelo

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