2022-06-02 23:20:42 +00:00
|
|
|
// Copyright (c) 2022 Tailscale Inc & AUTHORS All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package controlhttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
|
|
|
"net"
|
|
|
|
"net/url"
|
|
|
|
|
|
|
|
"nhooyr.io/websocket"
|
|
|
|
"tailscale.com/control/controlbase"
|
|
|
|
"tailscale.com/net/dnscache"
|
|
|
|
"tailscale.com/types/key"
|
|
|
|
)
|
|
|
|
|
2022-06-08 21:56:52 +00:00
|
|
|
// Variant of Dial that tunnels the request over WebSockets, since we cannot do
|
2022-06-02 23:20:42 +00:00
|
|
|
// bi-directional communication over an HTTP connection when in JS.
|
2022-08-15 13:47:12 +00:00
|
|
|
func Dial(ctx context.Context, host string, httpPort string, httpsPort string, machineKey key.MachinePrivate, controlKey key.MachinePublic, protocolVersion uint16, dialer dnscache.DialContextFunc) (*controlbase.Conn, error) {
|
2022-06-02 23:20:42 +00:00
|
|
|
init, cont, err := controlbase.ClientDeferred(machineKey, controlKey, protocolVersion)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-06-08 21:56:52 +00:00
|
|
|
wsScheme := "wss"
|
|
|
|
if host == "localhost" {
|
|
|
|
wsScheme = "ws"
|
2022-08-15 13:47:12 +00:00
|
|
|
host = net.JoinHostPort(host, httpPort)
|
2022-06-08 21:56:52 +00:00
|
|
|
}
|
2022-06-02 23:20:42 +00:00
|
|
|
wsURL := &url.URL{
|
2022-06-08 21:56:52 +00:00
|
|
|
Scheme: wsScheme,
|
2022-08-15 13:47:12 +00:00
|
|
|
Host: host,
|
2022-06-02 23:20:42 +00:00
|
|
|
Path: serverUpgradePath,
|
|
|
|
// Can't set HTTP headers on the websocket request, so we have to to send
|
|
|
|
// the handshake via an HTTP header.
|
|
|
|
RawQuery: url.Values{
|
|
|
|
handshakeHeaderName: []string{base64.StdEncoding.EncodeToString(init)},
|
|
|
|
}.Encode(),
|
|
|
|
}
|
|
|
|
wsConn, _, err := websocket.Dial(ctx, wsURL.String(), &websocket.DialOptions{
|
|
|
|
Subprotocols: []string{upgradeHeaderValue},
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-06-06 23:13:15 +00:00
|
|
|
netConn := websocket.NetConn(context.Background(), wsConn, websocket.MessageBinary)
|
2022-06-02 23:20:42 +00:00
|
|
|
cbConn, err := cont(ctx, netConn)
|
|
|
|
if err != nil {
|
|
|
|
netConn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return cbConn, nil
|
|
|
|
|
|
|
|
}
|