]> Sergey Matveev's repositories - btrtrc.git/blobdiff - webtorrent/tracker_protocol.go
Add generalized decodeJsonByteString and a fuzz target for it
[btrtrc.git] / webtorrent / tracker_protocol.go
index b6ac1a5b835064b22bffb902df75632b97834047..14be67e452fee9386c91417e65f1a6680acfae34 100644 (file)
@@ -48,6 +48,17 @@ func binaryToJsonString(b []byte) string {
 }
 
 func jsonStringToInfoHash(s string) (ih [20]byte, err error) {
+       b, err := decodeJsonByteString(s, ih[:0])
+       if err != nil {
+               return
+       }
+       if len(b) != len(ih) {
+               err = fmt.Errorf("string decoded to %v bytes", len(b))
+       }
+       return
+}
+
+func decodeJsonByteString(s string, b []byte) ([]byte, error) {
        defer func() {
                r := recover()
                if r == nil {
@@ -55,12 +66,11 @@ func jsonStringToInfoHash(s string) (ih [20]byte, err error) {
                }
                panic(fmt.Sprintf("%q", s))
        }()
-       for i, c := range []rune(s) {
+       for _, c := range []rune(s) {
                if c < 0 || c > math.MaxUint8 {
-                       err = fmt.Errorf("bad infohash string: %v", s)
-                       return
+                       return b, fmt.Errorf("rune out of bounds: %v", c)
                }
-               ih[i] = byte(c)
+               b = append(b, byte(c))
        }
-       return
+       return b, nil
 }