team-ljyzipelo

공개
399줄14 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 let mut components = Vec::new();
244 let mut decoded_components = 0u8;
245 let mut progressive = false;
246 while at < source.len() {
247 check.check()?;
248 if scanning {
249 at += source[at..]
250 .iter()
251 .position(|byte| *byte == 0xff)
252 .ok_or(ErrorCode::Integrity)?;
253 }
254 if source[at] != 0xff {
255 return Err(ErrorCode::Integrity);
256 }
257 while source.get(at) == Some(&0xff) {
258 at += 1;
259 }
260 let marker = *source.get(at).ok_or(ErrorCode::Integrity)?;
261 at += 1;
262 match marker {
263 0 | 0xd0..=0xd7 if scanning => continue,
264 0xd9 if at == source.len() && seen_scan => {
265 if decoded_components != (1 << components.len()) - 1 {
266 return Err(ErrorCode::Integrity);
267 }
268 return info.ok_or(ErrorCode::Integrity);
269 }
270 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity),
271 1 => continue,
272 _ => {}
273 }
274 let length = source.get(at..at + 2).ok_or(ErrorCode::Integrity)?;
275 let length = u16::from_be_bytes(length.try_into().unwrap()) as usize;
276 let end = at
277 .checked_add(length)
278 .filter(|n| length >= 2 && *n <= source.len())
279 .ok_or(ErrorCode::Integrity)?;
280 let body = &source[at + 2..end];
281 if matches!(marker, 0xc0..=0xcf) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) {
282 if info.is_some() || body.len() < 6 {
283 return Err(ErrorCode::Integrity);
284 }
285 if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 {
286 return Err(ErrorCode::UnsupportedFeature);
287 }
288 progressive = marker == 0xc2;
289 let count = usize::from(body[5]);
290 if !(1..=4).contains(&count) || body.len() != 6 + count * 3 {
291 return Err(ErrorCode::Integrity);
292 }
293 for component in body[6..].chunks_exact(3) {
294 if components.contains(&component[0]) {
295 return Err(ErrorCode::Integrity);
296 }
297 components.push(component[0]);
298 }
299 info = Some(rgba_info(
300 entry_id,
301 u32::from(u16::from_be_bytes(body[3..5].try_into().unwrap())),
302 u32::from(u16::from_be_bytes(body[1..3].try_into().unwrap())),
303 )?);
304 }
305 if marker == 0xe2 && body.starts_with(b"MPF\0") {
306 return Err(ErrorCode::UnsupportedFeature);
307 }
308 scanning = marker == 0xda;
309 if scanning {
310 let count = usize::from(*body.first().ok_or(ErrorCode::Integrity)?);
311 if info.is_none()
312 || count == 0
313 || count > components.len()
314 || body.len() != 4 + count * 2
315 {
316 return Err(ErrorCode::Integrity);
317 }
318 let mut scan_components = 0u8;
319 for component in body[1..1 + count * 2].chunks_exact(2) {
320 let index = components
321 .iter()
322 .position(|id| *id == component[0])
323 .ok_or(ErrorCode::Integrity)?;
324 let bit = 1 << index;
325 if scan_components & bit != 0 {
326 return Err(ErrorCode::Integrity);
327 }
328 scan_components |= bit;
329 }
330 if !progressive
331 && (scan_components & decoded_components != 0
332 || body[1 + count * 2..] != [0, 63, 0])
333 {
334 return Err(ErrorCode::Integrity);
335 }
336 // 모든 색상 성분의 최초 DC 스캔이 있어야 완전한 그림으로 처리함.
337 if body[1 + count * 2] == 0 && body[3 + count * 2] >> 4 == 0 {
338 decoded_components |= scan_components;
339 }
340 }
341 seen_scan |= scanning;
342 at = end;
343 check.activity()?;
344 }
345 Err(ErrorCode::Integrity)
346}
347fn jpeg_error(error: zune_jpeg::errors::DecodeErrors) -> ErrorCode {
348 match error {
349 zune_jpeg::errors::DecodeErrors::LargeDimensions(_) => ErrorCode::Limit,
350 zune_jpeg::errors::DecodeErrors::Unsupported(_) => ErrorCode::UnsupportedFeature,
351 _ => ErrorCode::Integrity,
352 }
353}
354fn jpeg(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> {
355 if !source.starts_with(&[0xff, 0xd8]) {
356 return Err(ErrorCode::UnsupportedFormat);
357 }
358 if !source.ends_with(&[0xff, 0xd9]) {
359 return Err(ErrorCode::Integrity);
360 }
361 let expected = jpeg_info(entry_id, source, check)?;
362 let options = DecoderOptions::new_safe()
363 .set_strict_mode(true)
364 .set_max_width(MAX_PREVIEW_DIMENSION as usize)
365 .set_max_height(MAX_PREVIEW_DIMENSION as usize)
366 .jpeg_set_max_scans(100)
367 .jpeg_set_out_colorspace(ColorSpace::RGB);
368 let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(source), options);
369 decoder.decode_headers().map_err(jpeg_error)?;
370 let header = decoder.info().ok_or(ErrorCode::Integrity)?;
371 let info = rgba_info(entry_id, u32::from(header.width), u32::from(header.height))?;
372 let rgb_bytes = (info.total_bytes / 4 * 3) as usize;
373 if info != expected || decoder.output_buffer_size() != Some(rgb_bytes) {
374 return Err(ErrorCode::Integrity);
375 }
376 let mut rgba = buffer(info.total_bytes as usize)?;
377 decoder
378 .decode_into(&mut rgba[..rgb_bytes])
379 .map_err(jpeg_error)?;
380 // CMYK의 RGBA 경로를 피하고 같은 버퍼 안에서 불투명 알파를 채움.
381 for row in (0..info.height as usize).rev() {
382 check.activity()?;
383 for column in (0..info.width as usize).rev() {
384 let pixel = row * info.width as usize + column;
385 let rgb = [
386 rgba[pixel * 3],
387 rgba[pixel * 3 + 1],
388 rgba[pixel * 3 + 2],
389 255,
390 ];
391 rgba[pixel * 4..pixel * 4 + 4].copy_from_slice(&rgb);
392 }
393 }
394 Ok((info, rgba))
395}
396
397#[cfg(test)]
398#[path = "../../../tests/rust-archive-worker/preview_decode.rs"]
399mod tests;