ValidateExtraHost validates that the specified string is a valid extrahost and returns it. ExtraHost is in the form of name:ip or name=ip, where the ip has to be a valid ip (IPv4 or IPv6). The address may be enclosed in square brackets. For example: my-hostname:127.0.0.1 my-hostname:::1 my-host
(val string)
| 160 | // argument to use the ':' separator and strip square brackets enclosing the |
| 161 | // address. |
| 162 | func ValidateExtraHost(val string) (string, error) { |
| 163 | k, v, ok := strings.Cut(val, "=") |
| 164 | if !ok { |
| 165 | // allow for IPv6 addresses in extra hosts by only splitting on first ":" |
| 166 | k, v, ok = strings.Cut(val, ":") |
| 167 | } |
| 168 | // Check that a hostname was given, and that it doesn't contain a ":". (Colon |
| 169 | // isn't allowed in a hostname, along with many other characters. It's |
| 170 | // special-cased here because the API server doesn't know about '=' separators in |
| 171 | // '--add-host'. So, it'll split at the first colon and generate a strange error |
| 172 | // message.) |
| 173 | if !ok || k == "" || strings.Contains(k, ":") { |
| 174 | return "", fmt.Errorf("bad format for add-host: %q", val) |
| 175 | } |
| 176 | // Skip IPaddr validation for "host-gateway" string |
| 177 | if v != hostGatewayName { |
| 178 | // If the address is enclosed in square brackets, extract it (for IPv6, but |
| 179 | // permit it for IPv4 as well; we don't know the address family here, but it's |
| 180 | // unambiguous). |
| 181 | if len(v) > 2 && v[0] == '[' && v[len(v)-1] == ']' { |
| 182 | v = v[1 : len(v)-1] |
| 183 | } |
| 184 | // ValidateIPAddress returns the address in canonical form (for example, |
| 185 | // 0:0:0:0:0:0:0:1 -> ::1). But, stick with the original form, to avoid |
| 186 | // surprising a user who's expecting to see the address they supplied in the |
| 187 | // output of 'docker inspect' or '/etc/hosts'. |
| 188 | if _, err := ValidateIPAddress(v); err != nil { |
| 189 | return "", fmt.Errorf("invalid IP address in add-host: %q", v) |
| 190 | } |
| 191 | } |
| 192 | // This result is passed directly to the API, the daemon doesn't accept the '=' |
| 193 | // separator or an address enclosed in brackets. So, construct something it can |
| 194 | // understand. |
| 195 | return k + ":" + v, nil |
| 196 | } |
searching dependent graphs…