Skip to content

Commit

Permalink
fix: panic in ParseIPv4 when len(dst) > 4
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed Mar 29, 2024
1 parent 9c3915b commit 072dbe8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
6 changes: 1 addition & 5 deletions bytesconv.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,15 +73,11 @@ func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error) {
if len(ipStr) == 0 {
return dst, errEmptyIPStr
}
if len(dst) < net.IPv4len {
if len(dst) < net.IPv4len || len(dst) > net.IPv4len {
dst = make([]byte, net.IPv4len)
}
copy(dst, net.IPv4zero)
dst = dst.To4()
if dst == nil {
// developer sanity-check
panic("BUG: dst must not be nil")
}

b := ipStr
for i := 0; i < 3; i++ {
Expand Down
24 changes: 15 additions & 9 deletions bytesconv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,27 @@ func testAppendHTMLEscape(t *testing.T, s, expectedS string) {
func TestParseIPv4(t *testing.T) {
t.Parallel()

testParseIPv4(t, "0.0.0.0", true)
testParseIPv4(t, "255.255.255.255", true)
testParseIPv4(t, "123.45.67.89", true)
testParseIPv4(t, net.IP{0}, "0.0.0.0", true)
testParseIPv4(t, nil, "0.0.0.0", true)
testParseIPv4(t, net.IP{0, 0, 0, 0, 0}, "0.0.0.0", true)
testParseIPv4(t, nil, "255.255.255.255", true)
testParseIPv4(t, nil, "123.45.67.89", true)

// ipv6 shouldn't work
testParseIPv4(t, "2001:4860:0:2001::68", false)
testParseIPv4(t, nil, "2001:4860:0:2001::68", false)

// invalid ip
testParseIPv4(t, "foobar", false)
testParseIPv4(t, "1.2.3", false)
testParseIPv4(t, "123.456.789.11", false)
testParseIPv4(t, nil, "", false)
testParseIPv4(t, nil, "foobar", false)
testParseIPv4(t, nil, "1.2.3", false)
testParseIPv4(t, nil, "123.456.789.11", false)
testParseIPv4(t, nil, "b.1.2.3", false)
testParseIPv4(t, nil, "1.2.3.b", false)
testParseIPv4(t, nil, "1.2.3.456", false)
}

func testParseIPv4(t *testing.T, ipStr string, isValid bool) {
ip, err := ParseIPv4(nil, []byte(ipStr))
func testParseIPv4(t *testing.T, dst net.IP, ipStr string, isValid bool) {
ip, err := ParseIPv4(dst, []byte(ipStr))
if isValid {
if err != nil {
t.Fatalf("unexpected error when parsing ip %q: %v", ipStr, err)
Expand Down

0 comments on commit 072dbe8

Please sign in to comment.