Skip to content

Commit

Permalink
fix(netxlite): consolidate IPv4/IPv6 checking code
Browse files Browse the repository at this point in the history
  • Loading branch information
bassosimone committed May 13, 2022
1 parent e126e73 commit c62b5f1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
20 changes: 8 additions & 12 deletions internal/netxlite/quirks.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package netxlite

import (
"errors"
"net"
"strings"
)

Expand Down Expand Up @@ -52,26 +53,21 @@ func quirkReduceErrors(errorslist []error) error {
// before IPv6. Dialers SHOULD call this code.
//
// It saddens me to have this quirk, but it is here to pair
// with quirkReduceErrors, which assumes that <facepalm>.
// with quirkReduceErrors, which assumes that IPv4 addrs
// appear before IPv6 addrs <facepalm>.
//
// Note: this function will skip any input that is not not
// a valid IPv4 or IPv6 address.
//
// See TODO(https://github.com/ooni/probe/issues/1779).
func quirkSortIPAddrs(addrs []string) (out []string) {
isIPv6 := func(x string) bool {
// This check for identifying IPv6 is discussed
// at https://stackoverflow.com/questions/22751035
// and seems good-enough for our purposes.
return strings.Contains(x, ":")
}
isIPv4 := func(x string) bool {
return !isIPv6(x)
}
for _, addr := range addrs {
if isIPv4(addr) {
if net.ParseIP(addr) != nil && !isIPv6(addr) {
out = append(out, addr)
}
}
for _, addr := range addrs {
if isIPv6(addr) {
if net.ParseIP(addr) != nil && isIPv6(addr) {
out = append(out, addr)
}
}
Expand Down
12 changes: 12 additions & 0 deletions internal/netxlite/quirks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ func TestQuirkSortIPAddrs(t *testing.T) {
addrs := []string{
"::1",
"192.168.1.2",
"x.org", // ensure we skip non IP addrs
"2a00:1450:4002:404::2004",
"example.com", // ensure we skip non IP addrs
"142.250.184.36",
"2604:8800:5000:82:466:38ff:fecb:d46e",
"198.145.29.83",
Expand All @@ -83,4 +85,14 @@ func TestQuirkSortIPAddrs(t *testing.T) {
t.Fatal("expected nil output")
}
})

t.Run("with non-IP addrs", func(t *testing.T) {
addrs := []string{
"example.com",
"x.org",
}
if quirkSortIPAddrs(addrs) != nil {
t.Fatal("expected nil output")
}
})
}

0 comments on commit c62b5f1

Please sign in to comment.