github.com/tonistiigi/docker@v0.10.1-0.20240229224939-974013b0dc6a/client/request.go (about) 1 package client // import "github.com/docker/docker/client" 2 3 import ( 4 "bytes" 5 "context" 6 "encoding/json" 7 "fmt" 8 "io" 9 "net" 10 "net/http" 11 "net/url" 12 "os" 13 "reflect" 14 "strings" 15 16 "github.com/docker/docker/api/types" 17 "github.com/docker/docker/api/types/versions" 18 "github.com/docker/docker/errdefs" 19 "github.com/pkg/errors" 20 ) 21 22 // serverResponse is a wrapper for http API responses. 23 type serverResponse struct { 24 body io.ReadCloser 25 header http.Header 26 statusCode int 27 reqURL *url.URL 28 } 29 30 // head sends an http request to the docker API using the method HEAD. 31 func (cli *Client) head(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { 32 return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) 33 } 34 35 // get sends an http request to the docker API using the method GET with a specific Go context. 36 func (cli *Client) get(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { 37 return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) 38 } 39 40 // post sends an http request to the docker API using the method POST with a specific Go context. 41 func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers http.Header) (serverResponse, error) { 42 body, headers, err := encodeBody(obj, headers) 43 if err != nil { 44 return serverResponse{}, err 45 } 46 return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) 47 } 48 49 func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { 50 return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) 51 } 52 53 func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers http.Header) (serverResponse, error) { 54 body, headers, err := encodeBody(obj, headers) 55 if err != nil { 56 return serverResponse{}, err 57 } 58 return cli.putRaw(ctx, path, query, body, headers) 59 } 60 61 // putRaw sends an http request to the docker API using the method PUT. 62 func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { 63 // PUT requests are expected to always have a body (apparently) 64 // so explicitly pass an empty body to sendRequest to signal that 65 // it should set the Content-Type header if not already present. 66 if body == nil { 67 body = http.NoBody 68 } 69 return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) 70 } 71 72 // delete sends an http request to the docker API using the method DELETE. 73 func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers http.Header) (serverResponse, error) { 74 return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) 75 } 76 77 func encodeBody(obj interface{}, headers http.Header) (io.Reader, http.Header, error) { 78 if obj == nil { 79 return nil, headers, nil 80 } 81 // encoding/json encodes a nil pointer as the JSON document `null`, 82 // irrespective of whether the type implements json.Marshaler or encoding.TextMarshaler. 83 // That is almost certainly not what the caller intended as the request body. 84 if reflect.TypeOf(obj).Kind() == reflect.Ptr && reflect.ValueOf(obj).IsNil() { 85 return nil, headers, nil 86 } 87 88 body, err := encodeData(obj) 89 if err != nil { 90 return nil, headers, err 91 } 92 if headers == nil { 93 headers = make(map[string][]string) 94 } 95 headers["Content-Type"] = []string{"application/json"} 96 return body, headers, nil 97 } 98 99 func (cli *Client) buildRequest(ctx context.Context, method, path string, body io.Reader, headers http.Header) (*http.Request, error) { 100 req, err := http.NewRequestWithContext(ctx, method, path, body) 101 if err != nil { 102 return nil, err 103 } 104 req = cli.addHeaders(req, headers) 105 req.URL.Scheme = cli.scheme 106 req.URL.Host = cli.addr 107 108 if cli.proto == "unix" || cli.proto == "npipe" { 109 // Override host header for non-tcp connections. 110 req.Host = DummyHost 111 } 112 113 if body != nil && req.Header.Get("Content-Type") == "" { 114 req.Header.Set("Content-Type", "text/plain") 115 } 116 return req, nil 117 } 118 119 func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) { 120 req, err := cli.buildRequest(ctx, method, cli.getAPIPath(ctx, path, query), body, headers) 121 if err != nil { 122 return serverResponse{}, err 123 } 124 125 resp, err := cli.doRequest(req) 126 switch { 127 case errors.Is(err, context.Canceled): 128 return serverResponse{}, errdefs.Cancelled(err) 129 case errors.Is(err, context.DeadlineExceeded): 130 return serverResponse{}, errdefs.Deadline(err) 131 case err == nil: 132 err = cli.checkResponseErr(resp) 133 } 134 return resp, errdefs.FromStatusCode(err, resp.statusCode) 135 } 136 137 // FIXME(thaJeztah): Should this actually return a serverResp when a connection error occurred? 138 func (cli *Client) doRequest(req *http.Request) (serverResponse, error) { 139 serverResp := serverResponse{statusCode: -1, reqURL: req.URL} 140 141 resp, err := cli.client.Do(req) 142 if err != nil { 143 if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { 144 return serverResp, errConnectionFailed{fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)} 145 } 146 147 if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") { 148 return serverResp, errConnectionFailed{errors.Wrap(err, "the server probably has client authentication (--tlsverify) enabled; check your TLS client certification settings")} 149 } 150 151 // Don't decorate context sentinel errors; users may be comparing to 152 // them directly. 153 if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { 154 return serverResp, err 155 } 156 157 if uErr, ok := err.(*url.Error); ok { 158 if nErr, ok := uErr.Err.(*net.OpError); ok { 159 if os.IsPermission(nErr.Err) { 160 return serverResp, errConnectionFailed{errors.Wrapf(err, "permission denied while trying to connect to the Docker daemon socket at %v", cli.host)} 161 } 162 } 163 } 164 165 if nErr, ok := err.(net.Error); ok { 166 // FIXME(thaJeztah): any net.Error should be considered a connection error (but we should include the original error)? 167 if nErr.Timeout() { 168 return serverResp, ErrorConnectionFailed(cli.host) 169 } 170 if strings.Contains(nErr.Error(), "connection refused") || strings.Contains(nErr.Error(), "dial unix") { 171 return serverResp, ErrorConnectionFailed(cli.host) 172 } 173 } 174 175 // Although there's not a strongly typed error for this in go-winio, 176 // lots of people are using the default configuration for the docker 177 // daemon on Windows where the daemon is listening on a named pipe 178 // `//./pipe/docker_engine, and the client must be running elevated. 179 // Give users a clue rather than the not-overly useful message 180 // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info: 181 // open //./pipe/docker_engine: The system cannot find the file specified.`. 182 // Note we can't string compare "The system cannot find the file specified" as 183 // this is localised - for example in French the error would be 184 // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.` 185 if strings.Contains(err.Error(), `open //./pipe/docker_engine`) { 186 // Checks if client is running with elevated privileges 187 if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil { 188 err = errors.Wrap(err, "in the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect") 189 } else { 190 f.Close() 191 err = errors.Wrap(err, "this error may indicate that the docker daemon is not running") 192 } 193 } 194 195 return serverResp, errConnectionFailed{errors.Wrap(err, "error during connect")} 196 } 197 198 if resp != nil { 199 serverResp.statusCode = resp.StatusCode 200 serverResp.body = resp.Body 201 serverResp.header = resp.Header 202 } 203 return serverResp, nil 204 } 205 206 func (cli *Client) checkResponseErr(serverResp serverResponse) error { 207 if serverResp.statusCode >= 200 && serverResp.statusCode < 400 { 208 return nil 209 } 210 211 var body []byte 212 var err error 213 if serverResp.body != nil { 214 bodyMax := 1 * 1024 * 1024 // 1 MiB 215 bodyR := &io.LimitedReader{ 216 R: serverResp.body, 217 N: int64(bodyMax), 218 } 219 body, err = io.ReadAll(bodyR) 220 if err != nil { 221 return err 222 } 223 if bodyR.N == 0 { 224 return fmt.Errorf("request returned %s with a message (> %d bytes) for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), bodyMax, serverResp.reqURL) 225 } 226 } 227 if len(body) == 0 { 228 return fmt.Errorf("request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), serverResp.reqURL) 229 } 230 231 var daemonErr error 232 if serverResp.header.Get("Content-Type") == "application/json" && (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) { 233 var errorResponse types.ErrorResponse 234 if err := json.Unmarshal(body, &errorResponse); err != nil { 235 return errors.Wrap(err, "Error reading JSON") 236 } 237 daemonErr = errors.New(strings.TrimSpace(errorResponse.Message)) 238 } else { 239 daemonErr = errors.New(strings.TrimSpace(string(body))) 240 } 241 return errors.Wrap(daemonErr, "Error response from daemon") 242 } 243 244 func (cli *Client) addHeaders(req *http.Request, headers http.Header) *http.Request { 245 // Add CLI Config's HTTP Headers BEFORE we set the Docker headers 246 // then the user can't change OUR headers 247 for k, v := range cli.customHTTPHeaders { 248 if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" { 249 continue 250 } 251 req.Header.Set(k, v) 252 } 253 254 for k, v := range headers { 255 req.Header[http.CanonicalHeaderKey(k)] = v 256 } 257 258 if cli.userAgent != nil { 259 if *cli.userAgent == "" { 260 req.Header.Del("User-Agent") 261 } else { 262 req.Header.Set("User-Agent", *cli.userAgent) 263 } 264 } 265 return req 266 } 267 268 func encodeData(data interface{}) (*bytes.Buffer, error) { 269 params := bytes.NewBuffer(nil) 270 if data != nil { 271 if err := json.NewEncoder(params).Encode(data); err != nil { 272 return nil, err 273 } 274 } 275 return params, nil 276 } 277 278 func ensureReaderClosed(response serverResponse) { 279 if response.body != nil { 280 // Drain up to 512 bytes and close the body to let the Transport reuse the connection 281 io.CopyN(io.Discard, response.body, 512) 282 response.body.Close() 283 } 284 }