Skip to main content

nitr_std/validate/media/
dimensions.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Header-only image dimensions for the formats whose header carries
7//! them: the decompression-bomb guard for whatever decodes the image
8//! later. Nothing is decoded; only the prefix is read.
9
10use super::MediaType;
11
12fn at(prefix: &[u8], offset: usize, magic: &[u8]) -> bool {
13    prefix.len() >= offset + magic.len() && &prefix[offset..offset + magic.len()] == magic
14}
15
16fn be16(prefix: &[u8], i: usize) -> Option<u32> {
17    prefix
18        .get(i..i + 2)
19        .map(|b| u32::from(u16::from_be_bytes([b[0], b[1]])))
20}
21
22fn be32(prefix: &[u8], i: usize) -> Option<u32> {
23    prefix
24        .get(i..i + 4)
25        .map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
26}
27
28fn le16(prefix: &[u8], i: usize) -> Option<u32> {
29    prefix
30        .get(i..i + 2)
31        .map(|b| u32::from(u16::from_le_bytes([b[0], b[1]])))
32}
33
34fn le32(prefix: &[u8], i: usize) -> Option<u32> {
35    prefix
36        .get(i..i + 4)
37        .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
38}
39
40fn png(prefix: &[u8]) -> Option<(u32, u32)> {
41    if !at(prefix, 12, b"IHDR") {
42        return None;
43    }
44    Some((be32(prefix, 16)?, be32(prefix, 20)?))
45}
46
47fn gif(prefix: &[u8]) -> Option<(u32, u32)> {
48    Some((le16(prefix, 6)?, le16(prefix, 8)?))
49}
50
51fn bmp(prefix: &[u8]) -> Option<(u32, u32)> {
52    let header = le32(prefix, 14)?;
53    if header == 12 {
54        Some((le16(prefix, 18)?, le16(prefix, 20)?))
55    } else {
56        let w = le32(prefix, 18)?;
57        let h = le32(prefix, 22)?;
58        // Height may be negative (top-down rows).
59        Some((w, (h as i32).unsigned_abs()))
60    }
61}
62
63/// Walks the JPEG segments to the first `SOFn` marker.
64fn jpeg(prefix: &[u8]) -> Option<(u32, u32)> {
65    let mut pos = 2usize;
66    while pos + 9 <= prefix.len() {
67        if prefix[pos] != 0xFF {
68            return None;
69        }
70        let marker = prefix[pos + 1];
71        if marker == 0xFF {
72            pos += 1;
73            continue;
74        }
75        if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
76            pos += 2;
77            continue;
78        }
79        let len = usize::from(u16::from_be_bytes([prefix[pos + 2], prefix[pos + 3]]));
80        if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) {
81            let h = be16(prefix, pos + 5)?;
82            let w = be16(prefix, pos + 7)?;
83            return Some((w, h));
84        }
85        if marker == 0xDA || len < 2 {
86            return None;
87        }
88        pos += 2 + len;
89    }
90    None
91}
92
93fn webp(prefix: &[u8]) -> Option<(u32, u32)> {
94    match prefix.get(12..16)? {
95        b"VP8 " => {
96            // Key frame: 3-byte frame tag, 3-byte start code, then 14-bit
97            // width and height.
98            if !at(prefix, 23, b"\x9d\x01\x2a") {
99                return None;
100            }
101            Some((le16(prefix, 26)? & 0x3FFF, le16(prefix, 28)? & 0x3FFF))
102        }
103        b"VP8L" => {
104            if prefix.get(20)? != &0x2F {
105                return None;
106            }
107            let bits = le32(prefix, 21)?;
108            Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
109        }
110        b"VP8X" => {
111            let u24 = |i: usize| -> Option<u32> {
112                Some(
113                    u32::from(*prefix.get(i)?)
114                        | (u32::from(*prefix.get(i + 1)?) << 8)
115                        | (u32::from(*prefix.get(i + 2)?) << 16),
116                )
117            };
118            Some((u24(24)? + 1, u24(27)? + 1))
119        }
120        _ => None,
121    }
122}
123
124fn tiff(prefix: &[u8]) -> Option<(u32, u32)> {
125    let little = prefix.starts_with(b"II");
126    let rd16 = |i: usize| -> Option<u32> {
127        if little {
128            le16(prefix, i)
129        } else {
130            be16(prefix, i)
131        }
132    };
133    let rd32 = |i: usize| -> Option<u32> {
134        if little {
135            le32(prefix, i)
136        } else {
137            be32(prefix, i)
138        }
139    };
140    let ifd = rd32(4)? as usize;
141    let count = rd16(ifd)? as usize;
142    let (mut w, mut h) = (None, None);
143    for i in 0..count.min(64) {
144        let entry = ifd + 2 + i * 12;
145        let tag = rd16(entry)?;
146        let kind = rd16(entry + 2)?;
147        let value = if kind == 3 {
148            rd16(entry + 8)?
149        } else {
150            rd32(entry + 8)?
151        };
152        match tag {
153            256 => w = Some(value),
154            257 => h = Some(value),
155            _ => {}
156        }
157    }
158    Some((w?, h?))
159}
160
161/// Header-only image dimensions, or `None` when the header does not
162/// carry them (or is truncated).
163pub fn dimensions(media: &MediaType, prefix: &[u8]) -> Option<(u32, u32)> {
164    match media.name {
165        "image/png" => png(prefix),
166        "image/gif" => gif(prefix),
167        "image/bmp" => bmp(prefix),
168        "image/jpeg" => jpeg(prefix),
169        "image/webp" => webp(prefix),
170        "image/tiff" => tiff(prefix),
171        _ => None,
172    }
173}