From dd9244c01d67ffef0050e6a6b7cef216f944f926 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Tue, 13 Feb 2018 00:21:28 +1100 Subject: [PATCH] bencode: Unmarshal now returns an error on unused trailing bytes --- bencode/api.go | 19 ++++++++++++++++--- client.go | 5 +++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/bencode/api.go b/bencode/api.go index 1b77f588..12511997 100644 --- a/bencode/api.go +++ b/bencode/api.go @@ -123,9 +123,22 @@ func Marshal(v interface{}) ([]byte, error) { // Unmarshal the bencode value in the 'data' to a value pointed by the 'v' // pointer, return a non-nil error if any. -func Unmarshal(data []byte, v interface{}) error { - e := Decoder{r: bytes.NewBuffer(data)} - return e.Decode(v) +func Unmarshal(data []byte, v interface{}) (err error) { + buf := bytes.NewBuffer(data) + e := Decoder{r: buf} + err = e.Decode(v) + if err == nil && buf.Len() != 0 { + err = ErrUnusedTrailingBytes{buf.Len()} + } + return +} + +type ErrUnusedTrailingBytes struct { + NumUnusedBytes int +} + +func (me ErrUnusedTrailingBytes) Error() string { + return fmt.Sprintf("%d unused trailing bytes", me.NumUnusedBytes) } func NewDecoder(r io.Reader) *Decoder { diff --git a/client.go b/client.go index 60bd43b4..deb09a3f 100644 --- a/client.go +++ b/client.go @@ -912,8 +912,9 @@ func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) { func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) error { var d map[string]int err := bencode.Unmarshal(payload, &d) - if err != nil { - return fmt.Errorf("error unmarshalling payload: %s: %q", err, payload) + if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok { + } else if err != nil { + return fmt.Errorf("error unmarshalling bencode: %s", err) } msgType, ok := d["msg_type"] if !ok {