hijack.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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/pkg/stdcopy"
  17. "github.com/docker/docker/pkg/term"
  18. "github.com/docker/docker/version"
  19. )
  20. type tlsClientCon struct {
  21. *tls.Conn
  22. rawConn net.Conn
  23. }
  24. func (c *tlsClientCon) CloseWrite() error {
  25. // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it
  26. // on its underlying connection.
  27. if cwc, ok := c.rawConn.(interface {
  28. CloseWrite() error
  29. }); ok {
  30. return cwc.CloseWrite()
  31. }
  32. return nil
  33. }
  34. func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) {
  35. return tlsDialWithDialer(new(net.Dialer), network, addr, config)
  36. }
  37. // We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in
  38. // order to return our custom tlsClientCon struct which holds both the tls.Conn
  39. // object _and_ its underlying raw connection. The rationale for this is that
  40. // we need to be able to close the write end of the connection when attaching,
  41. // which tls.Conn does not provide.
  42. func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {
  43. // We want the Timeout and Deadline values from dialer to cover the
  44. // whole process: TCP connection and TLS handshake. This means that we
  45. // also need to start our own timers now.
  46. timeout := dialer.Timeout
  47. if !dialer.Deadline.IsZero() {
  48. deadlineTimeout := dialer.Deadline.Sub(time.Now())
  49. if timeout == 0 || deadlineTimeout < timeout {
  50. timeout = deadlineTimeout
  51. }
  52. }
  53. var errChannel chan error
  54. if timeout != 0 {
  55. errChannel = make(chan error, 2)
  56. time.AfterFunc(timeout, func() {
  57. errChannel <- errors.New("")
  58. })
  59. }
  60. rawConn, err := dialer.Dial(network, addr)
  61. if err != nil {
  62. return nil, err
  63. }
  64. // When we set up a TCP connection for hijack, there could be long periods
  65. // of inactivity (a long running command with no output) that in certain
  66. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  67. // state. Setting TCP KeepAlive on the socket connection will prohibit
  68. // ECONNTIMEOUT unless the socket connection truly is broken
  69. if tcpConn, ok := rawConn.(*net.TCPConn); ok {
  70. tcpConn.SetKeepAlive(true)
  71. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  72. }
  73. colonPos := strings.LastIndex(addr, ":")
  74. if colonPos == -1 {
  75. colonPos = len(addr)
  76. }
  77. hostname := addr[:colonPos]
  78. // If no ServerName is set, infer the ServerName
  79. // from the hostname we're connecting to.
  80. if config.ServerName == "" {
  81. // Make a copy to avoid polluting argument or default.
  82. c := *config
  83. c.ServerName = hostname
  84. config = &c
  85. }
  86. conn := tls.Client(rawConn, config)
  87. if timeout == 0 {
  88. err = conn.Handshake()
  89. } else {
  90. go func() {
  91. errChannel <- conn.Handshake()
  92. }()
  93. err = <-errChannel
  94. }
  95. if err != nil {
  96. rawConn.Close()
  97. return nil, err
  98. }
  99. // This is Docker difference with standard's crypto/tls package: returned a
  100. // wrapper which holds both the TLS and raw connections.
  101. return &tlsClientCon{conn, rawConn}, nil
  102. }
  103. func (cli *DockerCli) dial() (net.Conn, error) {
  104. if cli.tlsConfig != nil && cli.proto != "unix" {
  105. // Notice this isn't Go standard's tls.Dial function
  106. return tlsDial(cli.proto, cli.addr, cli.tlsConfig)
  107. }
  108. return net.Dial(cli.proto, cli.addr)
  109. }
  110. func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error {
  111. return cli.hijackWithContentType(method, path, "text/plain", setRawTerminal, in, stdout, stderr, started, data)
  112. }
  113. func (cli *DockerCli) hijackWithContentType(method, path, contentType string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error {
  114. defer func() {
  115. if started != nil {
  116. close(started)
  117. }
  118. }()
  119. params, err := cli.encodeData(data)
  120. if err != nil {
  121. return err
  122. }
  123. req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), params)
  124. if err != nil {
  125. return err
  126. }
  127. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  128. // then the user can't change OUR headers
  129. for k, v := range cli.configFile.HTTPHeaders {
  130. req.Header.Set(k, v)
  131. }
  132. req.Header.Set("User-Agent", "Docker-Client/"+version.VERSION+" ("+runtime.GOOS+")")
  133. req.Header.Set("Content-Type", contentType)
  134. req.Header.Set("Connection", "Upgrade")
  135. req.Header.Set("Upgrade", "tcp")
  136. req.Host = cli.addr
  137. dial, err := cli.dial()
  138. if err != nil {
  139. if strings.Contains(err.Error(), "connection refused") {
  140. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?")
  141. }
  142. return err
  143. }
  144. // When we set up a TCP connection for hijack, there could be long periods
  145. // of inactivity (a long running command with no output) that in certain
  146. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  147. // state. Setting TCP KeepAlive on the socket connection will prohibit
  148. // ECONNTIMEOUT unless the socket connection truly is broken
  149. if tcpConn, ok := dial.(*net.TCPConn); ok {
  150. tcpConn.SetKeepAlive(true)
  151. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  152. }
  153. clientconn := httputil.NewClientConn(dial, nil)
  154. defer clientconn.Close()
  155. // Server hijacks the connection, error 'connection closed' expected
  156. clientconn.Do(req)
  157. rwc, br := clientconn.Hijack()
  158. defer rwc.Close()
  159. if started != nil {
  160. started <- rwc
  161. }
  162. var oldState *term.State
  163. if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" {
  164. oldState, err = term.SetRawTerminal(cli.inFd)
  165. if err != nil {
  166. return err
  167. }
  168. defer term.RestoreTerminal(cli.inFd, oldState)
  169. }
  170. receiveStdout := make(chan error, 1)
  171. if stdout != nil || stderr != nil {
  172. go func() {
  173. defer func() {
  174. if in != nil {
  175. if setRawTerminal && cli.isTerminalIn {
  176. term.RestoreTerminal(cli.inFd, oldState)
  177. }
  178. in.Close()
  179. }
  180. }()
  181. // When TTY is ON, use regular copy
  182. if setRawTerminal && stdout != nil {
  183. _, err = io.Copy(stdout, br)
  184. } else {
  185. _, err = stdcopy.StdCopy(stdout, stderr, br)
  186. }
  187. logrus.Debugf("[hijack] End of stdout")
  188. receiveStdout <- err
  189. }()
  190. }
  191. stdinDone := make(chan struct{})
  192. go func() {
  193. if in != nil {
  194. io.Copy(rwc, in)
  195. logrus.Debugf("[hijack] End of stdin")
  196. }
  197. if conn, ok := rwc.(interface {
  198. CloseWrite() error
  199. }); ok {
  200. if err := conn.CloseWrite(); err != nil {
  201. logrus.Debugf("Couldn't send EOF: %s", err)
  202. }
  203. }
  204. close(stdinDone)
  205. }()
  206. select {
  207. case err := <-receiveStdout:
  208. if err != nil {
  209. logrus.Debugf("Error receiveStdout: %s", err)
  210. return err
  211. }
  212. case <-stdinDone:
  213. if stdout != nil || stderr != nil {
  214. if err := <-receiveStdout; err != nil {
  215. logrus.Debugf("Error receiveStdout: %s", err)
  216. return err
  217. }
  218. }
  219. }
  220. return nil
  221. }