]> Sergey Matveev's repositories - btrtrc.git/commitdiff
bencode: Unmarshal now returns an error on unused trailing bytes
authorMatt Joiner <anacrolix@gmail.com>
Mon, 12 Feb 2018 13:21:28 +0000 (00:21 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Mon, 12 Feb 2018 13:21:28 +0000 (00:21 +1100)
bencode/api.go
client.go

index 1b77f588b58865cd592657d7d6206f2ef063fa83..125119978a908a9fdfc56f62cfa1ef1a250465d0 100644 (file)
@@ -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 {
index 60bd43b4460821c26958f8536bf081dde2ad9f71..deb09a3f4649302876d3955d92c3e52f77d21fed 100644 (file)
--- 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 {