hijack.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "bufio"
  4. "context"
  5. "crypto/tls"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "time"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/go-connections/sockets"
  15. "github.com/pkg/errors"
  16. )
  17. // postHijacked sends a POST request and hijacks the connection.
  18. func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) {
  19. bodyEncoded, err := encodeData(body)
  20. if err != nil {
  21. return types.HijackedResponse{}, err
  22. }
  23. apiPath := cli.getAPIPath(ctx, path, query)
  24. req, err := http.NewRequest(http.MethodPost, apiPath, bodyEncoded)
  25. if err != nil {
  26. return types.HijackedResponse{}, err
  27. }
  28. req = cli.addHeaders(req, headers)
  29. conn, mediaType, err := cli.setupHijackConn(ctx, req, "tcp")
  30. if err != nil {
  31. return types.HijackedResponse{}, err
  32. }
  33. return types.NewHijackedResponse(conn, mediaType), err
  34. }
  35. // DialHijack returns a hijacked connection with negotiated protocol proto.
  36. func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) {
  37. req, err := http.NewRequest(http.MethodPost, url, nil)
  38. if err != nil {
  39. return nil, err
  40. }
  41. req = cli.addHeaders(req, meta)
  42. conn, _, err := cli.setupHijackConn(ctx, req, proto)
  43. return conn, err
  44. }
  45. // fallbackDial is used when WithDialer() was not called.
  46. // See cli.Dialer().
  47. func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) {
  48. if tlsConfig != nil && proto != "unix" && proto != "npipe" {
  49. return tls.Dial(proto, addr, tlsConfig)
  50. }
  51. if proto == "npipe" {
  52. return sockets.DialPipe(addr, 32*time.Second)
  53. }
  54. return net.Dial(proto, addr)
  55. }
  56. func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, string, error) {
  57. req.URL.Host = cli.addr
  58. if cli.proto == "unix" || cli.proto == "npipe" {
  59. // Override host header for non-tcp connections.
  60. req.Host = DummyHost
  61. }
  62. req.Header.Set("Connection", "Upgrade")
  63. req.Header.Set("Upgrade", proto)
  64. dialer := cli.Dialer()
  65. conn, err := dialer(ctx)
  66. if err != nil {
  67. return nil, "", errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?")
  68. }
  69. // When we set up a TCP connection for hijack, there could be long periods
  70. // of inactivity (a long running command with no output) that in certain
  71. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  72. // state. Setting TCP KeepAlive on the socket connection will prohibit
  73. // ECONNTIMEOUT unless the socket connection truly is broken
  74. if tcpConn, ok := conn.(*net.TCPConn); ok {
  75. tcpConn.SetKeepAlive(true)
  76. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  77. }
  78. clientconn := httputil.NewClientConn(conn, nil)
  79. defer clientconn.Close()
  80. // Server hijacks the connection, error 'connection closed' expected
  81. resp, err := clientconn.Do(req)
  82. //nolint:staticcheck // ignore SA1019 for connecting to old (pre go1.8) daemons
  83. if err != httputil.ErrPersistEOF {
  84. if err != nil {
  85. return nil, "", err
  86. }
  87. if resp.StatusCode != http.StatusSwitchingProtocols {
  88. resp.Body.Close()
  89. return nil, "", fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode)
  90. }
  91. }
  92. c, br := clientconn.Hijack()
  93. if br.Buffered() > 0 {
  94. // If there is buffered content, wrap the connection. We return an
  95. // object that implements CloseWrite if the underlying connection
  96. // implements it.
  97. if _, ok := c.(types.CloseWriter); ok {
  98. c = &hijackedConnCloseWriter{&hijackedConn{c, br}}
  99. } else {
  100. c = &hijackedConn{c, br}
  101. }
  102. } else {
  103. br.Reset(nil)
  104. }
  105. var mediaType string
  106. if versions.GreaterThanOrEqualTo(cli.ClientVersion(), "1.42") {
  107. // Prior to 1.42, Content-Type is always set to raw-stream and not relevant
  108. mediaType = resp.Header.Get("Content-Type")
  109. }
  110. return c, mediaType, nil
  111. }
  112. // hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case
  113. // that a) there was already buffered data in the http layer when Hijack() was
  114. // called, and b) the underlying net.Conn does *not* implement CloseWrite().
  115. // hijackedConn does not implement CloseWrite() either.
  116. type hijackedConn struct {
  117. net.Conn
  118. r *bufio.Reader
  119. }
  120. func (c *hijackedConn) Read(b []byte) (int, error) {
  121. return c.r.Read(b)
  122. }
  123. // hijackedConnCloseWriter is a hijackedConn which additionally implements
  124. // CloseWrite(). It is returned by setupHijackConn in the case that a) there
  125. // was already buffered data in the http layer when Hijack() was called, and b)
  126. // the underlying net.Conn *does* implement CloseWrite().
  127. type hijackedConnCloseWriter struct {
  128. *hijackedConn
  129. }
  130. var _ types.CloseWriter = &hijackedConnCloseWriter{}
  131. func (c *hijackedConnCloseWriter) CloseWrite() error {
  132. conn := c.Conn.(types.CloseWriter)
  133. return conn.CloseWrite()
  134. }