|
17 | 17 | package docker |
18 | 18 |
|
19 | 19 | import ( |
| 20 | + "net" |
20 | 21 | "net/http" |
| 22 | + |
| 23 | + "github.com/pkg/errors" |
21 | 24 | ) |
22 | 25 |
|
23 | 26 | // HostCapabilities represent the capabilities of the registry |
@@ -202,12 +205,41 @@ func MatchAllHosts(string) (bool, error) { |
202 | 205 |
|
203 | 206 | // MatchLocalhost is a host match function which returns true for |
204 | 207 | // localhost. |
| 208 | +// |
| 209 | +// Note: this does not handle matching of ip addresses in octal, |
| 210 | +// decimal or hex form. |
205 | 211 | 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 |
209 | 231 | } |
| 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" |
210 | 241 | } |
211 | | - return host == "::1", nil |
| 242 | + ip := net.ParseIP(h) |
212 | 243 |
|
| 244 | + return ip.IsLoopback(), nil |
213 | 245 | } |
0 commit comments