Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions match_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ func TestMatch(t *testing.T) {
{[]byte{0xFF, 0xD8, 0xFF}, "jpg"},
{[]byte{0xFF, 0xD8, 0x00}, "unknown"},
{[]byte{0x89, 0x50, 0x4E, 0x47}, "png"},
{[]byte("BMW"), "unknown"},
{
[]byte{
'B', 'M',
0x3A, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00,
},
"bmp",
},
}

for _, test := range cases {
Expand All @@ -32,6 +42,30 @@ func TestMatch(t *testing.T) {
}
}

func TestBmpNotAsciiPrefix(t *testing.T) {
// Issue #117: "BMW" starts with BM but is not a BMP file.
kind, err := Match([]byte("BMW"))
if err != nil {
t.Fatalf("Match: %v", err)
}
if kind.Extension == "bmp" {
t.Fatalf("ASCII BMW matched as bmp")
}
if matchers.Bmp([]byte("BMW")) {
t.Fatalf("Bmp matcher accepted ASCII BMW")
}

header := make([]byte, 14)
header[0], header[1] = 'B', 'M'
if !matchers.Bmp(header) {
t.Fatalf("14-byte BM header with reserved=0 should match")
}
header[6] = 1
if matchers.Bmp(header) {
t.Fatalf("non-zero reserved field should not match")
}
}

func TestMatchFile(t *testing.T) {
cases := []struct {
ext string
Expand Down Expand Up @@ -100,6 +134,7 @@ func TestMatches(t *testing.T) {
{[]byte{0xFF, 0xD8, 0xFF}, true},
{[]byte{0xFF, 0x0, 0x0}, false},
{[]byte{0x89, 0x50, 0x4E, 0x47}, true},
{[]byte("BMW"), false},
}

for _, test := range cases {
Expand Down
12 changes: 9 additions & 3 deletions matchers/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,15 @@ func Tiff(buf []byte) bool {
}

func Bmp(buf []byte) bool {
return len(buf) > 1 &&
buf[0] == 0x42 &&
buf[1] == 0x4D
// BITMAPFILEHEADER is 14 bytes: "BM" + size + reserved (must be 0) + pixel offset.
// Matching only "BM" treats short ASCII like "BMW" as image/bmp (issue #117).
if len(buf) < 14 {
return false
}
if buf[0] != 0x42 || buf[1] != 0x4D {
return false
}
return buf[6] == 0 && buf[7] == 0 && buf[8] == 0 && buf[9] == 0
}

func Jxr(buf []byte) bool {
Expand Down