From 389a7c28ca55fd5bc7b0256b71066a729b086ccc Mon Sep 17 00:00:00 2001 From: Gusted Date: Mon, 16 Dec 2024 04:27:46 +0100 Subject: [PATCH] Fix brotli match when stream is nil 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. --- brotli.go | 18 ++++++++++-------- formats_test.go | 7 +++++++ 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/brotli.go b/brotli.go index e6d09ab..02ad866 100644 --- a/brotli.go +++ b/brotli.go @@ -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 diff --git a/formats_test.go b/formats_test.go index 1735f00..ac91d1c 100644 --- a/formats_test.go +++ b/formats_test.go @@ -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()) + } }