hijack.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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/stdcopy"
  18. "github.com/docker/docker/pkg/term"
  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. defer func() {
  112. if started != nil {
  113. close(started)
  114. }
  115. }()
  116. params, err := cli.encodeData(data)
  117. if err != nil {
  118. return err
  119. }
  120. req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), params)
  121. if err != nil {
  122. return err
  123. }
  124. // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
  125. // then the user can't change OUR headers
  126. for k, v := range cli.configFile.HTTPHeaders {
  127. req.Header.Set(k, v)
  128. }
  129. req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
  130. req.Header.Set("Content-Type", "text/plain")
  131. req.Header.Set("Connection", "Upgrade")
  132. req.Header.Set("Upgrade", "tcp")
  133. req.Host = cli.addr
  134. dial, err := cli.dial()
  135. if err != nil {
  136. if strings.Contains(err.Error(), "connection refused") {
  137. return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?")
  138. }
  139. return err
  140. }
  141. // When we set up a TCP connection for hijack, there could be long periods
  142. // of inactivity (a long running command with no output) that in certain
  143. // network setups may cause ECONNTIMEOUT, leaving the client in an unknown
  144. // state. Setting TCP KeepAlive on the socket connection will prohibit
  145. // ECONNTIMEOUT unless the socket connection truly is broken
  146. if tcpConn, ok := dial.(*net.TCPConn); ok {
  147. tcpConn.SetKeepAlive(true)
  148. tcpConn.SetKeepAlivePeriod(30 * time.Second)
  149. }
  150. clientconn := httputil.NewClientConn(dial, nil)
  151. defer clientconn.Close()
  152. // Server hijacks the connection, error 'connection closed' expected
  153. clientconn.Do(req)
  154. rwc, br := clientconn.Hijack()
  155. defer rwc.Close()
  156. if started != nil {
  157. started <- rwc
  158. }
  159. var oldState *term.State
  160. if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" {
  161. oldState, err = term.SetRawTerminal(cli.inFd)
  162. if err != nil {
  163. return err
  164. }
  165. defer term.RestoreTerminal(cli.inFd, oldState)
  166. }
  167. receiveStdout := make(chan error, 1)
  168. if stdout != nil || stderr != nil {
  169. go func() {
  170. defer func() {
  171. if in != nil {
  172. if setRawTerminal && cli.isTerminalIn {
  173. term.RestoreTerminal(cli.inFd, oldState)
  174. }
  175. in.Close()
  176. }
  177. }()
  178. // When TTY is ON, use regular copy
  179. if setRawTerminal && stdout != nil {
  180. _, err = io.Copy(stdout, br)
  181. } else {
  182. _, err = stdcopy.StdCopy(stdout, stderr, br)
  183. }
  184. logrus.Debugf("[hijack] End of stdout")
  185. receiveStdout <- err
  186. }()
  187. }
  188. stdinDone := make(chan struct{})
  189. go func() {
  190. if in != nil {
  191. io.Copy(rwc, in)
  192. logrus.Debugf("[hijack] End of stdin")
  193. }
  194. if conn, ok := rwc.(interface {
  195. CloseWrite() error
  196. }); ok {
  197. if err := conn.CloseWrite(); err != nil {
  198. logrus.Debugf("Couldn't send EOF: %s", err)
  199. }
  200. }
  201. close(stdinDone)
  202. }()
  203. select {
  204. case err := <-receiveStdout:
  205. if err != nil {
  206. logrus.Debugf("Error receiveStdout: %s", err)
  207. return err
  208. }
  209. case <-stdinDone:
  210. if stdout != nil || stderr != nil {
  211. if err := <-receiveStdout; err != nil {
  212. logrus.Debugf("Error receiveStdout: %s", err)
  213. return err
  214. }
  215. }
  216. }
  217. return nil
  218. }