Open cyphar opened 3 years ago
Here's a simple reproducer -- note that in this case, Read
is called until the end of the stream is reached and then WriteTo
is called. https://play.golang.org/p/touWFY2ATjv
package main
import (
"fmt"
"bytes"
"io"
"io/ioutil"
"github.com/klauspost/pgzip"
)
// echo hello | gzip -c | xxd -i
var gzipData = []byte{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xcb, 0x48,
0xcd, 0xc9, 0xc9, 0xe7, 0x02, 0x00, 0x20, 0x30, 0x3a, 0x36, 0x06, 0x00,
0x00, 0x00,
}
func main() {
buf := bytes.NewBuffer(gzipData)
rdr, err := pgzip.NewReader(buf)
if err != nil {
panic(err)
}
b, err := ioutil.ReadAll(rdr)
if err != nil {
panic(err)
}
fmt.Printf("read %q from stream\n", string(b))
n, err := io.Copy(ioutil.Discard, rdr)
fmt.Printf("io.Copy at end of stream: n=%v, err=%v\n", n, err)
}
It turns out that if you have a
pgzip.Reader
which has read to the end of the stream, if you callio.Copy
on that stream you getio.EOF
-- which should never happen and causes spurious errors on callers that check error values fromio.Copy
. I hit this when working on opencontainers/umoci#360.This happens because (as an optimisation)
io.Copy
will use theWriteTo
method of the reader (orReadFrom
method of the writer) if they support that method. And in this mode,io.Copy
simply returns whatever error the reader or writer give it -- meaning it doesn't hideio.EOF
s returned from those methods. In the normalRead
+Write
mode,io.Copy
does hide the error.It seems as though this is at some level a stdlib bug, because this requirement of
io.WriterTo
andio.ReaderTo
implementations (don't returnio.EOF
becauseio.Copy
can't handle it) is not spelled out anywhere in the documentation. So eitherio.Copy
should handle this, or this requirment should be documented. So I will open a parallel issue on the Go tracker for this problem.But for now, it seems that the
WriteTo
implementation should avoid returningio.EOF
. If the reader reaches anio.EOF
before it is expected, the error should instead beio.ErrUnexpectedEOF
.