cleanup panics and make NewFromBytes faster

This commit is contained in:
Jeromy 2016-04-29 14:16:41 -07:00
parent 41d1117052
commit 9c4a0baf6d
4 changed files with 100 additions and 48 deletions

View File

@ -3,7 +3,6 @@ package multiaddr
import ( import (
"encoding/base32" "encoding/base32"
"encoding/binary" "encoding/binary"
"errors"
"fmt" "fmt"
"net" "net"
"strconv" "strconv"
@ -52,27 +51,42 @@ func stringToBytes(s string) ([]byte, error) {
return b, nil return b, nil
} }
func bytesToString(b []byte) (ret string, err error) { func validateBytes(b []byte) (err error) {
// panic handler, in case we try accessing bytes incorrectly. // panic handler, in case we try accessing bytes incorrectly.
defer func() { for len(b) > 0 {
if e := recover(); e != nil { code, n, err := ReadVarintCode(b)
ret = "" b = b[n:]
switch e := e.(type) { p := ProtocolWithCode(code)
case error: if p.Code == 0 {
err = e return fmt.Errorf("no protocol with code %d", code)
case string:
err = errors.New(e)
default:
err = fmt.Errorf("%v", e)
}
} }
}()
if p.Size == 0 {
continue
}
size, err := sizeForAddr(p, b)
if err != nil {
return err
}
if len(b) < size {
return fmt.Errorf("invalid value for size")
}
b = b[size:]
}
return nil
}
func bytesToString(b []byte) (ret string, err error) {
s := "" s := ""
for len(b) > 0 { for len(b) > 0 {
code, n, err := ReadVarintCode(b)
if err != nil {
return "", err
}
code, n := ReadVarintCode(b)
b = b[n:] b = b[n:]
p := ProtocolWithCode(code) p := ProtocolWithCode(code)
if p.Code == 0 { if p.Code == 0 {
@ -84,7 +98,11 @@ func bytesToString(b []byte) (ret string, err error) {
continue continue
} }
size := sizeForAddr(p, b) size, err := sizeForAddr(p, b)
if err != nil {
return "", err
}
a, err := addressBytesToString(p, b[:size]) a, err := addressBytesToString(p, b[:size])
if err != nil { if err != nil {
return "", err return "", err
@ -98,36 +116,40 @@ func bytesToString(b []byte) (ret string, err error) {
return s, nil return s, nil
} }
func sizeForAddr(p Protocol, b []byte) int { func sizeForAddr(p Protocol, b []byte) (int, error) {
switch { switch {
case p.Size > 0: case p.Size > 0:
return (p.Size / 8) return (p.Size / 8), nil
case p.Size == 0: case p.Size == 0:
return 0 return 0, nil
default: default:
size, n := ReadVarintCode(b) size, n, err := ReadVarintCode(b)
return size + n if err != nil {
return 0, err
}
return size + n, nil
} }
} }
func bytesSplit(b []byte) (ret [][]byte, err error) { func bytesSplit(b []byte) ([][]byte, error) {
// panic handler, in case we try accessing bytes incorrectly. var ret [][]byte
defer func() {
if e := recover(); e != nil {
ret = [][]byte{}
err = e.(error)
}
}()
ret = [][]byte{}
for len(b) > 0 { for len(b) > 0 {
code, n := ReadVarintCode(b) code, n, err := ReadVarintCode(b)
if err != nil {
return nil, err
}
p := ProtocolWithCode(code) p := ProtocolWithCode(code)
if p.Code == 0 { if p.Code == 0 {
return [][]byte{}, fmt.Errorf("no protocol with code %d", b[0]) return nil, fmt.Errorf("no protocol with code %d", b[0])
}
size, err := sizeForAddr(p, b[n:])
if err != nil {
return nil, err
} }
size := sizeForAddr(p, b[n:])
length := n + size length := n + size
ret = append(ret, b[:length]) ret = append(ret, b[:length])
b = b[length:] b = b[length:]
@ -228,10 +250,14 @@ func addressBytesToString(p Protocol, b []byte) (string, error) {
case P_IPFS: // ipfs case P_IPFS: // ipfs
// the address is a varint-prefixed multihash string representation // the address is a varint-prefixed multihash string representation
size, n := ReadVarintCode(b) size, n, err := ReadVarintCode(b)
if err != nil {
return "", err
}
b = b[n:] b = b[n:]
if len(b) != size { if len(b) != size {
panic("inconsistent lengths") return "", fmt.Errorf("inconsistent lengths")
} }
m, err := mh.Cast(b) m, err := mh.Cast(b)
if err != nil { if err != nil {

View File

@ -23,11 +23,11 @@ func NewMultiaddr(s string) (Multiaddr, error) {
// NewMultiaddrBytes initializes a Multiaddr from a byte representation. // NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string. // It validates it as an input string.
func NewMultiaddrBytes(b []byte) (Multiaddr, error) { func NewMultiaddrBytes(b []byte) (Multiaddr, error) {
s, err := bytesToString(b) if err := validateBytes(b); err != nil {
if err != nil {
return nil, err return nil, err
} }
return NewMultiaddr(s)
return &multiaddr{bytes: b}, nil
} }
// Equal tests whether two multiaddrs are equal // Equal tests whether two multiaddrs are equal
@ -64,11 +64,14 @@ func (m *multiaddr) Protocols() []Protocol {
} }
}() }()
size := 0 var ps []Protocol
ps := []Protocol{} b := m.bytes
b := m.bytes[:]
for len(b) > 0 { for len(b) > 0 {
code, n := ReadVarintCode(b) code, n, err := ReadVarintCode(b)
if err != nil {
panic(err)
}
p := ProtocolWithCode(code) p := ProtocolWithCode(code)
if p.Code == 0 { if p.Code == 0 {
// this is a panic (and not returning err) because this should've been // this is a panic (and not returning err) because this should've been
@ -78,7 +81,7 @@ func (m *multiaddr) Protocols() []Protocol {
ps = append(ps, p) ps = append(ps, p)
b = b[n:] b = b[n:]
size = sizeForAddr(p, b) size, err := sizeForAddr(p, b)
b = b[size:] b = b[size:]
} }
return ps return ps

View File

@ -3,7 +3,9 @@ package multiaddr
import ( import (
"bytes" "bytes"
"encoding/hex" "encoding/hex"
"math/rand"
"testing" "testing"
"time"
) )
func newMultiaddr(t *testing.T, a string) Multiaddr { func newMultiaddr(t *testing.T, a string) Multiaddr {
@ -342,3 +344,21 @@ func TestGetValue(t *testing.T) {
assertValueForProto(t, a, P_UDP, "12345") assertValueForProto(t, a, P_UDP, "12345")
assertValueForProto(t, a, P_UTP, "") assertValueForProto(t, a, P_UTP, "")
} }
func TestFuzzBytes(t *testing.T) {
rand.Seed(time.Now().UnixNano())
// Bump up these numbers if you want to stress this
buf := make([]byte, 256)
for i := 0; i < 2000; i++ {
l := rand.Intn(len(buf))
rand.Read(buf[:l])
// just checking that it doesnt panic
ma, err := NewMultiaddrBytes(buf[:l])
if err == nil {
// for any valid multiaddrs, make sure these calls don't panic
ma.String()
ma.Protocols()
}
}
}

View File

@ -117,16 +117,19 @@ func CodeToVarint(num int) []byte {
// VarintToCode converts a varint-encoded []byte to an integer protocol code // VarintToCode converts a varint-encoded []byte to an integer protocol code
func VarintToCode(buf []byte) int { func VarintToCode(buf []byte) int {
num, _ := ReadVarintCode(buf) num, _, err := ReadVarintCode(buf)
if err != nil {
panic(err)
}
return num return num
} }
// ReadVarintCode reads a varint code from the beginning of buf. // ReadVarintCode reads a varint code from the beginning of buf.
// returns the code, and the number of bytes read. // returns the code, and the number of bytes read.
func ReadVarintCode(buf []byte) (int, int) { func ReadVarintCode(buf []byte) (int, int, error) {
num, n := binary.Uvarint(buf) num, n := binary.Uvarint(buf)
if n < 0 { if n < 0 {
panic("varints larger than uint64 not yet supported") return 0, 0, fmt.Errorf("varints larger than uint64 not yet supported")
} }
return int(num), n return int(num), n, nil
} }