github.com/rish1988/moby@v25.0.2+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  	"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  func (cli *Client) doRequest(req *http.Request) (serverResponse, error) {
   138  	serverResp := serverResponse{statusCode: -1, reqURL: req.URL}
   139  
   140  	resp, err := cli.client.Do(req)
   141  	if err != nil {
   142  		if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") {
   143  			return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
   144  		}
   145  
   146  		if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") {
   147  			return serverResp, errors.Wrap(err, "the server probably has client authentication (--tlsverify) enabled; check your TLS client certification settings")
   148  		}
   149  
   150  		// Don't decorate context sentinel errors; users may be comparing to
   151  		// them directly.
   152  		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
   153  			return serverResp, err
   154  		}
   155  
   156  		if uErr, ok := err.(*url.Error); ok {
   157  			if nErr, ok := uErr.Err.(*net.OpError); ok {
   158  				if os.IsPermission(nErr.Err) {
   159  					return serverResp, errors.Wrapf(err, "permission denied while trying to connect to the Docker daemon socket at %v", cli.host)
   160  				}
   161  			}
   162  		}
   163  
   164  		if nErr, ok := err.(net.Error); ok {
   165  			if nErr.Timeout() {
   166  				return serverResp, ErrorConnectionFailed(cli.host)
   167  			}
   168  			if strings.Contains(nErr.Error(), "connection refused") || strings.Contains(nErr.Error(), "dial unix") {
   169  				return serverResp, ErrorConnectionFailed(cli.host)
   170  			}
   171  		}
   172  
   173  		// Although there's not a strongly typed error for this in go-winio,
   174  		// lots of people are using the default configuration for the docker
   175  		// daemon on Windows where the daemon is listening on a named pipe
   176  		// `//./pipe/docker_engine, and the client must be running elevated.
   177  		// Give users a clue rather than the not-overly useful message
   178  		// such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info:
   179  		// open //./pipe/docker_engine: The system cannot find the file specified.`.
   180  		// Note we can't string compare "The system cannot find the file specified" as
   181  		// this is localised - for example in French the error would be
   182  		// `open //./pipe/docker_engine: Le fichier spécifié est introuvable.`
   183  		if strings.Contains(err.Error(), `open //./pipe/docker_engine`) {
   184  			// Checks if client is running with elevated privileges
   185  			if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil {
   186  				err = errors.Wrap(err, "in the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect")
   187  			} else {
   188  				f.Close()
   189  				err = errors.Wrap(err, "this error may indicate that the docker daemon is not running")
   190  			}
   191  		}
   192  
   193  		return serverResp, errors.Wrap(err, "error during connect")
   194  	}
   195  
   196  	if resp != nil {
   197  		serverResp.statusCode = resp.StatusCode
   198  		serverResp.body = resp.Body
   199  		serverResp.header = resp.Header
   200  	}
   201  	return serverResp, nil
   202  }
   203  
   204  func (cli *Client) checkResponseErr(serverResp serverResponse) error {
   205  	if serverResp.statusCode >= 200 && serverResp.statusCode < 400 {
   206  		return nil
   207  	}
   208  
   209  	var body []byte
   210  	var err error
   211  	if serverResp.body != nil {
   212  		bodyMax := 1 * 1024 * 1024 // 1 MiB
   213  		bodyR := &io.LimitedReader{
   214  			R: serverResp.body,
   215  			N: int64(bodyMax),
   216  		}
   217  		body, err = io.ReadAll(bodyR)
   218  		if err != nil {
   219  			return err
   220  		}
   221  		if bodyR.N == 0 {
   222  			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)
   223  		}
   224  	}
   225  	if len(body) == 0 {
   226  		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)
   227  	}
   228  
   229  	var daemonErr error
   230  	if serverResp.header.Get("Content-Type") == "application/json" && (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) {
   231  		var errorResponse types.ErrorResponse
   232  		if err := json.Unmarshal(body, &errorResponse); err != nil {
   233  			return errors.Wrap(err, "Error reading JSON")
   234  		}
   235  		daemonErr = errors.New(strings.TrimSpace(errorResponse.Message))
   236  	} else {
   237  		daemonErr = errors.New(strings.TrimSpace(string(body)))
   238  	}
   239  	return errors.Wrap(daemonErr, "Error response from daemon")
   240  }
   241  
   242  func (cli *Client) addHeaders(req *http.Request, headers http.Header) *http.Request {
   243  	// Add CLI Config's HTTP Headers BEFORE we set the Docker headers
   244  	// then the user can't change OUR headers
   245  	for k, v := range cli.customHTTPHeaders {
   246  		if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" {
   247  			continue
   248  		}
   249  		req.Header.Set(k, v)
   250  	}
   251  
   252  	for k, v := range headers {
   253  		req.Header[http.CanonicalHeaderKey(k)] = v
   254  	}
   255  
   256  	if cli.userAgent != nil {
   257  		if *cli.userAgent == "" {
   258  			req.Header.Del("User-Agent")
   259  		} else {
   260  			req.Header.Set("User-Agent", *cli.userAgent)
   261  		}
   262  	}
   263  	return req
   264  }
   265  
   266  func encodeData(data interface{}) (*bytes.Buffer, error) {
   267  	params := bytes.NewBuffer(nil)
   268  	if data != nil {
   269  		if err := json.NewEncoder(params).Encode(data); err != nil {
   270  			return nil, err
   271  		}
   272  	}
   273  	return params, nil
   274  }
   275  
   276  func ensureReaderClosed(response serverResponse) {
   277  	if response.body != nil {
   278  		// Drain up to 512 bytes and close the body to let the Transport reuse the connection
   279  		io.CopyN(io.Discard, response.body, 512)
   280  		response.body.Close()
   281  	}
   282  }