hijack.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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", "plain/text")
  118. req.Host = cli.addr
  119. dial, err := cli.dial()
  120. if err != nil {
  121. if strings.Contains(err.Error(), "connection refused") {
  122. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  123. }
  124. return err
  125. }
  126. clientconn := httputil.NewClientConn(dial, nil)
  127. defer clientconn.Close()
  128. // Server hijacks the connection, error 'connection closed' expected
  129. clientconn.Do(req)
  130. rwc, br := clientconn.Hijack()
  131. defer rwc.Close()
  132. if started != nil {
  133. started <- rwc
  134. }
  135. var receiveStdout chan error
  136. var oldState *term.State
  137. if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" {
  138. oldState, err = term.SetRawTerminal(cli.inFd)
  139. if err != nil {
  140. return err
  141. }
  142. defer term.RestoreTerminal(cli.inFd, oldState)
  143. }
  144. if stdout != nil || stderr != nil {
  145. receiveStdout = promise.Go(func() (err error) {
  146. defer func() {
  147. if in != nil {
  148. if setRawTerminal && cli.isTerminalIn {
  149. term.RestoreTerminal(cli.inFd, oldState)
  150. }
  151. // For some reason this Close call blocks on darwin..
  152. // As the client exists right after, simply discard the close
  153. // until we find a better solution.
  154. if runtime.GOOS != "darwin" {
  155. in.Close()
  156. }
  157. }
  158. }()
  159. // When TTY is ON, use regular copy
  160. if setRawTerminal && stdout != nil {
  161. _, err = io.Copy(stdout, br)
  162. } else {
  163. _, err = stdcopy.StdCopy(stdout, stderr, br)
  164. }
  165. log.Debugf("[hijack] End of stdout")
  166. return err
  167. })
  168. }
  169. sendStdin := promise.Go(func() error {
  170. if in != nil {
  171. io.Copy(rwc, in)
  172. log.Debugf("[hijack] End of stdin")
  173. }
  174. if conn, ok := rwc.(interface {
  175. CloseWrite() error
  176. }); ok {
  177. if err := conn.CloseWrite(); err != nil {
  178. log.Debugf("Couldn't send EOF: %s", err)
  179. }
  180. }
  181. // Discard errors due to pipe interruption
  182. return nil
  183. })
  184. if stdout != nil || stderr != nil {
  185. if err := <-receiveStdout; err != nil {
  186. log.Debugf("Error receiveStdout: %s", err)
  187. return err
  188. }
  189. }
  190. if !cli.isTerminalIn {
  191. if err := <-sendStdin; err != nil {
  192. log.Debugf("Error sendStdin: %s", err)
  193. return err
  194. }
  195. }
  196. return nil
  197. }