diff --git a/cli/command/container/kill.go b/cli/command/container/kill.go index feedbc0111..e83a580bd7 100644 --- a/cli/command/container/kill.go +++ b/cli/command/container/kill.go @@ -26,6 +26,11 @@ func NewKillCommand(dockerCli command.Cli) *cobra.Command { Short: "Kill one or more running containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + for _, name := range args { + if !cli.CheckContainerName(name) { + return fmt.Errorf("container name %s is invalid", name) + } + } opts.containers = args return runKill(dockerCli, &opts) }, diff --git a/cli/command/container/rm.go b/cli/command/container/rm.go index 2dcd4b6ace..cf0be9c51b 100644 --- a/cli/command/container/rm.go +++ b/cli/command/container/rm.go @@ -29,6 +29,11 @@ func NewRmCommand(dockerCli command.Cli) *cobra.Command { Short: "Remove one or more containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + for _, name := range args { + if !cli.CheckContainerName(name) { + return fmt.Errorf("container name %s is invalid", name) + } + } opts.containers = args return runRm(dockerCli, &opts) }, diff --git a/cli/command/container/stop.go b/cli/command/container/stop.go index e299175436..13ddcfd5bc 100644 --- a/cli/command/container/stop.go +++ b/cli/command/container/stop.go @@ -28,6 +28,11 @@ func NewStopCommand(dockerCli command.Cli) *cobra.Command { Short: "Stop one or more running containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + for _, name := range args { + if !cli.CheckContainerName(name) { + return fmt.Errorf("container name %s is invalid", name) + } + } opts.containers = args opts.timeChanged = cmd.Flags().Changed("time") return runStop(dockerCli, &opts) diff --git a/cli/names.go b/cli/names.go new file mode 100644 index 0000000000..4b7c687125 --- /dev/null +++ b/cli/names.go @@ -0,0 +1,19 @@ +package cli + +import ( + "strings" + + "github.com/docker/cli/cli/names" +) + +var ( + validContainerNamePattern = names.RestrictedNamePattern +) + +// CheckContainerName check container's name is valid or not +func CheckContainerName(name string) bool { + if len(name) == 0 { + return false + } + return validContainerNamePattern.MatchString(strings.TrimPrefix(name, "/")) +} diff --git a/cli/names/names.go b/cli/names/names.go new file mode 100644 index 0000000000..1d77e3ab14 --- /dev/null +++ b/cli/names/names.go @@ -0,0 +1,11 @@ +package names + +import ( + "regexp" +) + +// RestrictedNameChars collects the characters allowed to represent a name, normally used to validate container and volume names. +const RestrictedNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]` + +// RestrictedNamePattern is a regular expression to validate names against the collection of restricted characters. +var RestrictedNamePattern = regexp.MustCompile(`^` + RestrictedNameChars + `+$`)