15 // The default bencode string length limit. This is a poor attempt to prevent excessive memory
16 // allocation when parsing, but also leaves the window open to implement a better solution.
17 const DefaultDecodeMaxStrLen = 1<<27 - 1 // ~128MiB
19 type MaxStrLen = int64
22 // Maximum parsed bencode string length. Defaults to DefaultMaxStrLen if zero.
29 // Sum of bytes used to Decode values.
34 func (d *Decoder) Decode(v interface{}) (err error) {
43 _, ok := r.(runtime.Error)
47 if err, ok = r.(error); !ok {
50 // Errors thrown from deeper in parsing are unexpected. At value boundaries, errors should
51 // be returned directly (at least until all the panic nonsense is removed entirely).
53 err = io.ErrUnexpectedEOF
57 pv := reflect.ValueOf(v)
58 if pv.Kind() != reflect.Ptr || pv.IsNil() {
59 return &UnmarshalInvalidArgError{reflect.TypeOf(v)}
62 ok, err := d.parseValue(pv.Elem())
67 d.throwSyntaxError(d.Offset-1, errors.New("unexpected 'e'"))
72 func checkForUnexpectedEOF(err error, offset int64) {
76 What: io.ErrUnexpectedEOF,
81 func (d *Decoder) readByte() byte {
82 b, err := d.r.ReadByte()
84 checkForUnexpectedEOF(err, d.Offset)
92 // reads data writing it to 'd.buf' until 'sep' byte is encountered, 'sep' byte
93 // is consumed, but not included into the 'd.buf'
94 func (d *Decoder) readUntil(sep byte) {
104 func checkForIntParseError(err error, offset int64) {
113 func (d *Decoder) throwSyntaxError(offset int64, err error) {
120 // Assume the 'i' is already consumed. Read and validate the rest of an int into the buffer.
121 func (d *Decoder) readInt() error {
122 // start := d.Offset - 1
124 if err := d.checkBufferedInt(); err != nil {
127 // if d.buf.Len() == 0 {
128 // panic(&SyntaxError{
130 // What: errors.New("empty integer value"),
136 // called when 'i' was consumed, for the integer type in v.
137 func (d *Decoder) parseInt(v reflect.Value) error {
138 start := d.Offset - 1
140 if err := d.readInt(); err != nil {
143 s := bytesAsString(d.buf.Bytes())
146 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
147 n, err := strconv.ParseInt(s, 10, 64)
148 checkForIntParseError(err, start)
150 if v.OverflowInt(n) {
151 return &UnmarshalTypeError{
152 BencodeTypeName: "int",
153 UnmarshalTargetType: v.Type(),
157 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
158 n, err := strconv.ParseUint(s, 10, 64)
159 checkForIntParseError(err, start)
161 if v.OverflowUint(n) {
162 return &UnmarshalTypeError{
163 BencodeTypeName: "int",
164 UnmarshalTargetType: v.Type(),
171 return &UnmarshalTypeError{
172 BencodeTypeName: "int",
173 UnmarshalTargetType: v.Type(),
180 func (d *Decoder) checkBufferedInt() error {
188 if b[0] < '1' || b[0] > '9' {
189 return errors.New("invalid leading digit")
194 func (d *Decoder) parseStringLength() (int, error) {
195 // We should have already consumed the first byte of the length into the Decoder buf.
196 start := d.Offset - 1
198 if err := d.checkBufferedInt(); err != nil {
201 // Really the limit should be the uint size for the platform. But we can't pass in an allocator,
202 // or limit total memory use in Go, the best we might hope to do is limit the size of a single
203 // decoded value (by reading it in in-place and then operating on a view).
204 length, err := strconv.ParseInt(bytesAsString(d.buf.Bytes()), 10, 0)
205 checkForIntParseError(err, start)
206 if int64(length) > d.getMaxStrLen() {
207 err = fmt.Errorf("parsed string length %v exceeds limit (%v)", length, DefaultDecodeMaxStrLen)
210 return int(length), err
213 func (d *Decoder) parseString(v reflect.Value) error {
214 length, err := d.parseStringLength()
219 read := func(b []byte) {
220 n, err := io.ReadFull(d.r, b)
223 checkForUnexpectedEOF(err, d.Offset)
226 What: errors.New("unexpected I/O error: " + err.Error()),
233 b := make([]byte, length)
235 v.SetString(bytesAsString(b))
238 if v.Type().Elem().Kind() != reflect.Uint8 {
241 b := make([]byte, length)
246 if v.Type().Elem().Kind() != reflect.Uint8 {
250 b := d.buf.Bytes()[:length]
252 reflect.Copy(v, reflect.ValueOf(b))
256 b := d.buf.Bytes()[:length]
258 x, err := strconv.ParseBool(bytesAsString(b))
265 // Can't move this into default clause because some cases above fail through to here after
266 // additional checks.
268 read(d.buf.Bytes()[:length])
269 // I believe we return here to support "ignore_unmarshal_type_error".
270 return &UnmarshalTypeError{
271 BencodeTypeName: "string",
272 UnmarshalTargetType: v.Type(),
276 // Info for parsing a dict value.
277 type dictField struct {
279 Get func(value reflect.Value) func(reflect.Value)
283 // Returns specifics for parsing a dict field value.
284 func getDictField(dict reflect.Type, key string) (_ dictField, err error) {
285 // get valuev as a map value or as a struct field
286 switch k := dict.Kind(); k {
290 Get: func(mapValue reflect.Value) func(reflect.Value) {
291 return func(value reflect.Value) {
292 if mapValue.IsNil() {
293 mapValue.Set(reflect.MakeMap(dict))
295 // Assigns the value into the map.
296 // log.Printf("map type: %v", mapValue.Type())
297 mapValue.SetMapIndex(reflect.ValueOf(key).Convert(dict.Key()), value)
302 return getStructFieldForKey(dict, key), nil
303 // if sf.r.PkgPath != "" {
304 // panic(&UnmarshalFieldError{
306 // Type: dict.Type(),
311 err = fmt.Errorf("can't assign bencode dict items into a %v", k)
317 structFieldsMu sync.Mutex
318 structFields = map[reflect.Type]map[string]dictField{}
321 func parseStructFields(struct_ reflect.Type, each func(key string, df dictField)) {
322 for _i, n := 0, struct_.NumField(); _i < n; _i++ {
324 f := struct_.Field(i)
327 if t.Kind() == reflect.Ptr {
330 parseStructFields(t, func(key string, df dictField) {
332 df.Get = func(value reflect.Value) func(reflect.Value) {
333 anonPtr := value.Field(i)
334 if anonPtr.Kind() == reflect.Ptr && anonPtr.IsNil() {
335 anonPtr.Set(reflect.New(f.Type.Elem()))
336 anonPtr = anonPtr.Elem()
338 return innerGet(anonPtr)
344 tagStr := f.Tag.Get("bencode")
348 tag := parseTag(tagStr)
353 each(key, dictField{f.Type, func(value reflect.Value) func(reflect.Value) {
354 return value.Field(i).Set
359 func saveStructFields(struct_ reflect.Type) {
360 m := make(map[string]dictField)
361 parseStructFields(struct_, func(key string, sf dictField) {
364 structFields[struct_] = m
367 func getStructFieldForKey(struct_ reflect.Type, key string) (f dictField) {
368 structFieldsMu.Lock()
369 if _, ok := structFields[struct_]; !ok {
370 saveStructFields(struct_)
372 f, ok := structFields[struct_][key]
373 structFieldsMu.Unlock()
375 var discard interface{}
377 Type: reflect.TypeOf(discard),
378 Get: func(reflect.Value) func(reflect.Value) { return func(reflect.Value) {} },
385 func (d *Decoder) parseDict(v reflect.Value) error {
386 // At this point 'd' byte was consumed, now read key/value pairs
389 keyValue := reflect.ValueOf(&keyStr).Elem()
390 ok, err := d.parseValue(keyValue)
392 return fmt.Errorf("error parsing dict key: %w", err)
398 df, err := getDictField(v.Type(), keyStr)
400 return fmt.Errorf("parsing bencode dict into %v: %w", v.Type(), err)
403 // now we need to actually parse it
405 // Discard the value, there's nowhere to put it.
407 if_, ok = d.parseValueInterface()
409 return fmt.Errorf("error parsing value for key %q", keyStr)
412 return fmt.Errorf("missing value for key %q", keyStr)
416 setValue := reflect.New(df.Type).Elem()
417 // log.Printf("parsing into %v", setValue.Type())
418 ok, err = d.parseValue(setValue)
420 var target *UnmarshalTypeError
421 if !(errors.As(err, &target) && df.Tags.IgnoreUnmarshalTypeError()) {
422 return fmt.Errorf("parsing value for key %q: %w", keyStr, err)
426 return fmt.Errorf("missing value for key %q", keyStr)
432 func (d *Decoder) parseList(v reflect.Value) error {
435 // If the list is a singleton of the expected type, use that value. See
436 // https://github.com/anacrolix/torrent/issues/297.
437 l := reflect.New(reflect.SliceOf(v.Type()))
438 if err := d.parseList(l.Elem()); err != nil {
441 if l.Elem().Len() != 1 {
442 return &UnmarshalTypeError{
443 BencodeTypeName: "list",
444 UnmarshalTargetType: v.Type(),
447 v.Set(l.Elem().Index(0))
449 case reflect.Array, reflect.Slice:
450 // We can work with this. Normal case, fallthrough.
455 if v.Kind() == reflect.Slice && i >= v.Len() {
456 v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem())))
460 ok, err := d.parseValue(v.Index(i))
468 _, ok := d.parseValueInterface()
476 if v.Kind() == reflect.Array {
477 z := reflect.Zero(v.Type().Elem())
478 for n := v.Len(); i < n; i++ {
486 if i == 0 && v.Kind() == reflect.Slice {
487 v.Set(reflect.MakeSlice(v.Type(), 0, 0))
492 func (d *Decoder) readOneValue() bool {
493 b, err := d.r.ReadByte()
507 // read until there is nothing to read
508 for d.readOneValue() {
510 // consume 'e' as well
515 d.buf.WriteString("e")
517 if b >= '0' && b <= '9' {
518 start := d.buf.Len() - 1
520 length, err := strconv.ParseInt(bytesAsString(d.buf.Bytes()[start:]), 10, 64)
521 checkForIntParseError(err, d.Offset-1)
523 d.buf.WriteString(":")
524 n, err := io.CopyN(&d.buf, d.r, length)
527 checkForUnexpectedEOF(err, d.Offset)
530 What: errors.New("unexpected I/O error: " + err.Error()),
536 d.raiseUnknownValueType(b, d.Offset-1)
542 func (d *Decoder) parseUnmarshaler(v reflect.Value) bool {
543 if !v.Type().Implements(unmarshalerType) {
544 if v.Addr().Type().Implements(unmarshalerType) {
551 if !d.readOneValue() {
554 m := v.Interface().(Unmarshaler)
555 err := m.UnmarshalBencode(d.buf.Bytes())
557 panic(&UnmarshalerError{v.Type(), err})
562 // Returns true if there was a value and it's now stored in 'v', otherwise
563 // there was an end symbol ("e") and no value was stored.
564 func (d *Decoder) parseValue(v reflect.Value) (bool, error) {
565 // we support one level of indirection at the moment
566 if v.Kind() == reflect.Ptr {
567 // if the pointer is nil, allocate a new element of the type it
570 v.Set(reflect.New(v.Type().Elem()))
575 if d.parseUnmarshaler(v) {
579 // common case: interface{}
580 if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
581 iface, _ := d.parseValueInterface()
582 v.Set(reflect.ValueOf(iface))
586 b, err := d.r.ReadByte()
596 return true, d.parseDict(v)
598 return true, d.parseList(v)
600 return true, d.parseInt(v)
602 if b >= '0' && b <= '9' {
605 // Write the first digit of the length to the buffer.
607 return true, d.parseString(v)
610 d.raiseUnknownValueType(b, d.Offset-1)
615 // An unknown bencode type character was encountered.
616 func (d *Decoder) raiseUnknownValueType(b byte, offset int64) {
619 What: fmt.Errorf("unknown value type %+q", b),
623 func (d *Decoder) parseValueInterface() (interface{}, bool) {
624 b, err := d.r.ReadByte()
634 return d.parseDictInterface(), true
636 return d.parseListInterface(), true
638 return d.parseIntInterface(), true
640 if b >= '0' && b <= '9' {
642 // append first digit of the length to the buffer
644 return d.parseStringInterface(), true
647 d.raiseUnknownValueType(b, d.Offset-1)
652 // Called after 'i', for an arbitrary integer size.
653 func (d *Decoder) parseIntInterface() (ret interface{}) {
654 start := d.Offset - 1
656 if err := d.readInt(); err != nil {
659 n, err := strconv.ParseInt(d.buf.String(), 10, 64)
660 if ne, ok := err.(*strconv.NumError); ok && ne.Err == strconv.ErrRange {
662 _, ok := i.SetString(d.buf.String(), 10)
666 What: errors.New("failed to parse integer"),
671 checkForIntParseError(err, start)
679 func (d *Decoder) readBytes(length int) []byte {
680 b, err := io.ReadAll(io.LimitReader(d.r, int64(length)))
684 if len(b) != length {
685 panic(fmt.Errorf("read %v bytes expected %v", len(b), length))
690 func (d *Decoder) parseStringInterface() string {
691 length, err := d.parseStringLength()
695 b := d.readBytes(int(length))
696 d.Offset += int64(len(b))
698 panic(&SyntaxError{Offset: d.Offset, What: err})
700 return bytesAsString(b)
703 func (d *Decoder) parseDictInterface() interface{} {
704 dict := make(map[string]interface{})
709 keyi, ok := d.parseValueInterface()
714 key, ok := keyi.(string)
718 What: errors.New("non-string key in a dict"),
721 if lastKeyOk && key <= lastKey {
722 d.throwSyntaxError(start, fmt.Errorf("dict keys unsorted: %q <= %q", key, lastKey))
725 valuei, ok := d.parseValueInterface()
727 d.throwSyntaxError(start, fmt.Errorf("dict elem missing value [key=%v]", key))
737 func (d *Decoder) parseListInterface() (list []interface{}) {
738 list = []interface{}{}
739 valuei, ok := d.parseValueInterface()
741 list = append(list, valuei)
742 valuei, ok = d.parseValueInterface()
747 func (d *Decoder) getMaxStrLen() int64 {
748 if d.MaxStrLen == 0 {
749 return DefaultDecodeMaxStrLen