Skip to content

File.ReadFrom returns nil when the reader fails with io.ErrUnexpectedEOF #673

Closed

Description

@christhomas

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

  1. added 2 commits that reference this issue on Oct 15, 2026
    3d29963
    e5604b2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions