Skip to content

Commit

Permalink
Fix brotli match when stream is nil
Browse files Browse the repository at this point in the history
The documentation for the `Match` function says that setting passing
`nil` to `stream` is allowed, however there's a NPE in Brotli's `Match`
because it doesn't properly check if stream is specified or not.
  • Loading branch information
Gusted committed Dec 16, 2024
1 parent 5e373c5 commit 389a7c2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
18 changes: 10 additions & 8 deletions brotli.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,16 @@ func (br Brotli) Match(_ context.Context, filename string, stream io.Reader) (Ma
mr.ByName = true
}

// brotli does not have well-defined file headers or a magic number;
// the best way to match the stream is probably to try decoding part
// of it, but we'll just have to guess a large-enough size that is
// still small enough for the smallest streams we'll encounter
r := brotli.NewReader(stream)
buf := make([]byte, 16)
if _, err := io.ReadFull(r, buf); err == nil {
mr.ByStream = true
if stream != nil {
// brotli does not have well-defined file headers or a magic number;
// the best way to match the stream is probably to try decoding part
// of it, but we'll just have to guess a large-enough size that is
// still small enough for the smallest streams we'll encounter
r := brotli.NewReader(stream)
buf := make([]byte, 16)
if _, err := io.ReadFull(r, buf); err == nil {
mr.ByStream = true
}
}

return mr, nil
Expand Down
7 changes: 7 additions & 0 deletions formats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -455,5 +455,12 @@ func TestIdentifyASCIIFileStartingWithX(t *testing.T) {
if !errors.Is(err, NoMatch) {
t.Errorf("Identify failed: %v", err)
}
}

func TestIdentifyStreamNil(t *testing.T) {
format, _, err := Identify(context.Background(), "test.tar.zst", nil)
checkErr(t, err, "identifying tar.zst")
if format.Extension() != ".tar.zst" {
t.Errorf("unexpected format found: expected=.tar.zst actual=%s", format.Extension())
}
}

0 comments on commit 389a7c2

Please sign in to comment.