diff --git a/api/client/commands.go b/api/client/commands.go index 947e241b4b..84e426ef77 100644 --- a/api/client/commands.go +++ b/api/client/commands.go @@ -441,7 +441,7 @@ func (cli *DockerCli) CmdLogin(args ...string) error { authconfig.ServerAddress = serverAddress cli.configFile.Configs[serverAddress] = authconfig - stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], false) + stream, statusCode, err := cli.call("POST", "/auth", cli.configFile.Configs[serverAddress], nil) if statusCode == 401 { delete(cli.configFile.Configs, serverAddress) registry.SaveConfig(cli.configFile) @@ -527,7 +527,7 @@ func (cli *DockerCli) CmdVersion(args ...string) error { } fmt.Fprintf(cli.out, "OS/Arch (client): %s/%s\n", runtime.GOOS, runtime.GOARCH) - body, _, err := readBody(cli.call("GET", "/version", nil, false)) + body, _, err := readBody(cli.call("GET", "/version", nil, nil)) if err != nil { return err } @@ -559,7 +559,7 @@ func (cli *DockerCli) CmdInfo(args ...string) error { cmd.Require(flag.Exact, 0) utils.ParseFlags(cmd, args, false) - body, _, err := readBody(cli.call("GET", "/info", nil, false)) + body, _, err := readBody(cli.call("GET", "/info", nil, nil)) if err != nil { return err } @@ -696,7 +696,7 @@ func (cli *DockerCli) CmdStop(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, false)) + _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to stop one or more containers") @@ -719,7 +719,7 @@ func (cli *DockerCli) CmdRestart(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, false)) + _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to restart one or more containers") @@ -748,7 +748,7 @@ func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { if sig == "" { log.Errorf("Unsupported signal: %v. Discarding.", s) } - if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, nil)); err != nil { log.Debugf("Error sending signal: %s", err) } } @@ -774,7 +774,7 @@ func (cli *DockerCli) CmdStart(args ...string) error { return fmt.Errorf("You cannot start and attach multiple containers at once.") } - stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false) + stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) if err != nil { return err } @@ -834,7 +834,7 @@ func (cli *DockerCli) CmdStart(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, false)) + _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, nil)) if err != nil { if !*attach && !*openStdin { // attach and openStdin is false means it could be starting multiple containers @@ -882,7 +882,7 @@ func (cli *DockerCli) CmdUnpause(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to unpause container named %s", name) } else { @@ -899,7 +899,7 @@ func (cli *DockerCli) CmdPause(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to pause container named %s", name) } else { @@ -922,7 +922,7 @@ func (cli *DockerCli) CmdRename(args ...string) error { old_name := cmd.Arg(0) new_name := cmd.Arg(1) - if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", old_name, new_name), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", old_name, new_name), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) return fmt.Errorf("Error: failed to rename container named %s", old_name) } @@ -951,7 +951,7 @@ func (cli *DockerCli) CmdInspect(args ...string) error { status := 0 for _, name := range cmd.Args() { - obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, false)) + obj, _, err := readBody(cli.call("GET", "/containers/"+name+"/json", nil, nil)) if err != nil { if strings.Contains(err.Error(), "Too many") { fmt.Fprintf(cli.err, "Error: %v", err) @@ -959,7 +959,7 @@ func (cli *DockerCli) CmdInspect(args ...string) error { continue } - obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, false)) + obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, nil)) if err != nil { if strings.Contains(err.Error(), "No such") { fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name) @@ -1022,7 +1022,7 @@ func (cli *DockerCli) CmdTop(args ...string) error { val.Set("ps_args", strings.Join(cmd.Args()[1:], " ")) } - stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, false) + stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil) if err != nil { return err } @@ -1048,7 +1048,7 @@ func (cli *DockerCli) CmdPort(args ...string) error { cmd.Require(flag.Min, 1) utils.ParseFlags(cmd, args, true) - stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, false) + stream, _, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) if err != nil { return err } @@ -1113,7 +1113,7 @@ func (cli *DockerCli) CmdRmi(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, false)) + body, _, err := readBody(cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to remove one or more images") @@ -1144,7 +1144,7 @@ func (cli *DockerCli) CmdHistory(args ...string) error { utils.ParseFlags(cmd, args, true) - body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, false)) + body, _, err := readBody(cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, nil)) if err != nil { return err } @@ -1211,7 +1211,7 @@ func (cli *DockerCli) CmdRm(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, false)) + _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to remove one or more containers") @@ -1232,7 +1232,7 @@ func (cli *DockerCli) CmdKill(args ...string) error { var encounteredError error for _, name := range cmd.Args() { - if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) encounteredError = fmt.Errorf("Error: failed to kill one or more containers") } else { @@ -1317,32 +1317,8 @@ func (cli *DockerCli) CmdPush(args ...string) error { v := url.Values{} v.Set("tag", tag) - push := func(authConfig registry.AuthConfig) error { - buf, err := json.Marshal(authConfig) - if err != nil { - return err - } - registryAuthHeader := []string{ - base64.URLEncoding.EncodeToString(buf), - } - - return cli.stream("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, map[string][]string{ - "X-Registry-Auth": registryAuthHeader, - }) - } - - if err := push(authConfig); err != nil { - if strings.Contains(err.Error(), "Status 401") { - fmt.Fprintln(cli.out, "\nPlease login prior to push:") - if err := cli.CmdLogin(repoInfo.Index.GetAuthConfigKey()); err != nil { - return err - } - authConfig := cli.configFile.ResolveAuthConfig(repoInfo.Index) - return push(authConfig) - } - return err - } - return nil + _, _, err = cli.clientRequestAttemptLogin("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, repoInfo.Index, "push") + return err } func (cli *DockerCli) CmdPull(args ...string) error { @@ -1375,36 +1351,8 @@ func (cli *DockerCli) CmdPull(args ...string) error { cli.LoadConfigFile() - // Resolve the Auth config relevant for this server - authConfig := cli.configFile.ResolveAuthConfig(repoInfo.Index) - - pull := func(authConfig registry.AuthConfig) error { - buf, err := json.Marshal(authConfig) - if err != nil { - return err - } - registryAuthHeader := []string{ - base64.URLEncoding.EncodeToString(buf), - } - - return cli.stream("POST", "/images/create?"+v.Encode(), nil, cli.out, map[string][]string{ - "X-Registry-Auth": registryAuthHeader, - }) - } - - if err := pull(authConfig); err != nil { - if strings.Contains(err.Error(), "Status 401") { - fmt.Fprintln(cli.out, "\nPlease login prior to pull:") - if err := cli.CmdLogin(repoInfo.Index.GetAuthConfigKey()); err != nil { - return err - } - authConfig := cli.configFile.ResolveAuthConfig(repoInfo.Index) - return pull(authConfig) - } - return err - } - - return nil + _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull") + return err } func (cli *DockerCli) CmdImages(args ...string) error { @@ -1448,7 +1396,7 @@ func (cli *DockerCli) CmdImages(args ...string) error { v.Set("filters", filterJson) } - body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false)) + body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, nil)) if err != nil { return err } @@ -1526,7 +1474,7 @@ func (cli *DockerCli) CmdImages(args ...string) error { v.Set("all", "1") } - body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, false)) + body, _, err := readBody(cli.call("GET", "/images/json?"+v.Encode(), nil, nil)) if err != nil { return err @@ -1724,7 +1672,7 @@ func (cli *DockerCli) CmdPs(args ...string) error { v.Set("filters", filterJson) } - body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, false)) + body, _, err := readBody(cli.call("GET", "/containers/json?"+v.Encode(), nil, nil)) if err != nil { return err } @@ -1865,7 +1813,7 @@ func (cli *DockerCli) CmdCommit(args ...string) error { return err } } - stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, false) + stream, _, err := cli.call("POST", "/commit?"+v.Encode(), config, nil) if err != nil { return err } @@ -1976,7 +1924,7 @@ func (cli *DockerCli) CmdDiff(args ...string) error { utils.ParseFlags(cmd, args, true) - body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, false)) + body, _, err := readBody(cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil)) if err != nil { return err @@ -2014,7 +1962,7 @@ func (cli *DockerCli) CmdLogs(args ...string) error { name := cmd.Arg(0) - stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false) + stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, nil) if err != nil { return err } @@ -2055,7 +2003,7 @@ func (cli *DockerCli) CmdAttach(args ...string) error { utils.ParseFlags(cmd, args, true) name := cmd.Arg(0) - stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, false) + stream, _, err := cli.call("GET", "/containers/"+name+"/json", nil, nil) if err != nil { return err } @@ -2126,16 +2074,27 @@ func (cli *DockerCli) CmdSearch(args ...string) error { utils.ParseFlags(cmd, args, true) + name := cmd.Arg(0) v := url.Values{} - v.Set("term", cmd.Arg(0)) - - body, _, err := readBody(cli.call("GET", "/images/search?"+v.Encode(), nil, true)) + v.Set("term", name) + // Resolve the Repository name from fqn to hostname + name + taglessRemote, _ := parsers.ParseRepositoryTag(name) + repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) if err != nil { return err } + + cli.LoadConfigFile() + + body, statusCode, errReq := cli.clientRequestAttemptLogin("GET", "/images/search?"+v.Encode(), nil, nil, repoInfo.Index, "search") + rawBody, _, err := readBody(body, statusCode, errReq) + if err != nil { + return err + } + outs := engine.NewTable("star_count", 0) - if _, err := outs.ReadListFrom(body); err != nil { + if _, err := outs.ReadListFrom(rawBody); err != nil { return err } w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0) @@ -2190,7 +2149,7 @@ func (cli *DockerCli) CmdTag(args ...string) error { v.Set("force", "1") } - if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, nil)); err != nil { return err } return nil @@ -2292,7 +2251,7 @@ func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc } //create the container - stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false) + stream, statusCode, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil) //if image not found try to pull it if statusCode == 404 { repo, tag := parsers.ParseRepositoryTag(config.Image) @@ -2306,7 +2265,7 @@ func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runc return nil, err } // Retry - if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, false); err != nil { + if stream, _, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil); err != nil { return nil, err } } else if err != nil { @@ -2496,7 +2455,7 @@ func (cli *DockerCli) CmdRun(args ...string) error { } //start the container - if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, false)); err != nil { + if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, nil)); err != nil { return err } @@ -2526,13 +2485,13 @@ func (cli *DockerCli) CmdRun(args ...string) error { if *flAutoRemove { // Autoremove: wait for the container to finish, retrieve // the exit code and remove the container - if _, _, err := readBody(cli.call("POST", "/containers/"+createResponse.ID+"/wait", nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", "/containers/"+createResponse.ID+"/wait", nil, nil)); err != nil { return err } if _, status, err = getExitCode(cli, createResponse.ID); err != nil { return err } - if _, _, err := readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, false)); err != nil { + if _, _, err := readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, nil)); err != nil { return err } } else { @@ -2572,7 +2531,7 @@ func (cli *DockerCli) CmdCp(args ...string) error { copyData.Set("Resource", info[1]) copyData.Set("HostPath", cmd.Arg(1)) - stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, false) + stream, statusCode, err := cli.call("POST", "/containers/"+info[0]+"/copy", copyData, nil) if stream != nil { defer stream.Close() } @@ -2667,7 +2626,7 @@ func (cli *DockerCli) CmdExec(args ...string) error { return &utils.StatusError{StatusCode: 1} } - stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, false) + stream, _, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil) if err != nil { return err } @@ -2689,7 +2648,7 @@ func (cli *DockerCli) CmdExec(args ...string) error { return err } } else { - if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, false)); err != nil { + if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execConfig, nil)); err != nil { return err } // For now don't print this - wait for when we support exec wait() @@ -2781,7 +2740,7 @@ type containerStats struct { } func (s *containerStats) Collect(cli *DockerCli) { - stream, _, err := cli.call("GET", "/containers/"+s.Name+"/stats", nil, false) + stream, _, err := cli.call("GET", "/containers/"+s.Name+"/stats", nil, nil) if err != nil { s.err = err return diff --git a/api/client/utils.go b/api/client/utils.go index 103bfdec3a..29aa203971 100644 --- a/api/client/utils.go +++ b/api/client/utils.go @@ -54,124 +54,144 @@ func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) { return params, nil } -func (cli *DockerCli) call(method, path string, data interface{}, passAuthInfo bool) (io.ReadCloser, int, error) { - params, err := cli.encodeData(data) - if err != nil { - return nil, -1, err - } - req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), params) - if err != nil { - return nil, -1, err - } - if passAuthInfo { - cli.LoadConfigFile() - // Resolve the Auth config relevant for this server - authConfig := cli.configFile.Configs[registry.IndexServerAddress()] - getHeaders := func(authConfig registry.AuthConfig) (map[string][]string, error) { - buf, err := json.Marshal(authConfig) - if err != nil { - return nil, err - } - registryAuthHeader := []string{ - base64.URLEncoding.EncodeToString(buf), - } - return map[string][]string{"X-Registry-Auth": registryAuthHeader}, nil - } - if headers, err := getHeaders(authConfig); err == nil && headers != nil { - for k, v := range headers { - req.Header[k] = v - } - } - } - req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION) - req.URL.Host = cli.addr - req.URL.Scheme = cli.scheme - if data != nil { - req.Header.Set("Content-Type", "application/json") - } else if method == "POST" { - req.Header.Set("Content-Type", "text/plain") - } - resp, err := cli.HTTPClient().Do(req) - if err != nil { - if strings.Contains(err.Error(), "connection refused") { - return nil, -1, ErrConnectionRefused - } - - if cli.tlsConfig == nil { - return nil, -1, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err) - } - return nil, -1, fmt.Errorf("An error occurred trying to connect: %v", err) - - } - - if resp.StatusCode < 200 || resp.StatusCode >= 400 { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, -1, err - } - if len(body) == 0 { - return nil, resp.StatusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(resp.StatusCode), req.URL) - } - return nil, resp.StatusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body)) - } - - return resp.Body, resp.StatusCode, nil -} - -func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error { - return cli.streamHelper(method, path, true, in, out, nil, headers) -} - -func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error { - if (method == "POST" || method == "PUT") && in == nil { +func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, int, error) { + expectedPayload := (method == "POST" || method == "PUT") + if expectedPayload && in == nil { in = bytes.NewReader([]byte{}) } - req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), in) if err != nil { - return err + return nil, "", -1, err } req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION) req.URL.Host = cli.addr req.URL.Scheme = cli.scheme - if method == "POST" { - req.Header.Set("Content-Type", "text/plain") - } - if headers != nil { for k, v := range headers { req.Header[k] = v } } + if expectedPayload && req.Header.Get("Content-Type") == "" { + req.Header.Set("Content-Type", "text/plain") + } + resp, err := cli.HTTPClient().Do(req) + statusCode := -1 + if resp != nil { + statusCode = resp.StatusCode + } if err != nil { if strings.Contains(err.Error(), "connection refused") { - return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?") + return nil, "", statusCode, ErrConnectionRefused } - return err - } - defer resp.Body.Close() - if resp.StatusCode < 200 || resp.StatusCode >= 400 { + if cli.tlsConfig == nil { + return nil, "", statusCode, fmt.Errorf("%v. Are you trying to connect to a TLS-enabled daemon without TLS?", err) + } + + return nil, "", statusCode, fmt.Errorf("An error occurred trying to connect: %v", err) + } + + if statusCode < 200 || statusCode >= 400 { body, err := ioutil.ReadAll(resp.Body) if err != nil { - return err + return nil, "", statusCode, err } if len(body) == 0 { - return fmt.Errorf("Error :%s", http.StatusText(resp.StatusCode)) + return nil, "", statusCode, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(statusCode), req.URL) } - return fmt.Errorf("Error: %s", bytes.TrimSpace(body)) + return nil, "", statusCode, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body)) } - if api.MatchesContentType(resp.Header.Get("Content-Type"), "application/json") { - return utils.DisplayJSONMessagesStream(resp.Body, stdout, cli.outFd, cli.isTerminalOut) + return resp.Body, resp.Header.Get("Content-Type"), statusCode, nil +} + +func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) { + cmdAttempt := func(authConfig registry.AuthConfig) (io.ReadCloser, int, error) { + buf, err := json.Marshal(authConfig) + if err != nil { + return nil, -1, err + } + registryAuthHeader := []string{ + base64.URLEncoding.EncodeToString(buf), + } + + // begin the request + body, contentType, statusCode, err := cli.clientRequest(method, path, in, map[string][]string{ + "X-Registry-Auth": registryAuthHeader, + }) + if err == nil && out != nil { + // If we are streaming output, complete the stream since + // errors may not appear until later. + err = cli.streamBody(body, contentType, true, out, nil) + } + if err != nil { + // Since errors in a stream appear after status 200 has been written, + // we may need to change the status code. + if strings.Contains(err.Error(), "Authentication is required") || + strings.Contains(err.Error(), "Status 401") || + strings.Contains(err.Error(), "status code 401") { + statusCode = http.StatusUnauthorized + } + } + return body, statusCode, err + } + + // Resolve the Auth config relevant for this server + authConfig := cli.configFile.ResolveAuthConfig(index) + body, statusCode, err := cmdAttempt(authConfig) + if statusCode == http.StatusUnauthorized { + fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName) + if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil { + return nil, -1, err + } + authConfig = cli.configFile.ResolveAuthConfig(index) + return cmdAttempt(authConfig) + } + return body, statusCode, err +} + +func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) { + params, err := cli.encodeData(data) + if err != nil { + return nil, -1, err + } + + if data != nil { + if headers == nil { + headers = make(map[string][]string) + } + headers["Content-Type"] = []string{"application/json"} + } + + body, _, statusCode, err := cli.clientRequest(method, path, params, headers) + return body, statusCode, err +} +func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer, headers map[string][]string) error { + return cli.streamHelper(method, path, true, in, out, nil, headers) +} + +func (cli *DockerCli) streamHelper(method, path string, setRawTerminal bool, in io.Reader, stdout, stderr io.Writer, headers map[string][]string) error { + body, contentType, _, err := cli.clientRequest(method, path, in, headers) + if err != nil { + return err + } + return cli.streamBody(body, contentType, setRawTerminal, stdout, stderr) +} + +func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, setRawTerminal bool, stdout, stderr io.Writer) error { + defer body.Close() + + if api.MatchesContentType(contentType, "application/json") { + return utils.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut) } if stdout != nil || stderr != nil { // When TTY is ON, use regular copy + var err error if setRawTerminal { - _, err = io.Copy(stdout, resp.Body) + _, err = io.Copy(stdout, body) } else { - _, err = stdcopy.StdCopy(stdout, stderr, resp.Body) + _, err = stdcopy.StdCopy(stdout, stderr, body) } log.Debugf("[stream] End of stdout") return err @@ -195,13 +215,13 @@ func (cli *DockerCli) resizeTty(id string, isExec bool) { path = "/exec/" + id + "/resize?" } - if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, false)); err != nil { + if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil { log.Debugf("Error resize: %s", err) } } -func waitForExit(cli *DockerCli, containerId string) (int, error) { - stream, _, err := cli.call("POST", "/containers/"+containerId+"/wait", nil, false) +func waitForExit(cli *DockerCli, containerID string) (int, error) { + stream, _, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil) if err != nil { return -1, err } @@ -215,8 +235,8 @@ func waitForExit(cli *DockerCli, containerId string) (int, error) { // getExitCode perform an inspect on the container. It returns // the running state and the exit code. -func getExitCode(cli *DockerCli, containerId string) (bool, int, error) { - stream, _, err := cli.call("GET", "/containers/"+containerId+"/json", nil, false) +func getExitCode(cli *DockerCli, containerID string) (bool, int, error) { + stream, _, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil) if err != nil { // If we can't connect, then the daemon probably died. if err != ErrConnectionRefused { @@ -236,8 +256,8 @@ func getExitCode(cli *DockerCli, containerId string) (bool, int, error) { // getExecExitCode perform an inspect on the exec command. It returns // the running state and the exit code. -func getExecExitCode(cli *DockerCli, execId string) (bool, int, error) { - stream, _, err := cli.call("GET", "/exec/"+execId+"/json", nil, false) +func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) { + stream, _, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil) if err != nil { // If we can't connect, then the daemon probably died. if err != ErrConnectionRefused { diff --git a/registry/auth.go b/registry/auth.go index bb91c95c00..4baf114c6c 100644 --- a/registry/auth.go +++ b/registry/auth.go @@ -1,7 +1,6 @@ package registry import ( - "crypto/tls" "encoding/base64" "encoding/json" "errors" @@ -71,21 +70,7 @@ func (auth *RequestAuthorization) getToken() (string, error) { return auth.tokenCache, nil } - tlsConfig := tls.Config{ - MinVersion: tls.VersionTLS10, - } - if !auth.registryEndpoint.IsSecure { - tlsConfig.InsecureSkipVerify = true - } - - client := &http.Client{ - Transport: &http.Transport{ - DisableKeepAlives: true, - Proxy: http.ProxyFromEnvironment, - TLSClientConfig: &tlsConfig, - }, - CheckRedirect: AddRequiredHeadersToRedirectedRequests, - } + client := auth.registryEndpoint.HTTPClient() factory := HTTPRequestFactory(nil) for _, challenge := range auth.registryEndpoint.AuthChallenges { @@ -252,16 +237,10 @@ func Login(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HT // loginV1 tries to register/login to the v1 registry server. func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) { var ( - status string - reqBody []byte - err error - client = &http.Client{ - Transport: &http.Transport{ - DisableKeepAlives: true, - Proxy: http.ProxyFromEnvironment, - }, - CheckRedirect: AddRequiredHeadersToRedirectedRequests, - } + status string + reqBody []byte + err error + client = registryEndpoint.HTTPClient() reqStatusCode = 0 serverAddress = authConfig.ServerAddress ) @@ -285,7 +264,7 @@ func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils. // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status. b := strings.NewReader(string(jsonBody)) - req1, err := http.Post(serverAddress+"users/", "application/json; charset=utf-8", b) + req1, err := client.Post(serverAddress+"users/", "application/json; charset=utf-8", b) if err != nil { return "", fmt.Errorf("Server Error: %s", err) } @@ -371,26 +350,10 @@ func loginV1(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils. // is to be determined. func loginV2(authConfig *AuthConfig, registryEndpoint *Endpoint, factory *utils.HTTPRequestFactory) (string, error) { log.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint) - - tlsConfig := tls.Config{ - MinVersion: tls.VersionTLS10, - } - if !registryEndpoint.IsSecure { - tlsConfig.InsecureSkipVerify = true - } - - client := &http.Client{ - Transport: &http.Transport{ - DisableKeepAlives: true, - Proxy: http.ProxyFromEnvironment, - TLSClientConfig: &tlsConfig, - }, - CheckRedirect: AddRequiredHeadersToRedirectedRequests, - } - var ( err error allErrors []error + client = registryEndpoint.HTTPClient() ) for _, challenge := range registryEndpoint.AuthChallenges { diff --git a/registry/endpoint.go b/registry/endpoint.go index b1785e4fdc..59ae4dd542 100644 --- a/registry/endpoint.go +++ b/registry/endpoint.go @@ -1,6 +1,7 @@ package registry import ( + "crypto/tls" "encoding/json" "fmt" "io/ioutil" @@ -262,3 +263,20 @@ HeaderLoop: return RegistryInfo{}, fmt.Errorf("v2 registry endpoint returned status %d: %q", resp.StatusCode, http.StatusText(resp.StatusCode)) } + +func (e *Endpoint) HTTPClient() *http.Client { + tlsConfig := tls.Config{ + MinVersion: tls.VersionTLS10, + } + if !e.IsSecure { + tlsConfig.InsecureSkipVerify = true + } + return &http.Client{ + Transport: &http.Transport{ + DisableKeepAlives: true, + Proxy: http.ProxyFromEnvironment, + TLSClientConfig: &tlsConfig, + }, + CheckRedirect: AddRequiredHeadersToRedirectedRequests, + } +} diff --git a/registry/session.go b/registry/session.go index 82338252eb..bf04b586d4 100644 --- a/registry/session.go +++ b/registry/session.go @@ -511,6 +511,10 @@ func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate } defer res.Body.Close() + if res.StatusCode == 401 { + return nil, errLoginRequired + } + var tokens, endpoints []string if !validate { if res.StatusCode != 200 && res.StatusCode != 201 {