Skip to content

Commit 3187a89

Browse files
wxiaoguangdelvhtechknowlogicklunny
authored andcommitted
Do not recognize text files as audio (go-gitea#23355)
Close go-gitea#17108 This PR uses a trick (removing the ID3 tag) to detect the content again to to see whether the content is text type. --------- Co-authored-by: delvh <[email protected]> Co-authored-by: techknowlogick <[email protected]> Co-authored-by: Lunny Xiao <[email protected]>
1 parent 3dc2724 commit 3187a89

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

modules/typesniffer/typesniffer.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,16 @@ func DetectContentType(data []byte) SniffedType {
9898
ct = SvgMimeType
9999
}
100100

101+
if strings.HasPrefix(ct, "audio/") && bytes.HasPrefix(data, []byte("ID3")) {
102+
// The MP3 detection is quite inaccurate, any content with "ID3" prefix will result in "audio/mpeg".
103+
// So remove the "ID3" prefix and detect again, if result is text, then it must be text content.
104+
// This works especially because audio files contain many unprintable/invalid characters like `0x00`
105+
ct2 := http.DetectContentType(data[3:])
106+
if strings.HasPrefix(ct2, "text/") {
107+
ct = ct2
108+
}
109+
}
110+
101111
return SniffedType{ct}
102112
}
103113

modules/typesniffer/typesniffer_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ func TestIsAudio(t *testing.T) {
8787
mp3, _ := base64.StdEncoding.DecodeString("SUQzBAAAAAABAFRYWFgAAAASAAADbWFqb3JfYnJhbmQAbXA0MgBUWFhYAAAAEQAAA21pbm9yX3Zl")
8888
assert.True(t, DetectContentType(mp3).IsAudio())
8989
assert.False(t, DetectContentType([]byte("plain text")).IsAudio())
90+
91+
assert.True(t, DetectContentType([]byte("ID3Toy\000")).IsAudio())
92+
assert.True(t, DetectContentType([]byte("ID3Toy\n====\t* hi 🌞, ...")).IsText()) // test ID3 tag for plain text
93+
assert.True(t, DetectContentType([]byte("ID3Toy\n====\t* hi 🌞, ..."+"🌛"[0:2])).IsText()) // test ID3 tag with incomplete UTF8 char
9094
}
9195

9296
func TestDetectContentTypeFromReader(t *testing.T) {

0 commit comments

Comments
 (0)