request.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 http.Header) (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 http.Header) (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 http.Header) (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 http.Header) (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 http.Header) (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 http.Header) (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 http.Header) (serverResponse, error) {
  64. return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers)
  65. }
  66. func encodeBody(obj interface{}, headers http.Header) (io.Reader, http.Header, error) {
  67. if obj == nil {
  68. return nil, headers, nil
  69. }
  70. // encoding/json encodes a nil pointer as the JSON document `null`,
  71. // irrespective of whether the type implements json.Marshaler or encoding.TextMarshaler.
  72. // That is almost certainly not what the caller intended as the request body.
  73. if reflect.TypeOf(obj).Kind() == reflect.Ptr && reflect.ValueOf(obj).IsNil() {
  74. return nil, headers, nil
  75. }
  76. body, err := encodeData(obj)
  77. if err != nil {
  78. return nil, headers, err
  79. }
  80. if headers == nil {
  81. headers = make(map[string][]string)
  82. }
  83. headers["Content-Type"] = []string{"application/json"}
  84. return body, headers, nil
  85. }
  86. func (cli *Client) buildRequest(ctx context.Context, method, path string, body io.Reader, headers http.Header) (*http.Request, error) {
  87. req, err := http.NewRequestWithContext(ctx, method, path, body)
  88. if err != nil {
  89. return nil, err
  90. }
  91. req = cli.addHeaders(req, headers)
  92. req.URL.Scheme = cli.scheme
  93. req.URL.Host = cli.addr
  94. if cli.proto == "unix" || cli.proto == "npipe" {
  95. // Override host header for non-tcp connections.
  96. req.Host = DummyHost
  97. }
  98. if body != nil && req.Header.Get("Content-Type") == "" {
  99. req.Header.Set("Content-Type", "text/plain")
  100. }
  101. return req, nil
  102. }
  103. func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers http.Header) (serverResponse, error) {
  104. req, err := cli.buildRequest(ctx, method, cli.getAPIPath(ctx, path, query), body, headers)
  105. if err != nil {
  106. return serverResponse{}, err
  107. }
  108. resp, err := cli.doRequest(req)
  109. switch {
  110. case errors.Is(err, context.Canceled):
  111. return serverResponse{}, errdefs.Cancelled(err)
  112. case errors.Is(err, context.DeadlineExceeded):
  113. return serverResponse{}, errdefs.Deadline(err)
  114. case err == nil:
  115. err = cli.checkResponseErr(resp)
  116. }
  117. return resp, errdefs.FromStatusCode(err, resp.statusCode)
  118. }
  119. func (cli *Client) doRequest(req *http.Request) (serverResponse, error) {
  120. serverResp := serverResponse{statusCode: -1, reqURL: req.URL}
  121. resp, err := cli.client.Do(req)
  122. if err != nil {
  123. if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") {
  124. return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err)
  125. }
  126. if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") {
  127. return serverResp, errors.Wrap(err, "the server probably has client authentication (--tlsverify) enabled; check your TLS client certification settings")
  128. }
  129. // Don't decorate context sentinel errors; users may be comparing to
  130. // them directly.
  131. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  132. return serverResp, err
  133. }
  134. if uErr, ok := err.(*url.Error); ok {
  135. if nErr, ok := uErr.Err.(*net.OpError); ok {
  136. if os.IsPermission(nErr.Err) {
  137. return serverResp, errors.Wrapf(err, "permission denied while trying to connect to the Docker daemon socket at %v", cli.host)
  138. }
  139. }
  140. }
  141. if nErr, ok := err.(net.Error); ok {
  142. if nErr.Timeout() {
  143. return serverResp, ErrorConnectionFailed(cli.host)
  144. }
  145. if strings.Contains(nErr.Error(), "connection refused") || strings.Contains(nErr.Error(), "dial unix") {
  146. return serverResp, ErrorConnectionFailed(cli.host)
  147. }
  148. }
  149. // Although there's not a strongly typed error for this in go-winio,
  150. // lots of people are using the default configuration for the docker
  151. // daemon on Windows where the daemon is listening on a named pipe
  152. // `//./pipe/docker_engine, and the client must be running elevated.
  153. // Give users a clue rather than the not-overly useful message
  154. // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info:
  155. // open //./pipe/docker_engine: The system cannot find the file specified.`.
  156. // Note we can't string compare "The system cannot find the file specified" as
  157. // this is localised - for example in French the error would be
  158. // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.`
  159. if strings.Contains(err.Error(), `open //./pipe/docker_engine`) {
  160. // Checks if client is running with elevated privileges
  161. if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil {
  162. err = errors.Wrap(err, "in the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect")
  163. } else {
  164. f.Close()
  165. err = errors.Wrap(err, "this error may indicate that the docker daemon is not running")
  166. }
  167. }
  168. return serverResp, errors.Wrap(err, "error during connect")
  169. }
  170. if resp != nil {
  171. serverResp.statusCode = resp.StatusCode
  172. serverResp.body = resp.Body
  173. serverResp.header = resp.Header
  174. }
  175. return serverResp, nil
  176. }
  177. func (cli *Client) checkResponseErr(serverResp serverResponse) error {
  178. if serverResp.statusCode >= 200 && serverResp.statusCode < 400 {
  179. return nil
  180. }
  181. var body []byte
  182. var err error
  183. if serverResp.body != nil {
  184. bodyMax := 1 * 1024 * 1024 // 1 MiB
  185. bodyR := &io.LimitedReader{
  186. R: serverResp.body,
  187. N: int64(bodyMax),
  188. }
  189. body, err = io.ReadAll(bodyR)
  190. if err != nil {
  191. return err
  192. }
  193. if bodyR.N == 0 {
  194. 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)
  195. }
  196. }
  197. if len(body) == 0 {
  198. 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)
  199. }
  200. var daemonErr error
  201. if serverResp.header.Get("Content-Type") == "application/json" && (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) {
  202. var errorResponse types.ErrorResponse
  203. if err := json.Unmarshal(body, &errorResponse); err != nil {
  204. return errors.Wrap(err, "Error reading JSON")
  205. }
  206. daemonErr = errors.New(strings.TrimSpace(errorResponse.Message))
  207. } else {
  208. daemonErr = errors.New(strings.TrimSpace(string(body)))
  209. }
  210. return errors.Wrap(daemonErr, "Error response from daemon")
  211. }
  212. func (cli *Client) addHeaders(req *http.Request, headers http.Header) *http.Request {
  213. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  214. // then the user can't change OUR headers
  215. for k, v := range cli.customHTTPHeaders {
  216. if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" {
  217. continue
  218. }
  219. req.Header.Set(k, v)
  220. }
  221. for k, v := range headers {
  222. req.Header[http.CanonicalHeaderKey(k)] = v
  223. }
  224. if cli.userAgent != nil {
  225. if *cli.userAgent == "" {
  226. req.Header.Del("User-Agent")
  227. } else {
  228. req.Header.Set("User-Agent", *cli.userAgent)
  229. }
  230. }
  231. return req
  232. }
  233. func encodeData(data interface{}) (*bytes.Buffer, error) {
  234. params := bytes.NewBuffer(nil)
  235. if data != nil {
  236. if err := json.NewEncoder(params).Encode(data); err != nil {
  237. return nil, err
  238. }
  239. }
  240. return params, nil
  241. }
  242. func ensureReaderClosed(response serverResponse) {
  243. if response.body != nil {
  244. // Drain up to 512 bytes and close the body to let the Transport reuse the connection
  245. io.CopyN(io.Discard, response.body, 512)
  246. response.body.Close()
  247. }
  248. }