team-ljyzipelo

공개
348줄12 KB
1use crate::{protocol::*, resources::Monitor};
2use std::io::{self, BufRead, Cursor, Read, Seek, SeekFrom};
3use zlib_rs::crc32::crc32;
4use zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
5
6type Result<T> = std::result::Result<T, ErrorCode>;
7
8#[derive(Clone, Copy)]
9pub(crate) enum Kind {
10 Text,
11 Png,
12 Jpeg,
13}
14impl Kind {
15 pub fn from_name(name: &str) -> Result<Self> {
16 match name
17 .rsplit_once('.')
18 .map(|(_, ext)| ext.to_ascii_lowercase())
19 .as_deref()
20 {
21 Some("txt" | "md" | "log" | "csv" | "json") => Ok(Self::Text),
22 Some("png") => Ok(Self::Png),
23 Some("jpg" | "jpeg") => Ok(Self::Jpeg),
24 _ => Err(ErrorCode::UnsupportedFeature),
25 }
26 }
27 pub fn limit(self) -> u64 {
28 match self {
29 Self::Text => MAX_PREVIEW_TEXT_BYTES,
30 Self::Png | Self::Jpeg => MAX_PREVIEW_IMAGE_BYTES,
31 }
32 }
33}
34fn rgba_info(entry_id: u32, width: u32, height: u32) -> Result<PreviewInfo> {
35 if width == 0 || height == 0 {
36 return Err(ErrorCode::Integrity);
37 }
38 let total_bytes = u64::from(width)
39 .checked_mul(u64::from(height))
40 .and_then(|n| n.checked_mul(4))
41 .ok_or(ErrorCode::Limit)?;
42 let info = PreviewInfo {
43 entry_id,
44 format: PreviewFormat::Rgba8,
45 total_bytes,
46 width,
47 height,
48 };
49 if !info.valid() {
50 return Err(ErrorCode::Limit);
51 }
52 Ok(info)
53}
54fn buffer(length: usize) -> Result<Vec<u8>> {
55 let mut bytes = Vec::new();
56 bytes
57 .try_reserve_exact(length)
58 .map_err(|_| ErrorCode::Limit)?;
59 bytes.resize(length, 0);
60 Ok(bytes)
61}
62pub(crate) fn decode(
63 kind: Kind,
64 entry_id: u32,
65 mut source: Vec<u8>,
66 check: &mut impl Monitor,
67) -> Result<(PreviewInfo, Vec<u8>)> {
68 check.check()?;
69 if source.len() as u64 > kind.limit() {
70 return Err(ErrorCode::Limit);
71 }
72 let result = match kind {
73 Kind::Text => {
74 std::str::from_utf8(&source).map_err(|_| ErrorCode::Integrity)?;
75 if source.starts_with(&[0xef, 0xbb, 0xbf]) {
76 source.drain(..3);
77 }
78 Ok((
79 PreviewInfo {
80 entry_id,
81 format: PreviewFormat::Utf8Text,
82 total_bytes: source.len() as u64,
83 width: 0,
84 height: 0,
85 },
86 source,
87 ))
88 }
89 Kind::Png => png(entry_id, &source, check),
90 Kind::Jpeg => jpeg(entry_id, &source, check),
91 };
92 check.activity()?;
93 result
94}
95struct Input<'a, M> {
96 bytes: Cursor<&'a [u8]>,
97 check: &'a mut M,
98}
99impl<M: Monitor> Read for Input<'_, M> {
100 fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
101 self.check
102 .check()
103 .map_err(|_| io::Error::other("preview interrupted"))?;
104 let length = self.bytes.read(bytes)?;
105 if length != 0 {
106 self.check
107 .activity()
108 .map_err(|_| io::Error::other("preview interrupted"))?;
109 }
110 Ok(length)
111 }
112}
113impl<M: Monitor> BufRead for Input<'_, M> {
114 fn fill_buf(&mut self) -> io::Result<&[u8]> {
115 self.check
116 .check()
117 .map_err(|_| io::Error::other("preview interrupted"))?;
118 self.bytes.fill_buf()
119 }
120 fn consume(&mut self, length: usize) {
121 self.bytes.consume(length);
122 }
123}
124impl<M: Monitor> Seek for Input<'_, M> {
125 fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
126 self.check
127 .check()
128 .map_err(|_| io::Error::other("preview interrupted"))?;
129 self.bytes.seek(position)
130 }
131}
132fn png(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> {
133 if !source.starts_with(b"\x89PNG\r\n\x1a\n") {
134 return Err(ErrorCode::UnsupportedFormat);
135 }
136 let mut at = 8usize;
137 let mut ended = false;
138 while at < source.len() {
139 check.check()?;
140 let header = source.get(at..at + 8).ok_or(ErrorCode::Integrity)?;
141 let length = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize;
142 let end = at
143 .checked_add(12)
144 .and_then(|n| n.checked_add(length))
145 .filter(|n| *n <= source.len())
146 .ok_or(ErrorCode::Integrity)?;
147 if crc32(0, &source[at + 4..end - 4])
148 != u32::from_be_bytes(source[end - 4..end].try_into().unwrap())
149 {
150 return Err(ErrorCode::Integrity);
151 }
152 if at == 8 && (&header[4..] != b"IHDR" || length != 13) {
153 return Err(ErrorCode::Integrity);
154 }
155 if matches!(&header[4..], b"acTL" | b"fcTL" | b"fdAT") {
156 return Err(ErrorCode::UnsupportedFeature);
157 }
158 if &header[4..] == b"IEND" {
159 if length != 0 || end != source.len() {
160 return Err(ErrorCode::Integrity);
161 }
162 ended = true;
163 }
164 at = end;
165 check.activity()?;
166 }
167 if !ended {
168 return Err(ErrorCode::Integrity);
169 }
170 let mut decoder = png::Decoder::new_with_limits(
171 Input {
172 bytes: Cursor::new(source),
173 check,
174 },
175 png::Limits {
176 bytes: 128 * 1024 * 1024,
177 },
178 );
179 decoder.set_ignore_text_chunk(true);
180 decoder.set_ignore_iccp_chunk(true);
181 decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
182 let header = decoder
183 .read_header_info()
184 .map_err(|_| ErrorCode::Integrity)?;
185 let info = rgba_info(entry_id, header.width, header.height)?;
186 let mut reader = decoder.read_info().map_err(|_| ErrorCode::Integrity)?;
187 let length = reader
188 .output_buffer_size()
189 .filter(|n| *n as u64 <= info.total_bytes)
190 .ok_or(ErrorCode::Limit)?;
191 let mut raw = buffer(length)?;
192 let decoded = reader
193 .next_frame(&mut raw)
194 .map_err(|_| ErrorCode::Integrity)?;
195 reader.finish().map_err(|_| ErrorCode::Integrity)?;
196 drop(reader);
197 check.activity()?;
198 if decoded.width != info.width
199 || decoded.height != info.height
200 || decoded.bit_depth != png::BitDepth::Eight
201 {
202 return Err(ErrorCode::Integrity);
203 }
204 raw.truncate(decoded.buffer_size());
205 let channels = match decoded.color_type {
206 png::ColorType::Grayscale => 1,
207 png::ColorType::GrayscaleAlpha => 2,
208 png::ColorType::Rgb => 3,
209 png::ColorType::Rgba => 4,
210 _ => return Err(ErrorCode::UnsupportedFeature),
211 };
212 if raw.len() != info.width as usize * info.height as usize * channels {
213 return Err(ErrorCode::Integrity);
214 }
215 if channels == 4 {
216 return Ok((info, raw));
217 }
218 let mut rgba = buffer(info.total_bytes as usize)?;
219 for (source, target) in raw
220 .chunks_exact(info.width as usize * channels)
221 .zip(rgba.chunks_exact_mut(info.width as usize * 4))
222 {
223 check.activity()?;
224 for (pixel, out) in source
225 .chunks_exact(channels)
226 .zip(target.chunks_exact_mut(4))
227 {
228 match channels {
229 1 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], 255]),
230 2 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], pixel[1]]),
231 3 => out.copy_from_slice(&[pixel[0], pixel[1], pixel[2], 255]),
232 _ => unreachable!(),
233 }
234 }
235 }
236 Ok((info, rgba))
237}
238fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<PreviewInfo> {
239 let mut at = 2usize;
240 let mut scanning = false;
241 let mut info = None;
242 let mut seen_scan = false;
243 while at < source.len() {
244 check.check()?;
245 if scanning {
246 at += source[at..]
247 .iter()
248 .position(|byte| *byte == 0xff)
249 .ok_or(ErrorCode::Integrity)?;
250 }
251 if source[at] != 0xff {
252 return Err(ErrorCode::Integrity);
253 }
254 while source.get(at) == Some(&0xff) {
255 at += 1;
256 }
257 let marker = *source.get(at).ok_or(ErrorCode::Integrity)?;
258 at += 1;
259 match marker {
260 0 | 0xd0..=0xd7 if scanning => continue,
261 0xd9 if at == source.len() && seen_scan => return info.ok_or(ErrorCode::Integrity),
262 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity),
263 1 => continue,
264 _ => {}
265 }
266 let length = source.get(at..at + 2).ok_or(ErrorCode::Integrity)?;
267 let length = u16::from_be_bytes(length.try_into().unwrap()) as usize;
268 let end = at
269 .checked_add(length)
270 .filter(|n| length >= 2 && *n <= source.len())
271 .ok_or(ErrorCode::Integrity)?;
272 let body = &source[at + 2..end];
273 if matches!(marker, 0xc0..=0xcf) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) {
274 if info.is_some() || body.len() < 6 {
275 return Err(ErrorCode::Integrity);
276 }
277 if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 {
278 return Err(ErrorCode::UnsupportedFeature);
279 }
280 info = Some(rgba_info(
281 entry_id,
282 u32::from(u16::from_be_bytes(body[3..5].try_into().unwrap())),
283 u32::from(u16::from_be_bytes(body[1..3].try_into().unwrap())),
284 )?);
285 }
286 if marker == 0xe2 && body.starts_with(b"MPF\0") {
287 return Err(ErrorCode::UnsupportedFeature);
288 }
289 scanning = marker == 0xda;
290 seen_scan |= scanning;
291 at = end;
292 check.activity()?;
293 }
294 Err(ErrorCode::Integrity)
295}
296fn jpeg_error(error: zune_jpeg::errors::DecodeErrors) -> ErrorCode {
297 match error {
298 zune_jpeg::errors::DecodeErrors::LargeDimensions(_) => ErrorCode::Limit,
299 zune_jpeg::errors::DecodeErrors::Unsupported(_) => ErrorCode::UnsupportedFeature,
300 _ => ErrorCode::Integrity,
301 }
302}
303fn jpeg(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> {
304 if !source.starts_with(&[0xff, 0xd8]) {
305 return Err(ErrorCode::UnsupportedFormat);
306 }
307 if !source.ends_with(&[0xff, 0xd9]) {
308 return Err(ErrorCode::Integrity);
309 }
310 let expected = jpeg_info(entry_id, source, check)?;
311 let options = DecoderOptions::new_safe()
312 .set_strict_mode(true)
313 .set_max_width(MAX_PREVIEW_DIMENSION as usize)
314 .set_max_height(MAX_PREVIEW_DIMENSION as usize)
315 .jpeg_set_max_scans(100)
316 .jpeg_set_out_colorspace(ColorSpace::RGB);
317 let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(source), options);
318 decoder.decode_headers().map_err(jpeg_error)?;
319 let header = decoder.info().ok_or(ErrorCode::Integrity)?;
320 let info = rgba_info(entry_id, u32::from(header.width), u32::from(header.height))?;
321 let rgb_bytes = (info.total_bytes / 4 * 3) as usize;
322 if info != expected || decoder.output_buffer_size() != Some(rgb_bytes) {
323 return Err(ErrorCode::Integrity);
324 }
325 let mut rgba = buffer(info.total_bytes as usize)?;
326 decoder
327 .decode_into(&mut rgba[..rgb_bytes])
328 .map_err(jpeg_error)?;
329 // CMYK의 RGBA 경로를 피하고 같은 버퍼 안에서 불투명 알파를 채움.
330 for row in (0..info.height as usize).rev() {
331 check.activity()?;
332 for column in (0..info.width as usize).rev() {
333 let pixel = row * info.width as usize + column;
334 let rgb = [
335 rgba[pixel * 3],
336 rgba[pixel * 3 + 1],
337 rgba[pixel * 3 + 2],
338 255,
339 ];
340 rgba[pixel * 4..pixel * 4 + 4].copy_from_slice(&rgb);
341 }
342 }
343 Ok((info, rgba))
344}
345
346#[cfg(test)]
347#[path = "../../../tests/rust-archive-worker/preview_decode.rs"]
348mod tests;