Repository navigation
Description
File.ReadFrom returns a nil error when the reader fails with io.ErrUnexpectedEOF, so io.Copy into an sftp.File reports success for a truncated source.
ReadFrom fills its buffer with io.ReadFull and treats io.ErrUnexpectedEOF as the end of the data, because io.ReadFull returns it when the reader ends part way through the buffer. But a reader can also return io.ErrUnexpectedEOF itself. net/http does this when a response body ends before its Content-Length, and so do the compress readers on truncated input. That error is dropped too. The concurrent path (UseConcurrentWrites) has the same check.
This happens when streaming a download into an SFTP upload: if the connection drops, io.Copy returns nil and the remote file is silently truncated.
Reproduction (v1.13.11, also current master)
package main
import (
"bufio"
"fmt"
"io"
"net"
"net/http"
"os"
"github.com/pkg/sftp"
)
func main() {
// An HTTP server that promises 1 MiB but drops the connection after 100 KiB.
l, _ := net.Listen("tcp", "127.0.0.1:0")
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
bufio.NewReader(c).ReadString('\n')
io.WriteString(c, "HTTP/1.1 200 OK\r\nContent-Length: 1048576\r\n\r\n")
c.Write(make([]byte, 100*1024))
c.Close()
}
}()
c1, c2 := net.Pipe()
go func() {
server, _ := sftp.NewServer(c2)
server.Serve()
}()
client, _ := sftp.NewClientPipe(c1, c1)
resp, _ := http.Get("http://" + l.Addr().String())
n, err := io.Copy(io.Discard, resp.Body)
fmt.Printf("io.Copy to io.Discard: n=%d, error: %v\n", n, err)
tmp, _ := os.CreateTemp("", "sftp-repro-")
tmp.Close()
defer os.Remove(tmp.Name())
resp, _ = http.Get("http://" + l.Addr().String())
f, _ := client.Create(tmp.Name())
n, err = io.Copy(f, resp.Body) // uses File.ReadFrom
f.Close()
fmt.Printf("io.Copy to sftp.File: n=%d, error: %v\n", n, err)
}Output:
io.Copy to io.Discard: n=102400, error: unexpected EOF
io.Copy to sftp.File: n=102400, error: <nil>
Expected: io.Copy to the sftp.File returns unexpected EOF, as it does for io.Discard or an *os.File.
Activity
return the reader's io.ErrUnexpectedEOF from File.ReadFrom
return the reader's io.ErrUnexpectedEOF from File.ReadFrom