This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
mimes.go
257 lines (230 loc) · 6.28 KB
/
mimes.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package thumbnailer
import (
"bytes"
"encoding/binary"
"image"
"io"
)
const sniffSize = 4 << 10
// Matching code partially adapted from "net/http/sniff.go"
// Mime type prefix magic number matchers and canonical extensions
var matchers = []Matcher{
// Probably most common types, this library will be used for, first.
// More expensive checks are also positioned lower.
&exactSig{"jpg", "image/jpeg", []byte("\xFF\xD8\xFF")},
&exactSig{"png", "image/png", []byte("\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")},
&exactSig{"gif", "image/gif", []byte("GIF87a")},
&exactSig{"gif", "image/gif", []byte("GIF89a")},
&maskedSig{
"webp",
"image/webp",
[]byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF"),
[]byte("RIFF\x00\x00\x00\x00WEBPVP"),
},
&maskedSig{
"ogg",
"application/ogg",
[]byte("OggS\x00"),
[]byte("\x4F\x67\x67\x53\x00"),
},
MatcherFunc(matchWebmOrMKV),
&exactSig{"pdf", "application/pdf", []byte("%PDF-")},
&maskedSig{
"mp3",
"audio/mpeg",
[]byte("\xFF\xFF\xFF"),
[]byte("ID3"),
},
&exactSig{"mp3", "audio/mpeg", []byte("\xFF\xFB")},
MatcherFunc(matchMP4),
&exactSig{"aac", "audio/aac", []byte("ÿñ")},
&exactSig{"aac", "audio/aac", []byte("ÿù")},
&exactSig{"bmp", "image/bmp", []byte("BM")},
&maskedSig{
"wav",
"audio/wave",
[]byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"),
[]byte("RIFF\x00\x00\x00\x00WAVE"),
},
&maskedSig{
"avi",
"video/avi",
[]byte("\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF"),
[]byte("RIFF\x00\x00\x00\x00AVI "),
},
&exactSig{"psd", "image/photoshop", []byte("8BPS")},
&exactSig{"flac", "audio/x-flac", []byte("fLaC")},
&exactSig{"tiff", "image/tiff", []byte("II*\x00")},
&exactSig{"tiff", "image/tiff", []byte("MM\x00*")},
&exactSig{"mov", "video/quicktime", []byte("\x00\x00\x00\x14ftyp")},
&exactSig{
"wmv",
"video/x-ms-wmv",
[]byte{0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9},
},
&exactSig{"flv", "video/x-flv", []byte("FLV\x01")},
&exactSig{"ico", "image/x-icon", []byte("\x00\x00\x01\x00")},
&maskedSig{
"midi",
"audio/midi",
[]byte("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF"),
[]byte("MThd\x00\x00\x00\x06"),
},
&exactSig{"zip", mimeZip, []byte("\x50\x4B\x03\x04")},
&exactSig{"rar", mimeRar, []byte("\x52\x61\x72\x20\x1A\x07\x00")},
// RAR v5 archive
&exactSig{"rar", mimeRar, []byte("\x52\x61\x72\x21\x1A\x07\x01\x00")},
&exactSig{"7z", mime7Zip, []byte{'7', 'z', 0xBC, 0xAF, 0x27, 0x1C}},
}
var (
// User-defined MIME type processors
overrideProcessors = map[string]Processor{}
)
// Processor is a specialized file processor for a specific file type.
// Returns thumbnail and error.
//
// io.ReadSeeker is the start position, when passed to Processor.
type Processor func(io.ReadSeeker, *Source, Options) (image.Image, error)
// Matcher takes up to the first 4 KB of a file and returns the MIME type
// and canonical extension, that were matched. Empty string indicates no match.
type Matcher interface {
Match([]byte) (mime string, extension string)
}
// MatcherFunc is an adapter that allows using functions as Matcher
type MatcherFunc func([]byte) (string, string)
// Match implements Matcher
func (fn MatcherFunc) Match(data []byte) (string, string) {
return fn(data)
}
type exactSig struct {
ext, mime string
sig []byte
}
func (e *exactSig) Match(data []byte) (string, string) {
if bytes.HasPrefix(data, e.sig) {
return e.mime, e.ext
}
return "", ""
}
type maskedSig struct {
ext, mime string
mask, pat []byte
}
func (m *maskedSig) Match(data []byte) (string, string) {
if len(data) < len(m.mask) {
return "", ""
}
for i, mask := range m.mask {
db := data[i] & mask
if db != m.pat[i] {
return "", ""
}
}
return m.mime, m.ext
}
func matchWebmOrMKV(data []byte) (string, string) {
switch {
case len(data) < 8 || !bytes.HasPrefix(data, []byte("\x1A\x45\xDF\xA3")):
return "", ""
case bytes.Contains(data[4:], []byte("webm")):
return "video/webm", "webm"
case bytes.Contains(data[4:], []byte("matroska")):
return "video/x-matroska", "mkv"
default:
return "", ""
}
}
func matchMP4(data []byte) (string, string) {
if len(data) < 12 {
return "", ""
}
boxSize := int(binary.BigEndian.Uint32(data[:4]))
nope := boxSize%4 != 0 ||
len(data) < boxSize ||
!bytes.Equal(data[4:8], []byte("ftyp"))
if nope {
return "", ""
}
for st := 8; st < boxSize; st += 4 {
if st == 12 {
// minor version number
continue
}
if bytes.Equal(data[st:st+3], []byte("mp4")) ||
bytes.Equal(data[st:st+4], []byte("dash")) {
return "video/mp4", "mp4"
}
}
return "", ""
}
// MP3 is a retarded standard, that will not always even have a magic number.
// Need to detect with FFMPEG as a last resort.
func matchMP3(data []byte) (mime string, ext string) {
c, err := NewFFContext(bytes.NewReader(data))
if err != nil {
return
}
defer c.Close()
codec, err := c.CodecName(FFAudio)
if err != nil {
return
}
if codec == "mp3" || codec == "mp3float" {
return "audio/mpeg", "mp3"
}
return
}
// RegisterMatcher adds an extra magic prefix-based MIME type matcher to the
// default set with an included canonical file extension.
//
// Not safe to use concurrently with file processing.
func RegisterMatcher(m Matcher) {
matchers = append(matchers, m)
}
// RegisterProcessor registers a file processor for a specific MIME type.
// Can be used to add support for additional MIME types or as an override.
//
// Not safe to use concurrently with file processing.
func RegisterProcessor(mime string, fn Processor) {
overrideProcessors[mime] = fn
}
// DetectMIME detects the MIME typ of the rs.
//
// accepted: if not nil, specifies MIME types to not reject with
// ErrUnsupportedMIME
func DetectMIME(rs io.ReadSeeker, accepted map[string]bool,
) (
mime, ext string, err error,
) {
_, err = rs.Seek(0, 0)
if err != nil {
return
}
buf := make([]byte, sniffSize)
read, err := rs.Read(buf)
if err != nil {
return
}
if read < sniffSize {
buf = buf[:read]
}
for _, m := range matchers {
mime, ext = m.Match(buf)
if mime != "" {
break
}
}
if mime == "" {
if accepted == nil || accepted["audio/mpeg"] {
mime, ext = matchMP3(buf)
}
}
switch {
case mime == "":
err = ErrUnsupportedMIME("application/octet-stream")
// Check if MIME is accepted, if specified
case accepted != nil && !accepted[mime]:
err = ErrUnsupportedMIME(mime)
}
return
}