Browse Source

pb: fix IPv6 double brackets in ServerAddress formatting (#8329)

* pb: fix IPv6 double brackets in ServerAddress formatting

* pb: refactor IPv6 tests into table-driven test

* util: add JoinHostPortStr and use it in pb to avoid unsafe port parsing
pull/5637/merge
Chris Lu 7 days ago
committed by GitHub
parent
commit
1e4f30c56f
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 4
      weed/pb/server_address.go
  2. 33
      weed/pb/server_address_test.go
  3. 9
      weed/util/network.go

4
weed/pb/server_address.go

@ -57,7 +57,7 @@ func (sa ServerAddress) ToHttpAddress() string {
sepIndex := strings.LastIndex(string(ports), ".")
if sepIndex >= 0 {
host := string(sa[0:portsSepIndex])
return net.JoinHostPort(host, ports[0:sepIndex])
return util.JoinHostPortStr(host, ports[0:sepIndex])
}
return string(sa)
}
@ -74,7 +74,7 @@ func (sa ServerAddress) ToGrpcAddress() string {
sepIndex := strings.LastIndex(ports, ".")
if sepIndex >= 0 {
host := string(sa[0:portsSepIndex])
return net.JoinHostPort(host, ports[sepIndex+1:])
return util.JoinHostPortStr(host, ports[sepIndex+1:])
}
return ServerToGrpcAddress(string(sa))
}

33
weed/pb/server_address_test.go

@ -34,3 +34,36 @@ func TestServerAddresses_ToAddressMapOrSrv_shouldHandleIPPortList(t *testing.T)
t.Fatalf(`Expected %q, got %q`, expected, d.list)
}
}
func TestIPv6ServerAddressFormatting(t *testing.T) {
testCases := []struct {
name string
sa ServerAddress
expectedHttp string
expectedGrpc string
}{
{
name: "unbracketed IPv6",
sa: NewServerAddress("2001:db8::1", 8080, 18080),
expectedHttp: "[2001:db8::1]:8080",
expectedGrpc: "[2001:db8::1]:18080",
},
{
name: "bracketed IPv6",
sa: NewServerAddressWithGrpcPort("[2001:db8::1]:8080", 18080),
expectedHttp: "[2001:db8::1]:8080",
expectedGrpc: "[2001:db8::1]:18080",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
if httpAddr := tc.sa.ToHttpAddress(); httpAddr != tc.expectedHttp {
t.Errorf("%s: ToHttpAddress() = %s, want %s", tc.name, httpAddr, tc.expectedHttp)
}
if grpcAddr := tc.sa.ToGrpcAddress(); grpcAddr != tc.expectedGrpc {
t.Errorf("%s: ToGrpcAddress() = %s, want %s", tc.name, grpcAddr, tc.expectedGrpc)
}
})
}
}

9
weed/util/network.go

@ -58,11 +58,14 @@ func selectIpV4(netInterfaces []net.Interface, isIpV4 bool) string {
}
func JoinHostPort(host string, port int) string {
portStr := strconv.Itoa(port)
return JoinHostPortStr(host, strconv.Itoa(port))
}
func JoinHostPortStr(host string, port string) string {
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
return host + ":" + portStr
return host + ":" + port
}
return net.JoinHostPort(host, portStr)
return net.JoinHostPort(host, port)
}
// GetVolumeServerId returns the volume server ID.

Loading…
Cancel
Save