hijack.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/api"
  16. "github.com/docker/docker/autogen/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. // When we set up a TCP connection for hijack, there could be long periods
  66. // of inactivity (a long running command with no output) that in certain
  67. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  68. // state. Setting TCP KeepAlive on the socket connection will prohibit
  69. // ECONNTIMEOUT unless the socket connection truly is broken
  70. if tcpConn, ok := rawConn.(*net.TCPConn); ok {
  71. tcpConn.SetKeepAlive(true)
  72. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  73. }
  74. colonPos := strings.LastIndex(addr, ":")
  75. if colonPos == -1 {
  76. colonPos = len(addr)
  77. }
  78. hostname := addr[:colonPos]
  79. // If no ServerName is set, infer the ServerName
  80. // from the hostname we're connecting to.
  81. if config.ServerName == "" {
  82. // Make a copy to avoid polluting argument or default.
  83. c := *config
  84. c.ServerName = hostname
  85. config = &c
  86. }
  87. conn := tls.Client(rawConn, config)
  88. if timeout == 0 {
  89. err = conn.Handshake()
  90. } else {
  91. go func() {
  92. errChannel <- conn.Handshake()
  93. }()
  94. err = <-errChannel
  95. }
  96. if err != nil {
  97. rawConn.Close()
  98. return nil, err
  99. }
  100. // This is Docker difference with standard's crypto/tls package: returned a
  101. // wrapper which holds both the TLS and raw connections.
  102. return &tlsClientCon{conn, rawConn}, nil
  103. }
  104. func (cli *DockerCli) dial() (net.Conn, error) {
  105. if cli.tlsConfig != nil && cli.proto != "unix" {
  106. // Notice this isn't Go standard's tls.Dial function
  107. return tlsDial(cli.proto, cli.addr, cli.tlsConfig)
  108. }
  109. return net.Dial(cli.proto, cli.addr)
  110. }
  111. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error {
  112. defer func() {
  113. if started != nil {
  114. close(started)
  115. }
  116. }()
  117. params, err := cli.encodeData(data)
  118. if err != nil {
  119. return err
  120. }
  121. req, err := http.NewRequest(method, fmt.Sprintf("/v%s%s", api.Version, path), params)
  122. if err != nil {
  123. return err
  124. }
  125. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  126. // then the user can't change OUR headers
  127. for k, v := range cli.configFile.HttpHeaders {
  128. req.Header.Set(k, v)
  129. }
  130. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
  131. req.Header.Set("Content-Type", "text/plain")
  132. req.Header.Set("Connection", "Upgrade")
  133. req.Header.Set("Upgrade", "tcp")
  134. req.Host = cli.addr
  135. dial, err := cli.dial()
  136. // When we set up a TCP connection for hijack, there could be long periods
  137. // of inactivity (a long running command with no output) that in certain
  138. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  139. // state. Setting TCP KeepAlive on the socket connection will prohibit
  140. // ECONNTIMEOUT unless the socket connection truly is broken
  141. if tcpConn, ok := dial.(*net.TCPConn); ok {
  142. tcpConn.SetKeepAlive(true)
  143. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  144. }
  145. if err != nil {
  146. if strings.Contains(err.Error(), "connection refused") {
  147. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?")
  148. }
  149. return err
  150. }
  151. clientconn := httputil.NewClientConn(dial, nil)
  152. defer clientconn.Close()
  153. // Server hijacks the connection, error 'connection closed' expected
  154. clientconn.Do(req)
  155. rwc, br := clientconn.Hijack()
  156. defer rwc.Close()
  157. if started != nil {
  158. started <- rwc
  159. }
  160. var receiveStdout chan error
  161. var oldState *term.State
  162. if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" {
  163. oldState, err = term.SetRawTerminal(cli.inFd)
  164. if err != nil {
  165. return err
  166. }
  167. defer term.RestoreTerminal(cli.inFd, oldState)
  168. }
  169. if stdout != nil || stderr != nil {
  170. receiveStdout = promise.Go(func() (err error) {
  171. defer func() {
  172. if in != nil {
  173. if setRawTerminal && cli.isTerminalIn {
  174. term.RestoreTerminal(cli.inFd, oldState)
  175. }
  176. // For some reason this Close call blocks on darwin..
  177. // As the client exists right after, simply discard the close
  178. // until we find a better solution.
  179. if runtime.GOOS != "darwin" {
  180. in.Close()
  181. }
  182. }
  183. }()
  184. // When TTY is ON, use regular copy
  185. if setRawTerminal && stdout != nil {
  186. _, err = io.Copy(stdout, br)
  187. } else {
  188. _, err = stdcopy.StdCopy(stdout, stderr, br)
  189. }
  190. logrus.Debugf("[hijack] End of stdout")
  191. return err
  192. })
  193. }
  194. sendStdin := promise.Go(func() error {
  195. if in != nil {
  196. io.Copy(rwc, in)
  197. logrus.Debugf("[hijack] End of stdin")
  198. }
  199. if conn, ok := rwc.(interface {
  200. CloseWrite() error
  201. }); ok {
  202. if err := conn.CloseWrite(); err != nil {
  203. logrus.Debugf("Couldn't send EOF: %s", err)
  204. }
  205. }
  206. // Discard errors due to pipe interruption
  207. return nil
  208. })
  209. if stdout != nil || stderr != nil {
  210. if err := <-receiveStdout; err != nil {
  211. logrus.Debugf("Error receiveStdout: %s", err)
  212. return err
  213. }
  214. }
  215. if !cli.isTerminalIn {
  216. if err := <-sendStdin; err != nil {
  217. logrus.Debugf("Error sendStdin: %s", err)
  218. return err
  219. }
  220. }
  221. return nil
  222. }