Browse code

Allow IPv6 addresses in ExtraHosts option settings

Since the separator for extra host settings (for /etc/hosts in a
container) is a ":", the code that handles extra hosts needed to only
split on the first ":" to preserve IPv6 addresses which are passed via
the command line settings as well as stored in the JSON container
config.

Docker-DCO-1.1-Signed-off-by: Phil Estes <estesp@linux.vnet.ibm.com> (github: estesp)

Phil Estes authored on 2015/02/05 00:20:28
Showing 3 changed files
... ...
@@ -461,7 +461,8 @@ func (container *Container) buildHostsFiles(IP string) error {
461 461
 	}
462 462
 
463 463
 	for _, extraHost := range container.hostConfig.ExtraHosts {
464
-		parts := strings.Split(extraHost, ":")
464
+		// allow IPv6 addresses in extra hosts; only split on first ":"
465
+		parts := strings.SplitN(extraHost, ":", 2)
465 466
 		extraContent = append(extraContent, etchosts.Record{Hosts: parts[0], IP: parts[1]})
466 467
 	}
467 468
 
... ...
@@ -204,7 +204,8 @@ func validateDomain(val string) (string, error) {
204 204
 }
205 205
 
206 206
 func ValidateExtraHost(val string) (string, error) {
207
-	arr := strings.Split(val, ":")
207
+	// allow for IPv6 addresses in extra hosts by only splitting on first ":"
208
+	arr := strings.SplitN(val, ":", 2)
208 209
 	if len(arr) != 2 || len(arr[0]) == 0 {
209 210
 		return "", fmt.Errorf("bad format for add-host: %s", val)
210 211
 	}
... ...
@@ -104,3 +104,31 @@ func TestValidateDnsSearch(t *testing.T) {
104 104
 		}
105 105
 	}
106 106
 }
107
+
108
+func TestValidateExtraHosts(t *testing.T) {
109
+	valid := []string{
110
+		`myhost:192.168.0.1`,
111
+		`thathost:10.0.2.1`,
112
+		`anipv6host:2003:ab34:e::1`,
113
+		`ipv6local:::1`,
114
+	}
115
+
116
+	invalid := []string{
117
+		`myhost:192.notanipaddress.1`,
118
+		`thathost-nosemicolon10.0.0.1`,
119
+		`anipv6host:::::1`,
120
+		`ipv6local:::0::`,
121
+	}
122
+
123
+	for _, extrahost := range valid {
124
+		if _, err := ValidateExtraHost(extrahost); err != nil {
125
+			t.Fatalf("ValidateExtraHost(`"+extrahost+"`) should succeed: error %v", err)
126
+		}
127
+	}
128
+
129
+	for _, extrahost := range invalid {
130
+		if _, err := ValidateExtraHost(extrahost); err == nil {
131
+			t.Fatalf("ValidateExtraHost(`" + extrahost + "`) should have failed validation")
132
+		}
133
+	}
134
+}