hijack.go 5.1 KB

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