github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/client/hijack.go (about)

     1  package client // import "github.com/docker/docker/client"
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"crypto/tls"
     7  	"fmt"
     8  	"net"
     9  	"net/http"
    10  	"net/http/httputil"
    11  	"net/url"
    12  	"time"
    13  
    14  	"github.com/docker/docker/api/types"
    15  	"github.com/docker/go-connections/sockets"
    16  	"github.com/pkg/errors"
    17  )
    18  
    19  // postHijacked sends a POST request and hijacks the connection.
    20  func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) {
    21  	bodyEncoded, err := encodeData(body)
    22  	if err != nil {
    23  		return types.HijackedResponse{}, err
    24  	}
    25  
    26  	apiPath := cli.getAPIPath(ctx, path, query)
    27  	req, err := http.NewRequest(http.MethodPost, apiPath, bodyEncoded)
    28  	if err != nil {
    29  		return types.HijackedResponse{}, err
    30  	}
    31  	req = cli.addHeaders(req, headers)
    32  
    33  	conn, err := cli.setupHijackConn(ctx, req, "tcp")
    34  	if err != nil {
    35  		return types.HijackedResponse{}, err
    36  	}
    37  
    38  	return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err
    39  }
    40  
    41  // DialHijack returns a hijacked connection with negotiated protocol proto.
    42  func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) {
    43  	req, err := http.NewRequest(http.MethodPost, url, nil)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  	req = cli.addHeaders(req, meta)
    48  
    49  	return cli.setupHijackConn(ctx, req, proto)
    50  }
    51  
    52  // fallbackDial is used when WithDialer() was not called.
    53  // See cli.Dialer().
    54  func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) {
    55  	if tlsConfig != nil && proto != "unix" && proto != "npipe" {
    56  		return tls.Dial(proto, addr, tlsConfig)
    57  	}
    58  	if proto == "npipe" {
    59  		return sockets.DialPipe(addr, 32*time.Second)
    60  	}
    61  	return net.Dial(proto, addr)
    62  }
    63  
    64  func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, error) {
    65  	req.Host = cli.addr
    66  	req.Header.Set("Connection", "Upgrade")
    67  	req.Header.Set("Upgrade", proto)
    68  
    69  	dialer := cli.Dialer()
    70  	conn, err := dialer(ctx)
    71  	if err != nil {
    72  		return nil, errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?")
    73  	}
    74  
    75  	// When we set up a TCP connection for hijack, there could be long periods
    76  	// of inactivity (a long running command with no output) that in certain
    77  	// network setups may cause ECONNTIMEOUT, leaving the client in an unknown
    78  	// state. Setting TCP KeepAlive on the socket connection will prohibit
    79  	// ECONNTIMEOUT unless the socket connection truly is broken
    80  	if tcpConn, ok := conn.(*net.TCPConn); ok {
    81  		tcpConn.SetKeepAlive(true)
    82  		tcpConn.SetKeepAlivePeriod(30 * time.Second)
    83  	}
    84  
    85  	clientconn := httputil.NewClientConn(conn, nil)
    86  	defer clientconn.Close()
    87  
    88  	// Server hijacks the connection, error 'connection closed' expected
    89  	resp, err := clientconn.Do(req)
    90  
    91  	//nolint:staticcheck // ignore SA1019 for connecting to old (pre go1.8) daemons
    92  	if err != httputil.ErrPersistEOF {
    93  		if err != nil {
    94  			return nil, err
    95  		}
    96  		if resp.StatusCode != http.StatusSwitchingProtocols {
    97  			resp.Body.Close()
    98  			return nil, fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode)
    99  		}
   100  	}
   101  
   102  	c, br := clientconn.Hijack()
   103  	if br.Buffered() > 0 {
   104  		// If there is buffered content, wrap the connection.  We return an
   105  		// object that implements CloseWrite iff the underlying connection
   106  		// implements it.
   107  		if _, ok := c.(types.CloseWriter); ok {
   108  			c = &hijackedConnCloseWriter{&hijackedConn{c, br}}
   109  		} else {
   110  			c = &hijackedConn{c, br}
   111  		}
   112  	} else {
   113  		br.Reset(nil)
   114  	}
   115  
   116  	return c, nil
   117  }
   118  
   119  // hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case
   120  // that a) there was already buffered data in the http layer when Hijack() was
   121  // called, and b) the underlying net.Conn does *not* implement CloseWrite().
   122  // hijackedConn does not implement CloseWrite() either.
   123  type hijackedConn struct {
   124  	net.Conn
   125  	r *bufio.Reader
   126  }
   127  
   128  func (c *hijackedConn) Read(b []byte) (int, error) {
   129  	return c.r.Read(b)
   130  }
   131  
   132  // hijackedConnCloseWriter is a hijackedConn which additionally implements
   133  // CloseWrite().  It is returned by setupHijackConn in the case that a) there
   134  // was already buffered data in the http layer when Hijack() was called, and b)
   135  // the underlying net.Conn *does* implement CloseWrite().
   136  type hijackedConnCloseWriter struct {
   137  	*hijackedConn
   138  }
   139  
   140  var _ types.CloseWriter = &hijackedConnCloseWriter{}
   141  
   142  func (c *hijackedConnCloseWriter) CloseWrite() error {
   143  	conn := c.Conn.(types.CloseWriter)
   144  	return conn.CloseWrite()
   145  }