add debugging context to readPacket errors

This commit is contained in:
Cassondra Foesch 2025-05-30 13:51:56 +00:00
parent 432973ce46
commit e55eb41460
1 changed files with 24 additions and 8 deletions

View File

@ -2,6 +2,7 @@ package sshfx
import ( import (
"errors" "errors"
"fmt"
"io" "io"
) )
@ -123,9 +124,13 @@ func readPacket(r io.Reader, b []byte, maxPacketLength uint32) ([]byte, error) {
b = make([]byte, smallBufferSize) b = make([]byte, smallBufferSize)
} }
if _, err := io.ReadFull(r, b[:4]); err != nil { if n, err := io.ReadFull(r, b[:4]); err != nil {
if err == io.EOF {
// Do not ever wrap io.EOF.
return nil, err return nil, err
} }
return nil, fmt.Errorf("error reading packet length: %d of 4: %w", n, err)
}
length := unmarshalPacketLength(b) length := unmarshalPacketLength(b)
if int(length) < 5 { if int(length) < 5 {
@ -150,13 +155,24 @@ func readPacket(r io.Reader, b []byte, maxPacketLength uint32) ([]byte, error) {
} }
n, err := io.ReadFull(r, b[:length]) n, err := io.ReadFull(r, b[:length])
b = b[:n]
if err != nil {
if err == io.EOF { if err == io.EOF {
// ReadFull only returns EOF if it has read no bytes. // ReadFull only returns EOF if it has read no bytes.
// In this case, that means a partial packet (length but no body), // In this case, that means a partial packet (length but no body),
// and thus unexpected. // and thus unexpected.
err = io.ErrUnexpectedEOF err = io.ErrUnexpectedEOF
} }
return b[:n], err
if n > 0 {
return b, fmt.Errorf("error reading packet body: %d of %d: (%s) %w", n, length, PacketType(b[0]), err)
}
return b, fmt.Errorf("error reading packet body: %d of %d: %w", n, length, err)
}
return b, nil
} }
// ReadFrom provides a simple functional packet reader, // ReadFrom provides a simple functional packet reader,