Browse code

Add validate the input mac address on docker run command

Signed-off-by: Lei Jitang <leijitang@huawei.com>

Lei Jitang authored on 2015/02/28 00:27:12
Showing 4 changed files
... ...
@@ -2355,6 +2355,20 @@ func TestRunInspectMacAddress(t *testing.T) {
2355 2355
 	logDone("run - inspecting MAC address")
2356 2356
 }
2357 2357
 
2358
+// test docker run use a invalid mac address
2359
+func TestRunWithInvalidMacAddress(t *testing.T) {
2360
+	defer deleteAllContainers()
2361
+
2362
+	runCmd := exec.Command(dockerBinary, "run", "--mac-address", "92:d0:c6:0a:29", "busybox")
2363
+	out, _, err := runCommandWithOutput(runCmd)
2364
+	//use a invalid mac address should with a error out
2365
+	if err == nil || !strings.Contains(out, "is not a valid mac address") {
2366
+		t.Fatalf("run with an invalid --mac-address should with error out")
2367
+	}
2368
+
2369
+	logDone("run - can't use an invalid mac address")
2370
+}
2371
+
2358 2372
 func TestRunDeallocatePortOnMissingIptablesRule(t *testing.T) {
2359 2373
 	defer deleteAllContainers()
2360 2374
 	testRequires(t, SameHostDaemon)
... ...
@@ -183,6 +183,15 @@ func ValidateIPAddress(val string) (string, error) {
183 183
 	return "", fmt.Errorf("%s is not an ip address", val)
184 184
 }
185 185
 
186
+func ValidateMACAddress(val string) (string, error) {
187
+	_, err := net.ParseMAC(strings.TrimSpace(val))
188
+	if err != nil {
189
+		return "", err
190
+	} else {
191
+		return val, nil
192
+	}
193
+}
194
+
186 195
 // Validates domain for resolvconf search configuration.
187 196
 // A zero length domain is represented by .
188 197
 func ValidateDnsSearch(val string) (string, error) {
... ...
@@ -28,6 +28,20 @@ func TestValidateIPAddress(t *testing.T) {
28 28
 
29 29
 }
30 30
 
31
+func TestValidateMACAddress(t *testing.T) {
32
+	if _, err := ValidateMACAddress(`92:d0:c6:0a:29:33`); err != nil {
33
+		t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:29:33`) got %s", err)
34
+	}
35
+
36
+	if _, err := ValidateMACAddress(`92:d0:c6:0a:33`); err == nil {
37
+		t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:33`) succeeded; expected failure on invalid MAC")
38
+	}
39
+
40
+	if _, err := ValidateMACAddress(`random invalid string`); err == nil {
41
+		t.Fatalf("ValidateMACAddress(`random invalid string`) succeeded; expected failure on invalid MAC")
42
+	}
43
+}
44
+
31 45
 func TestListOpts(t *testing.T) {
32 46
 	o := NewListOpts(nil)
33 47
 	o.Set("foo")
... ...
@@ -94,6 +94,12 @@ func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe
94 94
 		return nil, nil, cmd, ErrInvalidWorkingDirectory
95 95
 	}
96 96
 
97
+	// Validate the input mac address
98
+	if *flMacAddress != "" {
99
+		if _, err := opts.ValidateMACAddress(*flMacAddress); err != nil {
100
+			return nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress)
101
+		}
102
+	}
97 103
 	var (
98 104
 		attachStdin  = flAttach.Get("stdin")
99 105
 		attachStdout = flAttach.Get("stdout")