2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
// Package derphttp implements DERP-over-HTTP.
|
|
|
|
//
|
|
|
|
// This makes DERP look exactly like WebSockets.
|
|
|
|
// A server can implement DERP over HTTPS and even if the TLS connection
|
|
|
|
// intercepted using a fake root CA, unless the interceptor knows how to
|
|
|
|
// detect DERP packets, it will look like a web socket.
|
|
|
|
package derphttp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2020-02-18 16:57:11 +00:00
|
|
|
"context"
|
2021-12-28 01:58:33 +00:00
|
|
|
"crypto/rand"
|
2020-02-05 22:16:58 +00:00
|
|
|
"crypto/tls"
|
2020-08-18 22:32:32 +00:00
|
|
|
"crypto/x509"
|
2020-02-05 22:16:58 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2020-02-28 21:18:10 +00:00
|
|
|
"io"
|
2020-02-05 22:16:58 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2022-07-26 03:55:44 +00:00
|
|
|
"net/netip"
|
2020-02-05 22:16:58 +00:00
|
|
|
"net/url"
|
2021-10-21 17:12:51 +00:00
|
|
|
"runtime"
|
2023-02-01 21:43:06 +00:00
|
|
|
"strings"
|
2020-02-05 22:16:58 +00:00
|
|
|
"sync"
|
2020-02-28 21:18:10 +00:00
|
|
|
"time"
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-08-18 22:32:32 +00:00
|
|
|
"go4.org/mem"
|
2020-02-05 22:16:58 +00:00
|
|
|
"tailscale.com/derp"
|
2022-01-24 18:52:57 +00:00
|
|
|
"tailscale.com/envknob"
|
2020-03-05 18:29:19 +00:00
|
|
|
"tailscale.com/net/dnscache"
|
2023-04-17 23:01:41 +00:00
|
|
|
"tailscale.com/net/netmon"
|
2020-05-28 23:48:08 +00:00
|
|
|
"tailscale.com/net/netns"
|
2023-02-03 20:07:58 +00:00
|
|
|
"tailscale.com/net/sockstats"
|
2020-04-25 20:24:53 +00:00
|
|
|
"tailscale.com/net/tlsdial"
|
2020-08-13 22:25:54 +00:00
|
|
|
"tailscale.com/net/tshttpproxy"
|
2022-08-04 17:43:49 +00:00
|
|
|
"tailscale.com/syncs"
|
2020-05-17 16:51:38 +00:00
|
|
|
"tailscale.com/tailcfg"
|
2023-07-27 19:56:33 +00:00
|
|
|
"tailscale.com/tstime"
|
2020-02-17 21:52:11 +00:00
|
|
|
"tailscale.com/types/key"
|
2020-02-15 03:23:16 +00:00
|
|
|
"tailscale.com/types/logger"
|
2023-06-08 02:46:59 +00:00
|
|
|
"tailscale.com/util/cmpx"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Client is a DERP-over-HTTP client.
|
|
|
|
//
|
|
|
|
// It automatically reconnects on error retry. That is, a failed Send or
|
|
|
|
// Recv will report the error and not retry, but subsequent calls to
|
2020-02-18 16:57:11 +00:00
|
|
|
// Send/Recv will completely re-establish the connection (unless Close
|
|
|
|
// has been called).
|
2020-02-05 22:16:58 +00:00
|
|
|
type Client struct {
|
2020-04-25 20:24:53 +00:00
|
|
|
TLSConfig *tls.Config // optional; nil means default
|
|
|
|
DNSCache *dnscache.Resolver // optional; nil means no caching
|
2020-06-01 22:19:41 +00:00
|
|
|
MeshKey string // optional; for trusted clients
|
2021-07-13 05:04:16 +00:00
|
|
|
IsProber bool // optional; for probers to optional declare themselves as such
|
2020-03-03 21:48:57 +00:00
|
|
|
|
2023-10-25 18:59:06 +00:00
|
|
|
// WatchConnectionChanges is whether the client wishes to subscribe to
|
|
|
|
// notifications about clients connecting & disconnecting.
|
|
|
|
//
|
|
|
|
// Only trusted connections (using MeshKey) are allowed to use this.
|
|
|
|
WatchConnectionChanges bool
|
|
|
|
|
2023-07-31 01:58:13 +00:00
|
|
|
// BaseContext, if non-nil, returns the base context to use for dialing a
|
|
|
|
// new derp server. If nil, context.Background is used.
|
|
|
|
// In either case, additional timeouts may be added to the base context.
|
|
|
|
BaseContext func() context.Context
|
|
|
|
|
2021-10-28 22:42:50 +00:00
|
|
|
privateKey key.NodePrivate
|
2020-02-11 17:37:20 +00:00
|
|
|
logf logger.Logf
|
2023-04-17 23:01:41 +00:00
|
|
|
netMon *netmon.Monitor // optional; nil means interfaces will be looked up on-demand
|
2021-07-29 17:45:07 +00:00
|
|
|
dialer func(ctx context.Context, network, addr string) (net.Conn, error)
|
2020-05-17 16:51:38 +00:00
|
|
|
|
|
|
|
// Either url or getRegion is non-nil:
|
|
|
|
url *url.URL
|
|
|
|
getRegion func() *tailcfg.DERPRegion
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
ctx context.Context // closed via cancelCtx in Client.Close
|
|
|
|
cancelCtx context.CancelFunc
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-01-29 22:52:00 +00:00
|
|
|
// addrFamSelAtomic is the last AddressFamilySelector set
|
|
|
|
// by SetAddressFamilySelector. It's an atomic because it needs
|
|
|
|
// to be accessed by multiple racing routines started while
|
|
|
|
// Client.conn holds mu.
|
2022-08-04 17:43:49 +00:00
|
|
|
addrFamSelAtomic syncs.AtomicValue[AddressFamilySelector]
|
2022-01-29 22:52:00 +00:00
|
|
|
|
2020-06-04 18:35:53 +00:00
|
|
|
mu sync.Mutex
|
2023-10-25 18:59:06 +00:00
|
|
|
started bool // true upon first connect, never transitions to false
|
2020-06-04 18:35:53 +00:00
|
|
|
preferred bool
|
2021-03-12 17:45:37 +00:00
|
|
|
canAckPings bool
|
2020-06-04 18:35:53 +00:00
|
|
|
closed bool
|
|
|
|
netConn io.Closer
|
|
|
|
client *derp.Client
|
|
|
|
connGen int // incremented once per new connection; valid values are >0
|
2021-10-28 22:42:50 +00:00
|
|
|
serverPubKey key.NodePublic
|
2022-01-26 19:58:56 +00:00
|
|
|
tlsState *tls.ConnectionState
|
2021-12-28 01:58:33 +00:00
|
|
|
pingOut map[derp.PingMessage]chan<- bool // chan to send to on pong
|
2023-07-27 19:56:33 +00:00
|
|
|
clock tstime.Clock
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2023-03-20 15:15:45 +00:00
|
|
|
func (c *Client) String() string {
|
|
|
|
return fmt.Sprintf("<derphttp_client.Client %s url=%s>", c.serverPubKey.ShortString(), c.url)
|
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
// NewRegionClient returns a new DERP-over-HTTP client. It connects lazily.
|
|
|
|
// To trigger a connection, use Connect.
|
2023-04-17 23:01:41 +00:00
|
|
|
// The netMon parameter is optional; if non-nil it's used to do faster interface lookups.
|
|
|
|
func NewRegionClient(privateKey key.NodePrivate, logf logger.Logf, netMon *netmon.Monitor, getRegion func() *tailcfg.DERPRegion) *Client {
|
2020-05-17 16:51:38 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
c := &Client{
|
|
|
|
privateKey: privateKey,
|
|
|
|
logf: logf,
|
2023-04-17 23:01:41 +00:00
|
|
|
netMon: netMon,
|
2020-05-17 16:51:38 +00:00
|
|
|
getRegion: getRegion,
|
|
|
|
ctx: ctx,
|
|
|
|
cancelCtx: cancel,
|
2023-07-27 19:56:33 +00:00
|
|
|
clock: tstime.StdClock{},
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
2022-10-13 18:10:11 +00:00
|
|
|
// NewNetcheckClient returns a Client that's only able to have its DialRegionTLS method called.
|
2020-05-29 20:31:08 +00:00
|
|
|
// It's used by the netcheck package.
|
|
|
|
func NewNetcheckClient(logf logger.Logf) *Client {
|
2023-07-27 19:56:33 +00:00
|
|
|
return &Client{logf: logf, clock: tstime.StdClock{}}
|
2020-05-29 20:31:08 +00:00
|
|
|
}
|
|
|
|
|
2020-02-18 16:57:11 +00:00
|
|
|
// NewClient returns a new DERP-over-HTTP client. It connects lazily.
|
2020-05-17 16:51:38 +00:00
|
|
|
// To trigger a connection, use Connect.
|
2021-10-28 22:42:50 +00:00
|
|
|
func NewClient(privateKey key.NodePrivate, serverURL string, logf logger.Logf) (*Client, error) {
|
2020-02-05 22:16:58 +00:00
|
|
|
u, err := url.Parse(serverURL)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("derphttp.NewClient: %v", err)
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
if urlPort(u) == "" {
|
|
|
|
return nil, fmt.Errorf("derphttp.NewClient: invalid URL scheme %q", u.Scheme)
|
|
|
|
}
|
2020-05-17 16:51:38 +00:00
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2020-02-11 17:37:20 +00:00
|
|
|
c := &Client{
|
2020-02-05 22:16:58 +00:00
|
|
|
privateKey: privateKey,
|
|
|
|
logf: logf,
|
|
|
|
url: u,
|
2020-02-28 21:18:10 +00:00
|
|
|
ctx: ctx,
|
|
|
|
cancelCtx: cancel,
|
2023-07-27 19:56:33 +00:00
|
|
|
clock: tstime.StdClock{},
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2023-10-25 18:59:06 +00:00
|
|
|
// isStarted reports whether this client has been used yet.
|
|
|
|
//
|
|
|
|
// If if reports false, it may still have its exported fields configured.
|
|
|
|
func (c *Client) isStarted() bool {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
return c.started
|
|
|
|
}
|
|
|
|
|
2020-02-18 16:57:11 +00:00
|
|
|
// Connect connects or reconnects to the server, unless already connected.
|
|
|
|
// It returns nil if there was already a good connection, or if one was made.
|
|
|
|
func (c *Client) Connect(ctx context.Context) error {
|
2020-06-04 18:35:53 +00:00
|
|
|
_, _, err := c.connect(ctx, "derphttp.Client.Connect")
|
2020-02-18 16:57:11 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-07-31 01:58:13 +00:00
|
|
|
// newContext returns a new context for setting up a new DERP connection.
|
|
|
|
// It uses either c.BaseContext or returns context.Background.
|
|
|
|
func (c *Client) newContext() context.Context {
|
|
|
|
if c.BaseContext != nil {
|
|
|
|
ctx := c.BaseContext()
|
|
|
|
if ctx == nil {
|
|
|
|
panic("BaseContext returned nil")
|
|
|
|
}
|
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
return context.Background()
|
|
|
|
}
|
|
|
|
|
2022-01-26 19:58:56 +00:00
|
|
|
// TLSConnectionState returns the last TLS connection state, if any.
|
|
|
|
// The client must already be connected.
|
|
|
|
func (c *Client) TLSConnectionState() (_ *tls.ConnectionState, ok bool) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if c.closed || c.client == nil {
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
return c.tlsState, c.tlsState != nil
|
|
|
|
}
|
|
|
|
|
2020-06-04 18:35:53 +00:00
|
|
|
// ServerPublicKey returns the server's public key.
|
2020-06-03 21:42:20 +00:00
|
|
|
//
|
|
|
|
// It only returns a non-zero value once a connection has succeeded
|
|
|
|
// from an earlier call.
|
2021-10-28 22:42:50 +00:00
|
|
|
func (c *Client) ServerPublicKey() key.NodePublic {
|
2020-06-04 18:35:53 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
return c.serverPubKey
|
|
|
|
}
|
|
|
|
|
2021-07-13 05:04:16 +00:00
|
|
|
// SelfPublicKey returns our own public key.
|
2021-10-28 22:42:50 +00:00
|
|
|
func (c *Client) SelfPublicKey() key.NodePublic {
|
2021-07-13 05:04:16 +00:00
|
|
|
return c.privateKey.Public()
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
func urlPort(u *url.URL) string {
|
|
|
|
if p := u.Port(); p != "" {
|
|
|
|
return p
|
|
|
|
}
|
|
|
|
switch u.Scheme {
|
|
|
|
case "https":
|
|
|
|
return "443"
|
|
|
|
case "http":
|
|
|
|
return "80"
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2023-04-05 00:10:50 +00:00
|
|
|
// debugDERPUseHTTP tells clients to connect to DERP via HTTP on port
|
|
|
|
// 3340 instead of HTTPS on 443.
|
|
|
|
var debugUseDERPHTTP = envknob.RegisterBool("TS_DEBUG_USE_DERP_HTTP")
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
func (c *Client) targetString(reg *tailcfg.DERPRegion) string {
|
|
|
|
if c.url != nil {
|
|
|
|
return c.url.String()
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("region %d (%v)", reg.RegionID, reg.RegionCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) useHTTPS() bool {
|
|
|
|
if c.url != nil && c.url.Scheme == "http" {
|
|
|
|
return false
|
|
|
|
}
|
2023-04-05 00:10:50 +00:00
|
|
|
if debugUseDERPHTTP() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-06-01 16:01:37 +00:00
|
|
|
// tlsServerName returns the tls.Config.ServerName value (for the TLS ClientHello).
|
2020-05-30 05:33:08 +00:00
|
|
|
func (c *Client) tlsServerName(node *tailcfg.DERPNode) string {
|
2020-05-17 16:51:38 +00:00
|
|
|
if c.url != nil {
|
2023-10-24 14:27:29 +00:00
|
|
|
return c.url.Hostname()
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
return node.HostName
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) urlString(node *tailcfg.DERPNode) string {
|
|
|
|
if c.url != nil {
|
|
|
|
return c.url.String()
|
|
|
|
}
|
2023-04-05 00:10:50 +00:00
|
|
|
proto := "https"
|
|
|
|
if debugUseDERPHTTP() {
|
|
|
|
proto = "http"
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%s://%s/derp", proto, node.HostName)
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
|
2022-09-25 18:29:55 +00:00
|
|
|
// AddressFamilySelector decides whether IPv6 is preferred for
|
2022-01-29 22:52:00 +00:00
|
|
|
// outbound dials.
|
|
|
|
type AddressFamilySelector interface {
|
|
|
|
// PreferIPv6 reports whether IPv4 dials should be slightly
|
|
|
|
// delayed to give IPv6 a better chance of winning dial races.
|
|
|
|
// Implementations should only return true if IPv6 is expected
|
|
|
|
// to succeed. (otherwise delaying IPv4 will delay the
|
|
|
|
// connection overall)
|
|
|
|
PreferIPv6() bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetAddressFamilySelector sets the AddressFamilySelector that this
|
|
|
|
// connection will use. It should be called before any dials.
|
|
|
|
// The value must not be nil. If called more than once, s must
|
|
|
|
// be the same concrete type as any prior calls.
|
|
|
|
func (c *Client) SetAddressFamilySelector(s AddressFamilySelector) {
|
|
|
|
c.addrFamSelAtomic.Store(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) preferIPv6() bool {
|
|
|
|
if s, ok := c.addrFamSelAtomic.Load().(AddressFamilySelector); ok {
|
|
|
|
return s.PreferIPv6()
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-10-21 17:12:51 +00:00
|
|
|
// dialWebsocketFunc is non-nil (set by websocket.go's init) when compiled in.
|
|
|
|
var dialWebsocketFunc func(ctx context.Context, urlStr string) (net.Conn, error)
|
|
|
|
|
|
|
|
func useWebsockets() bool {
|
|
|
|
if runtime.GOOS == "js" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if dialWebsocketFunc != nil {
|
2022-01-24 18:52:57 +00:00
|
|
|
return envknob.Bool("TS_DEBUG_DERP_WS_CLIENT")
|
2021-10-21 17:12:51 +00:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-06-04 18:35:53 +00:00
|
|
|
func (c *Client) connect(ctx context.Context, caller string) (client *derp.Client, connGen int, err error) {
|
2020-02-28 21:18:10 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2023-10-25 18:59:06 +00:00
|
|
|
c.started = true
|
2020-02-28 21:18:10 +00:00
|
|
|
if c.closed {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, ErrClientClosed
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if c.client != nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return c.client, c.connGen, nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
// timeout is the fallback maximum time (if ctx doesn't limit
|
|
|
|
// it further) to do all of: DNS + TCP + TLS + HTTP Upgrade +
|
|
|
|
// DERP upgrade.
|
|
|
|
const timeout = 10 * time.Second
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
// Either timeout fired (handled below), or
|
|
|
|
// we're returning via the defer cancel()
|
|
|
|
// below.
|
|
|
|
case <-c.ctx.Done():
|
|
|
|
// Propagate a Client.Close call into
|
|
|
|
// cancelling this context.
|
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
defer cancel()
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
var reg *tailcfg.DERPRegion // nil when using c.url to dial
|
|
|
|
if c.getRegion != nil {
|
|
|
|
reg = c.getRegion()
|
|
|
|
if reg == nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, errors.New("DERP region not available")
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
var tcpConn net.Conn
|
2020-05-17 16:51:38 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
2020-02-28 21:18:10 +00:00
|
|
|
if ctx.Err() != nil {
|
|
|
|
err = fmt.Errorf("%v: %v", ctx.Err(), err)
|
|
|
|
}
|
2020-05-17 16:51:38 +00:00
|
|
|
err = fmt.Errorf("%s connect to %v: %v", caller, c.targetString(reg), err)
|
2020-02-28 21:18:10 +00:00
|
|
|
if tcpConn != nil {
|
|
|
|
go tcpConn.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
var node *tailcfg.DERPNode // nil when using c.url to dial
|
2021-10-21 17:12:51 +00:00
|
|
|
switch {
|
|
|
|
case useWebsockets():
|
|
|
|
var urlStr string
|
|
|
|
if c.url != nil {
|
|
|
|
urlStr = c.url.String()
|
|
|
|
} else {
|
|
|
|
urlStr = c.urlString(reg.Nodes[0])
|
|
|
|
}
|
|
|
|
c.logf("%s: connecting websocket to %v", caller, urlStr)
|
|
|
|
conn, err := dialWebsocketFunc(ctx, urlStr)
|
|
|
|
if err != nil {
|
|
|
|
c.logf("%s: websocket to %v error: %v", caller, urlStr, err)
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
brw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
|
|
|
|
derpClient, err := derp.NewClient(c.privateKey, conn, brw, c.logf,
|
|
|
|
derp.MeshKey(c.MeshKey),
|
|
|
|
derp.CanAckPings(c.canAckPings),
|
|
|
|
derp.IsProber(c.IsProber),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
if c.preferred {
|
|
|
|
if err := derpClient.NotePreferred(true); err != nil {
|
|
|
|
go conn.Close()
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.serverPubKey = derpClient.ServerPublicKey()
|
|
|
|
c.client = derpClient
|
2023-03-07 01:59:03 +00:00
|
|
|
c.netConn = conn
|
2021-10-21 17:12:51 +00:00
|
|
|
c.connGen++
|
|
|
|
return c.client, c.connGen, nil
|
|
|
|
case c.url != nil:
|
2020-05-17 16:51:38 +00:00
|
|
|
c.logf("%s: connecting to %v", caller, c.url)
|
|
|
|
tcpConn, err = c.dialURL(ctx)
|
2021-10-21 17:12:51 +00:00
|
|
|
default:
|
2020-05-17 16:51:38 +00:00
|
|
|
c.logf("%s: connecting to derp-%d (%v)", caller, reg.RegionID, reg.RegionCode)
|
2020-05-30 05:33:08 +00:00
|
|
|
tcpConn, node, err = c.dialRegion(ctx, reg)
|
2020-03-05 18:29:19 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
// Now that we have a TCP connection, force close it if the
|
|
|
|
// TLS handshake + DERP setup takes too long.
|
2020-02-28 21:18:10 +00:00
|
|
|
done := make(chan struct{})
|
|
|
|
defer close(done)
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
// Normal path. Upgrade occurred in time.
|
|
|
|
case <-ctx.Done():
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
// Normal path. Upgrade occurred in time.
|
|
|
|
// But the ctx.Done() is also done because
|
|
|
|
// the "defer cancel()" above scheduled
|
|
|
|
// before this goroutine.
|
|
|
|
default:
|
|
|
|
// The TLS or HTTP or DERP exchanges didn't complete
|
|
|
|
// in time. Force close the TCP connection to force
|
|
|
|
// them to fail quickly.
|
|
|
|
tcpConn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2021-10-28 22:42:50 +00:00
|
|
|
var httpConn net.Conn // a TCP conn or a TLS conn; what we speak HTTP to
|
|
|
|
var serverPub key.NodePublic // or zero if unknown (if not using TLS or TLS middlebox eats it)
|
2020-08-18 22:32:32 +00:00
|
|
|
var serverProtoVersion int
|
2022-01-26 19:58:56 +00:00
|
|
|
var tlsState *tls.ConnectionState
|
2020-05-17 16:51:38 +00:00
|
|
|
if c.useHTTPS() {
|
2020-08-18 22:32:32 +00:00
|
|
|
tlsConn := c.tlsClient(tcpConn, node)
|
|
|
|
httpConn = tlsConn
|
|
|
|
|
|
|
|
// Force a handshake now (instead of waiting for it to
|
|
|
|
// be done implicitly on read/write) so we can check
|
|
|
|
// the ConnectionState.
|
|
|
|
if err := tlsConn.Handshake(); err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// We expect to be using TLS 1.3 to our own servers, and only
|
|
|
|
// starting at TLS 1.3 are the server's returned certificates
|
|
|
|
// encrypted, so only look for and use our "meta cert" if we're
|
|
|
|
// using TLS 1.3. If we're not using TLS 1.3, it might be a user
|
|
|
|
// running cmd/derper themselves with a different configuration,
|
|
|
|
// in which case we can avoid this fast-start optimization.
|
|
|
|
// (If a corporate proxy is MITM'ing TLS 1.3 connections with
|
|
|
|
// corp-mandated TLS root certs than all bets are off anyway.)
|
|
|
|
// Note that we're not specifically concerned about TLS downgrade
|
|
|
|
// attacks. TLS handles that fine:
|
|
|
|
// https://blog.gypsyengineer.com/en/security/how-does-tls-1-3-protect-against-downgrade-attacks.html
|
2022-01-26 19:58:56 +00:00
|
|
|
cs := tlsConn.ConnectionState()
|
|
|
|
tlsState = &cs
|
|
|
|
if cs.Version >= tls.VersionTLS13 {
|
|
|
|
serverPub, serverProtoVersion = parseMetaCert(cs.PeerCertificates)
|
2020-08-18 22:32:32 +00:00
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
} else {
|
|
|
|
httpConn = tcpConn
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
brw := bufio.NewReadWriter(bufio.NewReader(httpConn), bufio.NewWriter(httpConn))
|
2020-08-18 22:32:32 +00:00
|
|
|
var derpClient *derp.Client
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
req, err := http.NewRequest("GET", c.urlString(node), nil)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
req.Header.Set("Upgrade", "DERP")
|
2020-02-05 22:16:58 +00:00
|
|
|
req.Header.Set("Connection", "Upgrade")
|
2020-02-28 21:18:10 +00:00
|
|
|
|
2020-08-18 22:32:32 +00:00
|
|
|
if !serverPub.IsZero() && serverProtoVersion != 0 {
|
|
|
|
// parseMetaCert found the server's public key (no TLS
|
|
|
|
// middlebox was in the way), so skip the HTTP upgrade
|
|
|
|
// exchange. See https://github.com/tailscale/tailscale/issues/693
|
|
|
|
// for an overview. We still send the HTTP request
|
|
|
|
// just to get routed into the server's HTTP Handler so it
|
|
|
|
// can Hijack the request, but we signal with a special header
|
|
|
|
// that we don't want to deal with its HTTP response.
|
|
|
|
req.Header.Set(fastStartHeader, "1") // suppresses the server's HTTP response
|
|
|
|
if err := req.Write(brw); err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
// No need to flush the HTTP request. the derp.Client's initial
|
|
|
|
// client auth frame will flush it.
|
|
|
|
} else {
|
|
|
|
if err := req.Write(brw); err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
if err := brw.Flush(); err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-08-18 22:32:32 +00:00
|
|
|
resp, err := http.ReadResponse(brw.Reader, req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusSwitchingProtocols {
|
2022-09-15 12:06:59 +00:00
|
|
|
b, _ := io.ReadAll(resp.Body)
|
2020-08-18 22:32:32 +00:00
|
|
|
resp.Body.Close()
|
|
|
|
return nil, 0, fmt.Errorf("GET failed: %v: %s", err, b)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-03-12 17:45:37 +00:00
|
|
|
derpClient, err = derp.NewClient(c.privateKey, httpConn, brw, c.logf,
|
|
|
|
derp.MeshKey(c.MeshKey),
|
|
|
|
derp.ServerPublicKey(serverPub),
|
|
|
|
derp.CanAckPings(c.canAckPings),
|
2021-07-13 05:04:16 +00:00
|
|
|
derp.IsProber(c.IsProber),
|
2021-03-12 17:45:37 +00:00
|
|
|
)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
if c.preferred {
|
|
|
|
if err := derpClient.NotePreferred(true); err != nil {
|
|
|
|
go httpConn.Close()
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, err
|
2020-03-05 23:00:56 +00:00
|
|
|
}
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
|
2023-10-25 18:59:06 +00:00
|
|
|
if c.WatchConnectionChanges {
|
|
|
|
if err := derpClient.WatchConnectionChanges(); err != nil {
|
|
|
|
go httpConn.Close()
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-03 21:42:20 +00:00
|
|
|
c.serverPubKey = derpClient.ServerPublicKey()
|
2020-02-05 22:16:58 +00:00
|
|
|
c.client = derpClient
|
2020-02-28 21:18:10 +00:00
|
|
|
c.netConn = tcpConn
|
2022-01-26 19:58:56 +00:00
|
|
|
c.tlsState = tlsState
|
2020-06-04 18:35:53 +00:00
|
|
|
c.connGen++
|
|
|
|
return c.client, c.connGen, nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-07-29 17:45:07 +00:00
|
|
|
// SetURLDialer sets the dialer to use for dialing URLs.
|
|
|
|
// This dialer is only use for clients created with NewClient, not NewRegionClient.
|
|
|
|
// If unset or nil, the default dialer is used.
|
|
|
|
//
|
|
|
|
// The primary use for this is the derper mesh mode to connect to each
|
|
|
|
// other over a VPC network.
|
|
|
|
func (c *Client) SetURLDialer(dialer func(ctx context.Context, network, addr string) (net.Conn, error)) {
|
|
|
|
c.dialer = dialer
|
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
func (c *Client) dialURL(ctx context.Context) (net.Conn, error) {
|
|
|
|
host := c.url.Hostname()
|
2021-07-29 17:45:07 +00:00
|
|
|
if c.dialer != nil {
|
|
|
|
return c.dialer(ctx, "tcp", net.JoinHostPort(host, urlPort(c.url)))
|
|
|
|
}
|
2020-05-17 16:51:38 +00:00
|
|
|
hostOrIP := host
|
2023-04-17 23:01:41 +00:00
|
|
|
dialer := netns.NewDialer(c.logf, c.netMon)
|
2020-05-17 16:51:38 +00:00
|
|
|
|
|
|
|
if c.DNSCache != nil {
|
2021-07-26 18:58:28 +00:00
|
|
|
ip, _, _, err := c.DNSCache.LookupIP(ctx, host)
|
2020-05-17 16:51:38 +00:00
|
|
|
if err == nil {
|
|
|
|
hostOrIP = ip.String()
|
|
|
|
}
|
2020-06-01 17:50:37 +00:00
|
|
|
if err != nil && netns.IsSOCKSDialer(dialer) {
|
2020-05-17 16:51:38 +00:00
|
|
|
// Return an error if we're not using a dial
|
|
|
|
// proxy that can do DNS lookups for us.
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
tcpConn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(hostOrIP, urlPort(c.url)))
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("dial of %v: %v", host, err)
|
|
|
|
}
|
|
|
|
return tcpConn, nil
|
|
|
|
}
|
|
|
|
|
2020-05-30 05:33:08 +00:00
|
|
|
// dialRegion returns a TCP connection to the provided region, trying
|
2020-05-17 16:51:38 +00:00
|
|
|
// each node in order (with dialNode) until one connects or ctx is
|
|
|
|
// done.
|
2020-05-30 05:33:08 +00:00
|
|
|
func (c *Client) dialRegion(ctx context.Context, reg *tailcfg.DERPRegion) (net.Conn, *tailcfg.DERPNode, error) {
|
2020-05-17 16:51:38 +00:00
|
|
|
if len(reg.Nodes) == 0 {
|
|
|
|
return nil, nil, fmt.Errorf("no nodes for %s", c.targetString(reg))
|
|
|
|
}
|
|
|
|
var firstErr error
|
|
|
|
for _, n := range reg.Nodes {
|
|
|
|
if n.STUNOnly {
|
2020-07-27 17:10:10 +00:00
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = fmt.Errorf("no non-STUNOnly nodes for %s", c.targetString(reg))
|
|
|
|
}
|
2020-05-17 16:51:38 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
c, err := c.dialNode(ctx, n)
|
|
|
|
if err == nil {
|
|
|
|
return c, n, nil
|
|
|
|
}
|
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, nil, firstErr
|
|
|
|
}
|
|
|
|
|
2020-05-30 05:33:08 +00:00
|
|
|
func (c *Client) tlsClient(nc net.Conn, node *tailcfg.DERPNode) *tls.Conn {
|
|
|
|
tlsConf := tlsdial.Config(c.tlsServerName(node), c.TLSConfig)
|
2020-06-01 16:01:37 +00:00
|
|
|
if node != nil {
|
2021-10-01 04:13:38 +00:00
|
|
|
if node.InsecureForTests {
|
|
|
|
tlsConf.InsecureSkipVerify = true
|
|
|
|
tlsConf.VerifyConnection = nil
|
|
|
|
}
|
2020-06-01 16:01:37 +00:00
|
|
|
if node.CertName != "" {
|
|
|
|
tlsdial.SetConfigExpectedCert(tlsConf, node.CertName)
|
|
|
|
}
|
2020-05-30 05:33:08 +00:00
|
|
|
}
|
|
|
|
return tls.Client(nc, tlsConf)
|
|
|
|
}
|
|
|
|
|
2022-04-19 18:46:30 +00:00
|
|
|
// DialRegionTLS returns a TLS connection to a DERP node in the given region.
|
|
|
|
//
|
|
|
|
// DERP nodes for a region are tried in sequence according to their order
|
|
|
|
// in the DERP map. TLS is initiated on the first node where a socket is
|
|
|
|
// established.
|
|
|
|
func (c *Client) DialRegionTLS(ctx context.Context, reg *tailcfg.DERPRegion) (tlsConn *tls.Conn, connClose io.Closer, node *tailcfg.DERPNode, err error) {
|
2020-05-30 05:33:08 +00:00
|
|
|
tcpConn, node, err := c.dialRegion(ctx, reg)
|
|
|
|
if err != nil {
|
2022-04-19 18:46:30 +00:00
|
|
|
return nil, nil, nil, err
|
2020-05-30 05:33:08 +00:00
|
|
|
}
|
2022-04-19 18:46:30 +00:00
|
|
|
done := make(chan bool) // unbuffered
|
2020-05-30 05:33:08 +00:00
|
|
|
defer close(done)
|
|
|
|
|
|
|
|
tlsConn = c.tlsClient(tcpConn, node)
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
case <-ctx.Done():
|
|
|
|
tcpConn.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
err = tlsConn.Handshake()
|
|
|
|
if err != nil {
|
2022-04-19 18:46:30 +00:00
|
|
|
return nil, nil, nil, err
|
2020-05-30 05:33:08 +00:00
|
|
|
}
|
|
|
|
select {
|
|
|
|
case done <- true:
|
2022-04-19 18:46:30 +00:00
|
|
|
return tlsConn, tcpConn, node, nil
|
2020-05-30 05:33:08 +00:00
|
|
|
case <-ctx.Done():
|
2022-04-19 18:46:30 +00:00
|
|
|
return nil, nil, nil, ctx.Err()
|
2020-05-30 05:33:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
func (c *Client) dialContext(ctx context.Context, proto, addr string) (net.Conn, error) {
|
2023-04-17 23:01:41 +00:00
|
|
|
return netns.NewDialer(c.logf, c.netMon).DialContext(ctx, proto, addr)
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// shouldDialProto reports whether an explicitly provided IPv4 or IPv6
|
|
|
|
// address (given in s) is valid. An empty value means to dial, but to
|
|
|
|
// use DNS. The predicate function reports whether the non-empty
|
|
|
|
// string s contained a valid IP address of the right family.
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
func shouldDialProto(s string, pred func(netip.Addr) bool) bool {
|
2020-05-17 16:51:38 +00:00
|
|
|
if s == "" {
|
|
|
|
return true
|
|
|
|
}
|
2022-07-26 03:55:44 +00:00
|
|
|
ip, _ := netip.ParseAddr(s)
|
2020-05-17 16:51:38 +00:00
|
|
|
return pred(ip)
|
|
|
|
}
|
|
|
|
|
|
|
|
const dialNodeTimeout = 1500 * time.Millisecond
|
|
|
|
|
|
|
|
// dialNode returns a TCP connection to node n, racing IPv4 and IPv6
|
|
|
|
// (both as applicable) against each other.
|
|
|
|
// A node is only given dialNodeTimeout to connect.
|
|
|
|
//
|
|
|
|
// TODO(bradfitz): longer if no options remain perhaps? ... Or longer
|
|
|
|
// overall but have dialRegion start overlapping races?
|
|
|
|
func (c *Client) dialNode(ctx context.Context, n *tailcfg.DERPNode) (net.Conn, error) {
|
2020-08-13 22:25:54 +00:00
|
|
|
// First see if we need to use an HTTP proxy.
|
|
|
|
proxyReq := &http.Request{
|
|
|
|
Method: "GET", // doesn't really matter
|
|
|
|
URL: &url.URL{
|
|
|
|
Scheme: "https",
|
|
|
|
Host: c.tlsServerName(n),
|
|
|
|
Path: "/", // unused
|
|
|
|
},
|
|
|
|
}
|
|
|
|
if proxyURL, err := tshttpproxy.ProxyFromEnvironment(proxyReq); err == nil && proxyURL != nil {
|
|
|
|
return c.dialNodeUsingProxy(ctx, n, proxyURL)
|
|
|
|
}
|
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
type res struct {
|
|
|
|
c net.Conn
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
resc := make(chan res) // must be unbuffered
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, dialNodeTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
2023-04-13 01:23:22 +00:00
|
|
|
ctx = sockstats.WithSockStats(ctx, sockstats.LabelDERPHTTPClient, c.logf)
|
2023-02-03 20:07:58 +00:00
|
|
|
|
2020-05-17 16:51:38 +00:00
|
|
|
nwait := 0
|
|
|
|
startDial := func(dstPrimary, proto string) {
|
|
|
|
nwait++
|
|
|
|
go func() {
|
2022-01-29 22:52:00 +00:00
|
|
|
if proto == "tcp4" && c.preferIPv6() {
|
2023-07-27 19:56:33 +00:00
|
|
|
t, tChannel := c.clock.NewTimer(200 * time.Millisecond)
|
2022-01-29 22:52:00 +00:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
// Either user canceled original context,
|
|
|
|
// it timed out, or the v6 dial succeeded.
|
|
|
|
t.Stop()
|
|
|
|
return
|
2023-07-27 19:56:33 +00:00
|
|
|
case <-tChannel:
|
2022-01-29 22:52:00 +00:00
|
|
|
// Start v4 dial
|
|
|
|
}
|
|
|
|
}
|
2023-06-08 02:46:59 +00:00
|
|
|
dst := cmpx.Or(dstPrimary, n.HostName)
|
2020-05-17 16:51:38 +00:00
|
|
|
port := "443"
|
2021-07-09 18:16:43 +00:00
|
|
|
if n.DERPPort != 0 {
|
|
|
|
port = fmt.Sprint(n.DERPPort)
|
2020-05-17 16:51:38 +00:00
|
|
|
}
|
|
|
|
c, err := c.dialContext(ctx, proto, net.JoinHostPort(dst, port))
|
|
|
|
select {
|
|
|
|
case resc <- res{c, err}:
|
|
|
|
case <-ctx.Done():
|
|
|
|
if c != nil {
|
|
|
|
c.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
if shouldDialProto(n.IPv4, netip.Addr.Is4) {
|
2020-05-17 16:51:38 +00:00
|
|
|
startDial(n.IPv4, "tcp4")
|
|
|
|
}
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
if shouldDialProto(n.IPv6, netip.Addr.Is6) {
|
2020-05-17 16:51:38 +00:00
|
|
|
startDial(n.IPv6, "tcp6")
|
|
|
|
}
|
|
|
|
if nwait == 0 {
|
|
|
|
return nil, errors.New("both IPv4 and IPv6 are explicitly disabled for node")
|
|
|
|
}
|
|
|
|
|
|
|
|
var firstErr error
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case res := <-resc:
|
|
|
|
nwait--
|
|
|
|
if res.err == nil {
|
|
|
|
return res.c, nil
|
|
|
|
}
|
|
|
|
if firstErr == nil {
|
|
|
|
firstErr = res.err
|
|
|
|
}
|
|
|
|
if nwait == 0 {
|
|
|
|
return nil, firstErr
|
|
|
|
}
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, ctx.Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-13 22:25:54 +00:00
|
|
|
func firstStr(a, b string) string {
|
|
|
|
if a != "" {
|
|
|
|
return a
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
// dialNodeUsingProxy connects to n using a CONNECT to the HTTP(s) proxy in proxyURL.
|
2023-08-29 10:14:46 +00:00
|
|
|
func (c *Client) dialNodeUsingProxy(ctx context.Context, n *tailcfg.DERPNode, proxyURL *url.URL) (_ net.Conn, err error) {
|
2020-08-13 22:25:54 +00:00
|
|
|
pu := proxyURL
|
2023-08-29 10:14:46 +00:00
|
|
|
var proxyConn net.Conn
|
2020-08-13 22:25:54 +00:00
|
|
|
if pu.Scheme == "https" {
|
|
|
|
var d tls.Dialer
|
|
|
|
proxyConn, err = d.DialContext(ctx, "tcp", net.JoinHostPort(pu.Hostname(), firstStr(pu.Port(), "443")))
|
|
|
|
} else {
|
|
|
|
var d net.Dialer
|
|
|
|
proxyConn, err = d.DialContext(ctx, "tcp", net.JoinHostPort(pu.Hostname(), firstStr(pu.Port(), "80")))
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if err != nil && proxyConn != nil {
|
|
|
|
// In a goroutine in case it's a *tls.Conn (that can block on Close)
|
|
|
|
// TODO(bradfitz): track the underlying tcp.Conn and just close that instead.
|
|
|
|
go proxyConn.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
done := make(chan struct{})
|
|
|
|
defer close(done)
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-done:
|
|
|
|
return
|
|
|
|
case <-ctx.Done():
|
|
|
|
proxyConn.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
target := net.JoinHostPort(n.HostName, "443")
|
2020-08-27 03:02:16 +00:00
|
|
|
|
|
|
|
var authHeader string
|
|
|
|
if v, err := tshttpproxy.GetAuthHeader(pu); err != nil {
|
|
|
|
c.logf("derphttp: error getting proxy auth header for %v: %v", proxyURL, err)
|
|
|
|
} else if v != "" {
|
2020-08-29 03:58:14 +00:00
|
|
|
authHeader = fmt.Sprintf("Proxy-Authorization: %s\r\n", v)
|
2020-08-27 03:02:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := fmt.Fprintf(proxyConn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n%s\r\n", target, pu.Hostname(), authHeader); err != nil {
|
2020-08-13 22:25:54 +00:00
|
|
|
if ctx.Err() != nil {
|
|
|
|
return nil, ctx.Err()
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
br := bufio.NewReader(proxyConn)
|
|
|
|
res, err := http.ReadResponse(br, nil)
|
|
|
|
if err != nil {
|
|
|
|
if ctx.Err() != nil {
|
|
|
|
return nil, ctx.Err()
|
|
|
|
}
|
|
|
|
c.logf("derphttp: CONNECT dial to %s: %v", target, err)
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
c.logf("derphttp: CONNECT dial to %s: %v", target, res.Status)
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
return nil, fmt.Errorf("invalid response status from HTTP proxy %s on CONNECT to %s: %v", pu, target, res.Status)
|
|
|
|
}
|
|
|
|
return proxyConn, nil
|
|
|
|
}
|
|
|
|
|
2021-10-28 22:42:50 +00:00
|
|
|
func (c *Client) Send(dstKey key.NodePublic, b []byte) error {
|
2023-07-31 01:58:13 +00:00
|
|
|
client, _, err := c.connect(c.newContext(), "derphttp.Client.Send")
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := client.Send(dstKey, b); err != nil {
|
2020-04-11 20:35:02 +00:00
|
|
|
c.closeForReconnect(client)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-12-28 01:58:33 +00:00
|
|
|
func (c *Client) registerPing(m derp.PingMessage, ch chan<- bool) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if c.pingOut == nil {
|
|
|
|
c.pingOut = map[derp.PingMessage]chan<- bool{}
|
|
|
|
}
|
|
|
|
c.pingOut[m] = ch
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) unregisterPing(m derp.PingMessage) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
delete(c.pingOut, m)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) handledPong(m derp.PongMessage) bool {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
k := derp.PingMessage(m)
|
|
|
|
if ch, ok := c.pingOut[k]; ok {
|
|
|
|
ch <- true
|
|
|
|
delete(c.pingOut, k)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ping sends a ping to the peer and waits for it either to be
|
|
|
|
// acknowledged (in which case Ping returns nil) or waits for ctx to
|
|
|
|
// be over and returns an error. It will wait at most 5 seconds
|
|
|
|
// before returning an error.
|
|
|
|
//
|
|
|
|
// Another goroutine must be in a loop calling Recv or
|
|
|
|
// RecvDetail or ping responses won't be handled.
|
|
|
|
func (c *Client) Ping(ctx context.Context) error {
|
|
|
|
maxDL := time.Now().Add(5 * time.Second)
|
|
|
|
if dl, ok := ctx.Deadline(); !ok || dl.After(maxDL) {
|
|
|
|
var cancel context.CancelFunc
|
|
|
|
ctx, cancel = context.WithDeadline(ctx, maxDL)
|
|
|
|
defer cancel()
|
|
|
|
}
|
|
|
|
var data derp.PingMessage
|
|
|
|
rand.Read(data[:])
|
|
|
|
gotPing := make(chan bool, 1)
|
|
|
|
c.registerPing(data, gotPing)
|
|
|
|
defer c.unregisterPing(data)
|
|
|
|
if err := c.SendPing(data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-gotPing:
|
|
|
|
return nil
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// SendPing writes a ping message, without any implicit connect or
|
|
|
|
// reconnect. This is a lower-level interface that writes a frame
|
|
|
|
// without any implicit handling of the response pong, if any. For a
|
|
|
|
// higher-level interface, use Ping.
|
2021-12-27 19:58:09 +00:00
|
|
|
func (c *Client) SendPing(data [8]byte) error {
|
|
|
|
c.mu.Lock()
|
|
|
|
closed, client := c.closed, c.client
|
|
|
|
c.mu.Unlock()
|
|
|
|
if closed {
|
|
|
|
return ErrClientClosed
|
|
|
|
}
|
|
|
|
if client == nil {
|
|
|
|
return errors.New("client not connected")
|
|
|
|
}
|
|
|
|
return client.SendPing(data)
|
|
|
|
}
|
|
|
|
|
2021-12-29 02:01:50 +00:00
|
|
|
// LocalAddr reports c's local TCP address, without any implicit
|
|
|
|
// connect or reconnect.
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
func (c *Client) LocalAddr() (netip.AddrPort, error) {
|
2021-12-29 02:01:50 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
closed, client := c.closed, c.client
|
|
|
|
c.mu.Unlock()
|
|
|
|
if closed {
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
return netip.AddrPort{}, ErrClientClosed
|
2021-12-29 02:01:50 +00:00
|
|
|
}
|
|
|
|
if client == nil {
|
all: convert more code to use net/netip directly
perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
goimports -w .
Then delete some stuff from the net/netaddr shim package which is no
longer neeed.
Updates #5162
Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
2022-07-26 04:14:09 +00:00
|
|
|
return netip.AddrPort{}, errors.New("client not connected")
|
2021-12-29 02:01:50 +00:00
|
|
|
}
|
|
|
|
return client.LocalAddr()
|
|
|
|
}
|
|
|
|
|
2021-10-28 22:42:50 +00:00
|
|
|
func (c *Client) ForwardPacket(from, to key.NodePublic, b []byte) error {
|
2023-07-31 01:58:13 +00:00
|
|
|
client, _, err := c.connect(c.newContext(), "derphttp.Client.ForwardPacket")
|
2020-06-03 21:42:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := client.ForwardPacket(from, to, b); err != nil {
|
|
|
|
c.closeForReconnect(client)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-03-09 20:53:02 +00:00
|
|
|
// SendPong sends a reply to a ping, with the ping's provided
|
|
|
|
// challenge/identifier data.
|
|
|
|
//
|
|
|
|
// Unlike other send methods, SendPong makes no attempt to connect or
|
|
|
|
// reconnect to the peer. It's best effort. If there's a connection
|
|
|
|
// problem, the server will choose to hang up on us if we're not
|
|
|
|
// replying.
|
|
|
|
func (c *Client) SendPong(data [8]byte) error {
|
|
|
|
c.mu.Lock()
|
|
|
|
if c.closed {
|
|
|
|
c.mu.Unlock()
|
|
|
|
return ErrClientClosed
|
|
|
|
}
|
|
|
|
if c.client == nil {
|
|
|
|
c.mu.Unlock()
|
|
|
|
return errors.New("not connected")
|
|
|
|
}
|
|
|
|
dc := c.client
|
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
return dc.SendPong(data)
|
|
|
|
}
|
|
|
|
|
2021-03-12 17:45:37 +00:00
|
|
|
// SetCanAckPings sets whether this client will reply to ping requests from the server.
|
|
|
|
//
|
|
|
|
// This only affects future connections.
|
|
|
|
func (c *Client) SetCanAckPings(v bool) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
c.canAckPings = v
|
|
|
|
}
|
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
// NotePreferred notes whether this Client is the caller's preferred
|
|
|
|
// (home) DERP node. It's only used for stats.
|
|
|
|
func (c *Client) NotePreferred(v bool) {
|
|
|
|
c.mu.Lock()
|
|
|
|
if c.preferred == v {
|
|
|
|
c.mu.Unlock()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.preferred = v
|
|
|
|
client := c.client
|
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
if client != nil {
|
|
|
|
if err := client.NotePreferred(v); err != nil {
|
2020-04-11 20:35:02 +00:00
|
|
|
c.closeForReconnect(client)
|
2020-03-05 23:00:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-25 16:33:10 +00:00
|
|
|
// ClosePeer asks the server to close target's TCP connection.
|
|
|
|
//
|
|
|
|
// Only trusted connections (using MeshKey) are allowed to use this.
|
2021-10-28 22:42:50 +00:00
|
|
|
func (c *Client) ClosePeer(target key.NodePublic) error {
|
2023-07-31 01:58:13 +00:00
|
|
|
client, _, err := c.connect(c.newContext(), "derphttp.Client.ClosePeer")
|
2020-06-25 16:33:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = client.ClosePeer(target)
|
|
|
|
if err != nil {
|
|
|
|
c.closeForReconnect(client)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-06-15 17:26:50 +00:00
|
|
|
// Recv reads a message from c. The returned message may alias memory from Client.
|
|
|
|
// The message should only be used until the next Client call.
|
|
|
|
func (c *Client) Recv() (derp.ReceivedMessage, error) {
|
|
|
|
m, _, err := c.RecvDetail()
|
2020-06-04 18:35:53 +00:00
|
|
|
return m, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// RecvDetail is like Recv, but additional returns the connection generation on each message.
|
|
|
|
// The connGen value is incremented every time the derphttp.Client reconnects to the server.
|
2020-06-15 17:26:50 +00:00
|
|
|
func (c *Client) RecvDetail() (m derp.ReceivedMessage, connGen int, err error) {
|
2023-07-31 01:58:13 +00:00
|
|
|
client, connGen, err := c.connect(c.newContext(), "derphttp.Client.Recv")
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-06-04 18:35:53 +00:00
|
|
|
return nil, 0, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-12-28 01:58:33 +00:00
|
|
|
for {
|
|
|
|
m, err = client.Recv()
|
|
|
|
switch m := m.(type) {
|
|
|
|
case derp.PongMessage:
|
|
|
|
if c.handledPong(m) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
c.closeForReconnect(client)
|
|
|
|
if c.isClosed() {
|
|
|
|
err = ErrClientClosed
|
|
|
|
}
|
2021-02-12 20:04:16 +00:00
|
|
|
}
|
2021-12-28 01:58:33 +00:00
|
|
|
return m, connGen, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-12 20:04:16 +00:00
|
|
|
func (c *Client) isClosed() bool {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
return c.closed
|
|
|
|
}
|
|
|
|
|
2020-02-18 16:57:11 +00:00
|
|
|
// Close closes the client. It will not automatically reconnect after
|
|
|
|
// being closed.
|
2020-02-05 22:16:58 +00:00
|
|
|
func (c *Client) Close() error {
|
2022-10-13 18:10:11 +00:00
|
|
|
if c.cancelCtx != nil {
|
|
|
|
c.cancelCtx() // not in lock, so it can cancel Connect, which holds mu
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if c.closed {
|
|
|
|
return ErrClientClosed
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
c.closed = true
|
2020-02-28 21:38:45 +00:00
|
|
|
if c.netConn != nil {
|
|
|
|
c.netConn.Close()
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// closeForReconnect closes the underlying network connection and
|
|
|
|
// zeros out the client field so future calls to Connect will
|
|
|
|
// reconnect.
|
2020-04-11 20:35:02 +00:00
|
|
|
//
|
|
|
|
// The provided brokenClient is the client to forget. If current
|
|
|
|
// client is not brokenClient, closeForReconnect does nothing. (This
|
|
|
|
// prevents a send and receive goroutine from failing at the ~same
|
|
|
|
// time and both calling closeForReconnect and the caller goroutines
|
|
|
|
// forever calling closeForReconnect in lockstep endlessly;
|
|
|
|
// https://github.com/tailscale/tailscale/pull/264)
|
|
|
|
func (c *Client) closeForReconnect(brokenClient *derp.Client) {
|
2020-02-28 21:38:45 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2020-04-11 20:35:02 +00:00
|
|
|
if c.client != brokenClient {
|
|
|
|
return
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
if c.netConn != nil {
|
|
|
|
c.netConn.Close()
|
|
|
|
c.netConn = nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
c.client = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrClientClosed = errors.New("derphttp.Client closed")
|
2020-08-18 22:32:32 +00:00
|
|
|
|
2021-10-28 22:42:50 +00:00
|
|
|
func parseMetaCert(certs []*x509.Certificate) (serverPub key.NodePublic, serverProtoVersion int) {
|
2020-08-18 22:32:32 +00:00
|
|
|
for _, cert := range certs {
|
2022-11-18 18:13:14 +00:00
|
|
|
// Look for derpkey prefix added by initMetacert() on the server side.
|
2023-02-01 21:43:06 +00:00
|
|
|
if pubHex, ok := strings.CutPrefix(cert.Subject.CommonName, "derpkey"); ok {
|
2020-08-18 22:32:32 +00:00
|
|
|
var err error
|
2022-11-18 18:13:14 +00:00
|
|
|
serverPub, err = key.ParseNodePublicUntyped(mem.S(pubHex))
|
2020-08-18 22:32:32 +00:00
|
|
|
if err == nil && cert.SerialNumber.BitLen() <= 8 { // supports up to version 255
|
|
|
|
return serverPub, int(cert.SerialNumber.Int64())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-10-28 22:42:50 +00:00
|
|
|
return key.NodePublic{}, 0
|
2020-08-18 22:32:32 +00:00
|
|
|
}
|