From 6a33e70bd575e0032f52bc99ecb094b20eba3062 Mon Sep 17 00:00:00 2001 From: Derek McGowan Date: Thu, 25 Sep 2014 15:58:35 -0700 Subject: [PATCH] pkg/tarsum: fix panic with dynamic buffer When read is called on a tarsum with a two different read sizes, specifically the second call larger than the first, the dynamic buffer does not get reallocated causing a slice read error. Signed-off-by: Derek McGowan (github: dmcgowan) --- tarsum/tarsum.go | 4 ++-- tarsum/tarsum_test.go | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/tarsum/tarsum.go b/tarsum/tarsum.go index fe15287..6581f3f 100644 --- a/tarsum/tarsum.go +++ b/tarsum/tarsum.go @@ -179,7 +179,7 @@ func (ts *tarSum) Read(buf []byte) (int, error) { if ts.finished { return ts.bufWriter.Read(buf) } - if ts.bufData == nil { + if len(ts.bufData) < len(buf) { switch { case len(buf) <= buf8K: ts.bufData = make([]byte, buf8K) @@ -191,7 +191,7 @@ func (ts *tarSum) Read(buf []byte) (int, error) { ts.bufData = make([]byte, len(buf)) } } - buf2 := ts.bufData[:len(buf)-1] + buf2 := ts.bufData[:len(buf)] n, err := ts.tarR.Read(buf2) if err != nil { diff --git a/tarsum/tarsum_test.go b/tarsum/tarsum_test.go index 58dbdda..1e06cda 100644 --- a/tarsum/tarsum_test.go +++ b/tarsum/tarsum_test.go @@ -274,6 +274,22 @@ func TestTarSums(t *testing.T) { t.Errorf("%q :: %q", err, layer.filename) continue } + + // Read variable number of bytes to test dynamic buffer + dBuf := make([]byte, 1) + _, err = ts.Read(dBuf) + if err != nil { + t.Errorf("failed to read 1B from %s: %s", layer.filename, err) + continue + } + dBuf = make([]byte, 16*1024) + _, err = ts.Read(dBuf) + if err != nil { + t.Errorf("failed to read 16KB from %s: %s", layer.filename, err) + continue + } + + // Read and discard remaining bytes _, err = io.Copy(ioutil.Discard, ts) if err != nil { t.Errorf("failed to copy from %s: %s", layer.filename, err)