media.gno
11.97 Kb · 345 lines
1package safe
2
3import (
4 "encoding/hex"
5 "errors"
6 "strconv"
7)
8
9// Media checks, moved in from p/media/v1 (image.gno, cid.gno) so core can
10// validate an engine's media (mainnet plan §2.1, M-3) without importing an
11// upload package. Behaviour and error texts are unchanged ("media: …");
12// the frontend twins are chain/cid.ts and the image header check of the
13// upload layer (docs/test-vectors/upload-v1.json).
14
15// IANA media types CheckImage and ImageDims understand. GIF is parsed for
16// completeness; callers decide which types they accept.
17const (
18 MimeSVG = "image/svg+xml"
19 MimePNG = "image/png"
20 MimeWebP = "image/webp"
21 MimeJPEG = "image/jpeg"
22 MimeGIF = "image/gif"
23)
24
25// Media limits.
26const (
27 MaxDim = 4096 // px per side, decompression-bomb guard
28 MaxSVGImageBytes = 16384 // CheckImage's AssertSVG cap for an SVG file
29)
30
31// CID codecs.
32const (
33 CodecRaw = 0x55
34 CodecDagPB = 0x70
35)
36
37// IPFSScheme prefixes an IPFS URI.
38const IPFSScheme = "ipfs://"
39
40func mediaErr(msg string) error { return errors.New("media: " + msg) }
41
42// mimeShort is the short name used in error texts ("png", …), "" when the
43// type is not a raster type ImageDims parses.
44func mimeShort(mime string) string {
45 switch mime {
46 case MimePNG:
47 return "png"
48 case MimeWebP:
49 return "webp"
50 case MimeJPEG:
51 return "jpeg"
52 case MimeGIF:
53 return "gif"
54 }
55 return ""
56}
57
58// CheckImage checks a complete file against its declared IANA type: an SVG
59// must pass AssertSVG with MaxSVGImageBytes; a raster file must carry the
60// type's magic bytes and header dimensions of 1..MaxDim per side
61// (ImageDims). Nothing else of a raster file is parsed: raster bytes are
62// only ever shown through <img> (SA-M3).
63func CheckImage(mime, data string) error {
64 if mime == MimeSVG {
65 return AssertSVG(data, MaxSVGImageBytes)
66 }
67 _, _, err := ImageDims(mime, data)
68 return err
69}
70
71// ImageDims returns a raster file's pixel dimensions after checking its
72// magic bytes and header (PNG IHDR, WebP VP8/VP8L/VP8X, JPEG SOFn, GIF
73// logical screen) and the 1..MaxDim bound per side.
74func ImageDims(mime, data string) (w, h int, err error) {
75 switch mime {
76 case MimePNG:
77 w, h, err = pngDims(data)
78 case MimeWebP:
79 w, h, err = webpDims(data)
80 case MimeJPEG:
81 w, h, err = jpegDims(data)
82 case MimeGIF:
83 w, h, err = gifDims(data)
84 default:
85 return 0, 0, mediaErr("unknown media type " + strconv.Quote(mime))
86 }
87 if err != nil {
88 return 0, 0, err
89 }
90 if w < 1 || h < 1 || w > MaxDim || h > MaxDim {
91 return 0, 0, mediaErr(mimeShort(mime) + ": dimensions " + strconv.Itoa(w) + "x" + strconv.Itoa(h) +
92 " outside 1.." + strconv.Itoa(MaxDim))
93 }
94 return w, h, nil
95}
96
97func be16(s string, i int) int { return int(s[i])<<8 | int(s[i+1]) }
98func le16(s string, i int) int { return int(s[i]) | int(s[i+1])<<8 }
99func le24(s string, i int) int { return int(s[i]) | int(s[i+1])<<8 | int(s[i+2])<<16 }
100func be32(s string, i int) int64 {
101 return int64(s[i])<<24 | int64(s[i+1])<<16 | int64(s[i+2])<<8 | int64(s[i+3])
102}
103func le32(s string, i int) int64 {
104 return int64(s[i]) | int64(s[i+1])<<8 | int64(s[i+2])<<16 | int64(s[i+3])<<24
105}
106
107// pngDims: signature, then the IHDR chunk (length 13) with big-endian
108// width and height. The 4-byte CRC after IHDR must be present.
109func pngDims(s string) (int, int, error) {
110 if len(s) < 33 || s[:8] != "\x89PNG\r\n\x1a\n" {
111 return 0, 0, mediaErr("png: bad signature or truncated header")
112 }
113 if be32(s, 8) != 13 || s[12:16] != "IHDR" {
114 return 0, 0, mediaErr("png: first chunk must be IHDR")
115 }
116 return int(be32(s, 16)), int(be32(s, 20)), nil
117}
118
119// webpDims: RIFF container whose size field covers the whole file, form
120// type WEBP, then one of the three bitstream headers.
121func webpDims(s string) (int, int, error) {
122 if len(s) < 30 || s[:4] != "RIFF" || s[8:12] != "WEBP" {
123 return 0, 0, mediaErr("webp: bad RIFF/WEBP header or truncated")
124 }
125 if le32(s, 4)+8 != int64(len(s)) {
126 return 0, 0, mediaErr("webp: RIFF size does not match the file size")
127 }
128 switch s[12:16] {
129 case "VP8 ": // lossy: 3-byte frame tag, start code 9d 01 2a, 14-bit dims
130 if s[23:26] != "\x9d\x01\x2a" {
131 return 0, 0, mediaErr("webp: bad VP8 start code")
132 }
133 return le16(s, 26) & 0x3fff, le16(s, 28) & 0x3fff, nil
134 case "VP8L": // lossless: signature 0x2f, 14-bit width-1 and height-1
135 if s[20] != 0x2f {
136 return 0, 0, mediaErr("webp: bad VP8L signature")
137 }
138 bits := le32(s, 21)
139 return int(bits&0x3fff) + 1, int((bits>>14)&0x3fff) + 1, nil
140 case "VP8X": // extended: 24-bit canvas width-1 and height-1
141 return le24(s, 24) + 1, le24(s, 27) + 1, nil
142 }
143 return 0, 0, mediaErr("webp: unknown bitstream chunk")
144}
145
146// jpegDims walks the marker segments after SOI up to the first SOFn
147// (C0..CF except C4 DHT, C8 JPG, CC DAC). Reaching SOS or EOI first, or
148// running out of bytes, is an error.
149func jpegDims(s string) (int, int, error) {
150 if len(s) < 4 || s[0] != 0xff || s[1] != 0xd8 || s[2] != 0xff {
151 return 0, 0, mediaErr("jpeg: bad SOI")
152 }
153 i := 2
154 for i < len(s) {
155 if s[i] != 0xff {
156 return 0, 0, mediaErr("jpeg: expected a marker at byte " + strconv.Itoa(i))
157 }
158 for i < len(s) && s[i] == 0xff { // fill bytes
159 i++
160 }
161 if i >= len(s) {
162 break
163 }
164 m := s[i]
165 i++
166 switch {
167 case m == 0xd8 || m == 0x01 || (m >= 0xd0 && m <= 0xd7):
168 continue // standalone markers
169 case m == 0xd9 || m == 0xda:
170 return 0, 0, mediaErr("jpeg: no frame header before scan data")
171 }
172 if i+2 > len(s) {
173 break
174 }
175 n := be16(s, i)
176 if n < 2 || i+n > len(s) {
177 return 0, 0, mediaErr("jpeg: bad segment length")
178 }
179 if m >= 0xc0 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc {
180 if n < 8 {
181 return 0, 0, mediaErr("jpeg: short frame header")
182 }
183 return be16(s, i+5), be16(s, i+3), nil // width after height
184 }
185 i += n
186 }
187 return 0, 0, mediaErr("jpeg: truncated before the frame header")
188}
189
190func gifDims(s string) (int, int, error) {
191 if len(s) < 13 || (s[:6] != "GIF87a" && s[:6] != "GIF89a") {
192 return 0, 0, mediaErr("gif: bad signature or truncated")
193 }
194 return le16(s, 6), le16(s, 8), nil
195}
196
197// CIDv1 grammar (design §12.1; frontend chain/cid.ts is the twin):
198// multibase 'b' (RFC 4648 base32, lower case, no padding) over exactly
199// 0x01 · codec · 0x12 · 0x20 · digest[32], codec 0x55 (raw) or 0x70
200// (dag-pb). That is 36 bytes = 58 base32 characters + 'b'. The unused two
201// trailing bits must be zero, so every CID has exactly one spelling. CIDv0
202// ("Qm…"), upper case, other bases, codecs or hash functions are refused.
203
204const (
205 b32Alphabet = "abcdefghijklmnopqrstuvwxyz234567"
206 cidBytes = 36
207 cidChars = 58 // ceil(36*8/5)
208 mhSha256 = 0x12
209 digestLen = 32
210)
211
212// ParseCIDv1 returns the codec (CodecRaw or CodecDagPB) and the sha2-256
213// digest as lower-case hex.
214func ParseCIDv1(s string) (codec int, digestHex string, err error) {
215 if s == "" {
216 return 0, "", mediaErr("cid: empty")
217 }
218 if len(s) >= 2 && s[0] == 'Q' && s[1] == 'm' {
219 return 0, "", mediaErr("cid: CIDv0 is not accepted; convert it to CIDv1")
220 }
221 if s[0] != 'b' {
222 return 0, "", mediaErr("cid: multibase must be 'b' (base32 lower case)")
223 }
224 if len(s) != cidChars+1 {
225 return 0, "", mediaErr("cid: expected " + strconv.Itoa(cidChars+1) + " characters, got " + strconv.Itoa(len(s)))
226 }
227 bz, derr := base32Decode(s[1:])
228 if derr != nil {
229 return 0, "", derr
230 }
231 if len(bz) != cidBytes {
232 return 0, "", mediaErr("cid: wrong length")
233 }
234 if bz[0] != 1 {
235 return 0, "", mediaErr("cid: version must be 1")
236 }
237 c := int(bz[1])
238 if c != CodecRaw && c != CodecDagPB {
239 return 0, "", mediaErr("cid: codec must be raw (0x55) or dag-pb (0x70)")
240 }
241 if bz[2] != mhSha256 || bz[3] != digestLen {
242 return 0, "", mediaErr("cid: multihash must be sha2-256")
243 }
244 return c, hex.EncodeToString(bz[4:]), nil
245}
246
247// IsIPFSURI reports whether s is IPFSScheme followed by a CIDv1 that
248// ParseCIDv1 accepts.
249func IsIPFSURI(s string) bool {
250 if len(s) <= len(IPFSScheme) || s[:len(IPFSScheme)] != IPFSScheme {
251 return false
252 }
253 _, _, err := ParseCIDv1(s[len(IPFSScheme):])
254 return err == nil
255}
256
257// CIDFromDigest is the inverse of ParseCIDv1. It panics on an unsupported
258// codec or a digest that is not 64 lower-case hex characters.
259func CIDFromDigest(codec int, digestHex string) string {
260 if codec != CodecRaw && codec != CodecDagPB {
261 panic("media: cid: unsupported codec")
262 }
263 d, ok := Raw32(digestHex)
264 if !ok {
265 panic("media: cid: digest must be 64 lower-case hex characters")
266 }
267 bz := make([]byte, 0, cidBytes)
268 bz = append(bz, 1, byte(codec), mhSha256, digestLen)
269 bz = append(bz, d...)
270 return "b" + base32Encode(bz)
271}
272
273// IsHex32 reports whether s is exactly 64 lower-case hex characters.
274func IsHex32(s string) bool {
275 _, ok := Raw32(s)
276 return ok
277}
278
279// Raw32 decodes exactly 64 lower-case hex characters into 32 raw bytes
280// (one pass, table lookups).
281func Raw32(s string) (string, bool) {
282 if len(s) != 64 {
283 return "", false
284 }
285 out := make([]byte, 32)
286 for i := 0; i < 32; i++ {
287 hi, lo := hexRev[s[2*i]], hexRev[s[2*i+1]]
288 if hi > 15 || lo > 15 {
289 return "", false
290 }
291 out[i] = hi<<4 | lo
292 }
293 return string(out), true
294}
295
296// hexRev and b32Rev map a byte to its digit value, 0xff when it is not a
297// lower-case hex / base32 digit.
298const (
299 hexRev = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
300 b32Rev = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x1a\x1b\x1c\x1d\x1e\x1f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
301)
302
303func base32Encode(bz []byte) string {
304 out := make([]byte, 0, (len(bz)*8+4)/5)
305 var buf uint32
306 bits := uint(0)
307 for _, b := range bz {
308 buf = buf<<8 | uint32(b)
309 bits += 8
310 for bits >= 5 {
311 bits -= 5
312 out = append(out, b32Alphabet[(buf>>bits)&31])
313 }
314 buf &= (1 << bits) - 1
315 }
316 if bits > 0 {
317 out = append(out, b32Alphabet[(buf<<(5-bits))&31])
318 }
319 return string(out)
320}
321
322// base32Decode is strict: lower-case alphabet only, and the unused
323// trailing bits must be zero.
324func base32Decode(s string) ([]byte, error) {
325 out := make([]byte, 0, len(s)*5/8)
326 var buf uint32
327 bits := uint(0)
328 for i := 0; i < len(s); i++ {
329 v := b32Rev[s[i]]
330 if v > 31 {
331 return nil, mediaErr("cid: invalid base32 character " + strconv.Quote(s[i:i+1]))
332 }
333 buf = buf<<5 | uint32(v)
334 bits += 5
335 if bits >= 8 {
336 bits -= 8
337 out = append(out, byte(buf>>bits))
338 buf &= (1 << bits) - 1
339 }
340 }
341 if bits >= 5 || buf != 0 {
342 return nil, mediaErr("cid: non-canonical base32 padding bits")
343 }
344 return out, nil
345}