Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cyphar opened this issue Feb 19, 2021 · 1 comment · May be fixed by #40
Open

Comments

@cyphar
Copy link

cyphar commented Feb 19, 2021

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
Copy link
Author

cyphar commented Feb 19, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant