hijack.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package client
  2. import (
  3. "crypto/tls"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "net/http/httputil"
  10. "os"
  11. "runtime"
  12. "strings"
  13. "time"
  14. log "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/dockerversion"
  17. "github.com/docker/docker/pkg/promise"
  18. "github.com/docker/docker/pkg/stdcopy"
  19. "github.com/docker/docker/pkg/term"
  20. )
  21. type tlsClientCon struct {
  22. *tls.Conn
  23. rawConn net.Conn
  24. }
  25. func (c *tlsClientCon) CloseWrite() error {
  26. // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it
  27. // on its underlying connection.
  28. if cwc, ok := c.rawConn.(interface {
  29. CloseWrite() error
  30. }); ok {
  31. return cwc.CloseWrite()
  32. }
  33. return nil
  34. }
  35. func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) {
  36. return tlsDialWithDialer(new(net.Dialer), network, addr, config)
  37. }
  38. // We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in
  39. // order to return our custom tlsClientCon struct which holds both the tls.Conn
  40. // object _and_ its underlying raw connection. The rationale for this is that
  41. // we need to be able to close the write end of the connection when attaching,
  42. // which tls.Conn does not provide.
  43. func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {
  44. // We want the Timeout and Deadline values from dialer to cover the
  45. // whole process: TCP connection and TLS handshake. This means that we
  46. // also need to start our own timers now.
  47. timeout := dialer.Timeout
  48. if !dialer.Deadline.IsZero() {
  49. deadlineTimeout := dialer.Deadline.Sub(time.Now())
  50. if timeout == 0 || deadlineTimeout < timeout {
  51. timeout = deadlineTimeout
  52. }
  53. }
  54. var errChannel chan error
  55. if timeout != 0 {
  56. errChannel = make(chan error, 2)
  57. time.AfterFunc(timeout, func() {
  58. errChannel <- errors.New("")
  59. })
  60. }
  61. rawConn, err := dialer.Dial(network, addr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. colonPos := strings.LastIndex(addr, ":")
  66. if colonPos == -1 {
  67. colonPos = len(addr)
  68. }
  69. hostname := addr[:colonPos]
  70. // If no ServerName is set, infer the ServerName
  71. // from the hostname we're connecting to.
  72. if config.ServerName == "" {
  73. // Make a copy to avoid polluting argument or default.
  74. c := *config
  75. c.ServerName = hostname
  76. config = &c
  77. }
  78. conn := tls.Client(rawConn, config)
  79. if timeout == 0 {
  80. err = conn.Handshake()
  81. } else {
  82. go func() {
  83. errChannel <- conn.Handshake()
  84. }()
  85. err = <-errChannel
  86. }
  87. if err != nil {
  88. rawConn.Close()
  89. return nil, err
  90. }
  91. // This is Docker difference with standard's crypto/tls package: returned a
  92. // wrapper which holds both the TLS and raw connections.
  93. return &tlsClientCon{conn, rawConn}, nil
  94. }
  95. func (cli *DockerCli) dial() (net.Conn, error) {
  96. if cli.tlsConfig != nil && cli.proto != "unix" {
  97. // Notice this isn't Go standard's tls.Dial function
  98. return tlsDial(cli.proto, cli.addr, cli.tlsConfig)
  99. }
  100. return net.Dial(cli.proto, cli.addr)
  101. }
  102. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error {
  103. defer func() {
  104. if started != nil {
  105. close(started)
  106. }
  107. }()
  108. params, err := cli.encodeData(data)
  109. if err != nil {
  110. return err
  111. }
  112. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.APIVERSION, path), params)
  113. if err != nil {
  114. return err
  115. }
  116. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION)
  117. req.Header.Set("Content-Type", "text/plain")
  118. req.Header.Set("Connection", "Upgrade")
  119. req.Header.Set("Upgrade", "tcp")
  120. req.Host = cli.addr
  121. dial, err := cli.dial()
  122. if err != nil {
  123. if strings.Contains(err.Error(), "connection refused") {
  124. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  125. }
  126. return err
  127. }
  128. clientconn := httputil.NewClientConn(dial, nil)
  129. defer clientconn.Close()
  130. // Server hijacks the connection, error 'connection closed' expected
  131. clientconn.Do(req)
  132. rwc, br := clientconn.Hijack()
  133. defer rwc.Close()
  134. if started != nil {
  135. started <- rwc
  136. }
  137. var receiveStdout chan error
  138. var oldState *term.State
  139. if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" {
  140. oldState, err = term.SetRawTerminal(cli.inFd)
  141. if err != nil {
  142. return err
  143. }
  144. defer term.RestoreTerminal(cli.inFd, oldState)
  145. }
  146. if stdout != nil || stderr != nil {
  147. receiveStdout = promise.Go(func() (err error) {
  148. defer func() {
  149. if in != nil {
  150. if setRawTerminal && cli.isTerminalIn {
  151. term.RestoreTerminal(cli.inFd, oldState)
  152. }
  153. // For some reason this Close call blocks on darwin..
  154. // As the client exists right after, simply discard the close
  155. // until we find a better solution.
  156. if runtime.GOOS != "darwin" {
  157. in.Close()
  158. }
  159. }
  160. }()
  161. // When TTY is ON, use regular copy
  162. if setRawTerminal && stdout != nil {
  163. _, err = io.Copy(stdout, br)
  164. } else {
  165. _, err = stdcopy.StdCopy(stdout, stderr, br)
  166. }
  167. log.Debugf("[hijack] End of stdout")
  168. return err
  169. })
  170. }
  171. sendStdin := promise.Go(func() error {
  172. if in != nil {
  173. io.Copy(rwc, in)
  174. log.Debugf("[hijack] End of stdin")
  175. }
  176. if conn, ok := rwc.(interface {
  177. CloseWrite() error
  178. }); ok {
  179. if err := conn.CloseWrite(); err != nil {
  180. log.Debugf("Couldn't send EOF: %s", err)
  181. }
  182. }
  183. // Discard errors due to pipe interruption
  184. return nil
  185. })
  186. if stdout != nil || stderr != nil {
  187. if err := <-receiveStdout; err != nil {
  188. log.Debugf("Error receiveStdout: %s", err)
  189. return err
  190. }
  191. }
  192. if !cli.isTerminalIn {
  193. if err := <-sendStdin; err != nil {
  194. log.Debugf("Error sendStdin: %s", err)
  195. return err
  196. }
  197. }
  198. return nil
  199. }