team-ljyzipelo

공개
237줄7.4 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
148// 역방향 인덱스 검사는 디코더의 할당과 실제 해제량 검사보다 먼저 수행함.
149fn xz_layout(source: &mut File, limit: u64, check: &mut impl FnMut() -> Result<()>) -> Result<u64> {
150 use zlib_rs::crc32::crc32;
151 let mut end = source.metadata().map_err(space::io_error)?.len();
152 let mut total = 0u64;
153 let mut streams = 0usize;
154 while end != 0 {
155 let mut tail = [0; 4];
156 loop {
157 let at = end.checked_sub(4).ok_or(ErrorCode::Integrity)?;
158 read_at(source, at, &mut tail, check)?;
159 if tail != [0; 4] {
160 break;
161 }
162 end = at;
163 }
164 streams += 1;
165 if streams > crate::archive::MAX_OUTPUT_NODES {
166 return Err(ErrorCode::Limit);
167 }
168 let footer_at = end.checked_sub(12).ok_or(ErrorCode::Integrity)?;
169 let mut footer = [0; 12];
170 read_at(source, footer_at, &mut footer, check)?;
171 if &footer[10..] != b"YZ"
172 || crc32(0, &footer[4..10]) != u32::from_le_bytes(footer[..4].try_into().unwrap())
173 {
174 return Err(ErrorCode::Integrity);
175 }
176 let index_len = (u64::from(u32::from_le_bytes(footer[4..8].try_into().unwrap())) + 1) * 4;
177 if index_len > crate::archive::MAX_METADATA_BYTES as u64 {
178 return Err(ErrorCode::Limit);
179 }
180 if index_len < 8 {
181 return Err(ErrorCode::Integrity);
182 }
183 let index_at = footer_at
184 .checked_sub(index_len)
185 .ok_or(ErrorCode::Integrity)?;
186 let mut index = vec![0; index_len as usize];
187 read_at(source, index_at, &mut index, check)?;
188 let data_end = index.len() - 4;
189 if index[0] != 0
190 || crc32(0, &index[..data_end])
191 != u32::from_le_bytes(index[data_end..].try_into().unwrap())
192 {
193 return Err(ErrorCode::Integrity);
194 }
195 let mut cursor = 1;
196 let count = vli(&index[..data_end], &mut cursor)?;
197 if count > crate::archive::MAX_OUTPUT_NODES as u64 {
198 return Err(ErrorCode::Limit);
199 }
200 let mut blocks = 0u64;
201 for _ in 0..count {
202 check()?;
203 let unpadded = vli(&index[..data_end], &mut cursor)?;
204 let size = vli(&index[..data_end], &mut cursor)?;
205 if unpadded == 0 {
206 return Err(ErrorCode::Integrity);
207 }
208 blocks = blocks
209 .checked_add(unpadded.checked_add(3).ok_or(ErrorCode::Integrity)? & !3)
210 .ok_or(ErrorCode::Integrity)?;
211 total = total
212 .checked_add(size)
213 .filter(|total| *total <= limit)
214 .ok_or(ErrorCode::Limit)?;
215 }
216 if data_end - cursor > 3 || index[cursor..data_end].iter().any(|byte| *byte != 0) {
217 return Err(ErrorCode::Integrity);
218 }
219 let start = index_at
220 .checked_sub(blocks)
221 .and_then(|at| at.checked_sub(12))
222 .ok_or(ErrorCode::Integrity)?;
223 let mut header = [0; 12];
224 read_at(source, start, &mut header, check)?;
225 if &header[..6] != b"\xfd7zXZ\0"
226 || header[6..8] != footer[8..10]
227 || crc32(0, &header[6..8]) != u32::from_le_bytes(header[8..].try_into().unwrap())
228 {
229 return Err(ErrorCode::Integrity);
230 }
231 end = start;
232 }
233 if streams == 0 {
234 return Err(ErrorCode::Integrity);
235 }
236 Ok(total)
237}