| 1 | package imagefile |
| 2 | |
| 3 | import ( |
| 4 | "encoding/binary" |
| 5 | "hash/crc32" |
| 6 | ) |
| 7 | |
| 8 | // The PNG walker (§5). It keeps the critical chunks, the colour and |
| 9 | // layout chunks a picture needs (iCCP, sRGB, gAMA, cHRM, cICP, mDCV, |
| 10 | // cLLI, sBIT, pHYs, tRNS, bKGD) and APNG's (acTL, fcTL, fdAT). It drops |
| 11 | // eXIf, tEXt, zTXt, iTXt, tIME and every unknown ancillary chunk, and |
| 12 | // ends the file at IEND. A chunk whose CRC is wrong, or a critical |
| 13 | // chunk it does not know, is refused. |
| 14 | |
| 15 | var pngKept = map[string]bool{ |
| 16 | "IHDR": true, "PLTE": true, "IDAT": true, "IEND": true, |
| 17 | "iCCP": true, "sRGB": true, "gAMA": true, "cHRM": true, "cICP": true, |
| 18 | "mDCV": true, "cLLI": true, "sBIT": true, "pHYs": true, "tRNS": true, |
| 19 | "bKGD": true, "acTL": true, "fcTL": true, "fdAT": true, |
| 20 | } |
| 21 | |
| 22 | const pngSignature = "\x89PNG\r\n\x1a\n" |
| 23 | |
| 24 | func cleanPNG(raw []byte) ([]byte, int, error) { |
| 25 | out := append(make([]byte, 0, len(raw)), pngSignature...) |
| 26 | for at := len(pngSignature); ; { |
| 27 | kind, end, err := pngChunk(raw, at) |
| 28 | if err != nil { |
| 29 | return nil, 0, err |
| 30 | } |
| 31 | if at == len(pngSignature) && kind != "IHDR" { |
| 32 | return nil, 0, ErrMalformed |
| 33 | } |
| 34 | critical := kind[0] >= 'A' && kind[0] <= 'Z' |
| 35 | switch { |
| 36 | case pngKept[kind]: |
| 37 | out = append(out, raw[at:end]...) |
| 38 | case critical: |
| 39 | return nil, 0, ErrMalformed |
| 40 | } |
| 41 | if kind == "IEND" { |
| 42 | return out, 1, nil |
| 43 | } |
| 44 | at = end |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // pngChunk reads the chunk at raw[at]: its type and where it ends. |
| 49 | func pngChunk(raw []byte, at int) (string, int, error) { |
| 50 | if at+12 > len(raw) { |
| 51 | return "", 0, ErrMalformed |
| 52 | } |
| 53 | length := binary.BigEndian.Uint32(raw[at:]) |
| 54 | if uint64(length) > uint64(len(raw)-at-12) { |
| 55 | return "", 0, ErrMalformed |
| 56 | } |
| 57 | end := at + 12 + int(length) |
| 58 | kind := string(raw[at+4 : at+8]) |
| 59 | for _, letter := range []byte(kind) { |
| 60 | if !(letter >= 'A' && letter <= 'Z' || letter >= 'a' && |
| 61 | letter <= 'z') { |
| 62 | return "", 0, ErrMalformed |
| 63 | } |
| 64 | } |
| 65 | sum := binary.BigEndian.Uint32(raw[end-4:]) |
| 66 | if crc32.ChecksumIEEE(raw[at+4:end-4]) != sum { |
| 67 | return "", 0, ErrMalformed |
| 68 | } |
| 69 | return kind, end, nil |
| 70 | } |
| 71 | |