request.go 10 KB

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