Skip to content

Commit

Permalink
more validation checks
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoPolo committed Feb 6, 2025
1 parent b315fe3 commit 8129048
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
38 changes: 38 additions & 0 deletions component.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package multiaddr

import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -217,6 +218,43 @@ func newComponent(protocol Protocol, bvalue []byte) (Component, error) {
// It ensures that we will be able to call all methods on Component without
// error.
func validateComponent(c Component) (Component, error) {
if c.valueStartIdx > len(c.bytes) {
return Component{}, fmt.Errorf("component valueStartIdx is greater than the length of the component's bytes")
}

if len(c.protocol.VCode) == 0 {
return Component{}, fmt.Errorf("Component is missing its protocol's VCode field")
}
if len(c.bytes) < len(c.protocol.VCode) {
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.bytes), len(c.protocol.VCode))
}
if !bytes.Equal([]byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode) {
return Component{}, fmt.Errorf("component's VCode field is invalid: %v != %v", []byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode)
}
if c.protocol.Size < 0 {
size, n, err := ReadVarintCode([]byte(c.bytes[len(c.protocol.VCode):]))
if err != nil {
return Component{}, err
}
if size != len(c.bytes[c.valueStartIdx:]) {
return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:]))
}

if len(c.protocol.VCode)+n+size != len(c.bytes) {
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+n+size, len(c.bytes))
}
} else {
// Fixed size value
size := c.protocol.Size / 8
if size != len(c.bytes[c.valueStartIdx:]) {
return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:]))
}

if len(c.protocol.VCode)+size != len(c.bytes) {
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+size, len(c.bytes))
}
}

_, err := c.valueAndErr()
if err != nil {
return Component{}, err
Expand Down
3 changes: 3 additions & 0 deletions protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ func AddProtocol(p Protocol) error {
if p.Path && p.Size >= 0 {
return fmt.Errorf("path protocols must have variable-length sizes")
}
if len(p.VCode) == 0 {
return fmt.Errorf("protocol code %d is missing its VCode field", p.Code)
}

Protocols = append(Protocols, p)
protocolsByName[p.Name] = p
Expand Down

0 comments on commit 8129048

Please sign in to comment.