Skip to content

Commit b395f2f

Browse files
authored
Merge pull request #5160 from MadhavJivrajani/master
Use net.IP.IsLoopback() to match loopback addresses
2 parents a0cc9b4 + 8f863af commit b395f2f

2 files changed

Lines changed: 42 additions & 5 deletions

File tree

remotes/docker/registry.go

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717
package docker
1818

1919
import (
20+
"net"
2021
"net/http"
22+
23+
"github.com/pkg/errors"
2124
)
2225

2326
// HostCapabilities represent the capabilities of the registry
@@ -202,12 +205,41 @@ func MatchAllHosts(string) (bool, error) {
202205

203206
// MatchLocalhost is a host match function which returns true for
204207
// localhost.
208+
//
209+
// Note: this does not handle matching of ip addresses in octal,
210+
// decimal or hex form.
205211
func MatchLocalhost(host string) (bool, error) {
206-
for _, s := range []string{"localhost", "127.0.0.1", "[::1]"} {
207-
if len(host) >= len(s) && host[0:len(s)] == s && (len(host) == len(s) || host[len(s)] == ':') {
208-
return true, nil
212+
switch {
213+
case host == "::1":
214+
return true, nil
215+
case host == "[::1]":
216+
return true, nil
217+
}
218+
h, p, err := net.SplitHostPort(host)
219+
220+
// addrError helps distinguish between errors of form
221+
// "no colon in address" and "too many colons in address".
222+
// The former is fine as the host string need not have a
223+
// port. Latter needs to be handled.
224+
addrError := &net.AddrError{
225+
Err: "missing port in address",
226+
Addr: host,
227+
}
228+
if err != nil {
229+
if err.Error() != addrError.Error() {
230+
return false, err
209231
}
232+
// host string without any port specified
233+
h = host
234+
} else if len(p) == 0 {
235+
return false, errors.New("invalid host name format")
236+
}
237+
238+
// use ipv4 dotted decimal for further checking
239+
if h == "localhost" {
240+
h = "127.0.0.1"
210241
}
211-
return host == "::1", nil
242+
ip := net.ParseIP(h)
212243

244+
return ip.IsLoopback(), nil
213245
}

remotes/docker/registry_test.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,19 @@ func TestMatchLocalhost(t *testing.T) {
5252
match bool
5353
}{
5454
{"", false},
55-
{"127.1.1.1", false},
55+
{"127.1.1.1", true},
5656
{"127.0.0.1", true},
57+
{"127.256.0.1", false}, // test MatchLocalhost does not panic on invalid ip
58+
{"127.23.34.52", true},
5759
{"127.0.0.1:5000", true},
5860
{"registry.org", false},
61+
{"126.example.com", false},
5962
{"localhost", true},
6063
{"localhost:5000", true},
6164
{"[127:0:0:1]", false},
6265
{"[::1]", true},
66+
{"[::1]:", false}, // invalid ip
67+
{"127.0.1.1:", false}, // invalid ip
6368
{"[::1]:5000", true},
6469
{"::1", true},
6570
} {

0 commit comments

Comments
 (0)