klauspost / pgzip

Go parallel gzip (de)compression
MIT License
1.11k stars 77 forks source link

io.Copy(pgzip.Reader) returns io.EOF if stream already complete due to WriteTo implementation #38

Open cyphar opened 3 years ago

cyphar commented 3 years ago

It turns out that if you have a pgzip.Reader which has read to the end of the stream, if you call io.Copy on that stream you get io.EOF -- which should never happen and causes spurious errors on callers that check error values from io.Copy. I hit this when working on opencontainers/umoci#360.

This happens because (as an optimisation) io.Copy will use the WriteTo method of the reader (or ReadFrom 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 hide io.EOFs returned from those methods. In the normal Read+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 and io.ReaderTo implementations (don't return io.EOF because io.Copy can't handle it) is not spelled out anywhere in the documentation. So either io.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 returning io.EOF. If the reader reaches an io.EOF before it is expected, the error should instead be io.ErrUnexpectedEOF.

cyphar commented 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)
}