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