hijack.go 4.4 KB

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