Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions decode_stringlen_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package bencode

import (
"bytes"
"strings"
"testing"
)

// A malformed string length (negative, or so large it overflows the slice
// allocator) must be reported as an error, not crash the decoder.
func TestDecodeMalformedStringLength(t *testing.T) {
for _, in := range []string{
"-1:",
"900000000000000000:",
"5:abc", // truncated: claims 5 bytes, only 3 present
} {
if _, err := Decode(strings.NewReader(in)); err == nil {
t.Errorf("Decode(%q) = nil error, want error", in)
}
}
}

// A well-formed string must still decode correctly after the length check.
func TestDecodeStringRoundTrip(t *testing.T) {
got, err := Decode(bytes.NewReader([]byte("5:hello")))
if err != nil {
t.Fatalf("Decode: unexpected error: %v", err)
}
if got != "hello" {
t.Errorf("Decode = %q, want %q", got, "hello")
}
}
17 changes: 13 additions & 4 deletions incswparse.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"strconv"
)

Expand Down Expand Up @@ -105,12 +107,19 @@ func unmarshal(data *bufio.Reader) (interface{}, error) {
if err != nil {
return nil, err
}
if stringLength < 0 {
return nil, fmt.Errorf("bad string length: %d", stringLength)
}

buf := make([]byte, stringLength)

_, err = readAtLeast(data, buf, int(stringLength))
var buf bytes.Buffer
if _, err = io.CopyN(&buf, data, stringLength); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}

return string(buf), err
return buf.String(), nil
}
}

Expand Down