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