2020-02-05 22:16:58 +00:00
|
|
|
// Copyright (c) 2020 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 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"
|
2020-02-05 22:16:58 +00:00
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
2020-02-28 21:18:10 +00:00
|
|
|
"io"
|
2020-02-05 22:16:58 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"sync"
|
2020-02-28 21:18:10 +00:00
|
|
|
"time"
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
"tailscale.com/derp"
|
2020-03-05 18:29:19 +00:00
|
|
|
"tailscale.com/net/dnscache"
|
2020-02-17 21:52:11 +00:00
|
|
|
"tailscale.com/types/key"
|
2020-02-15 03:23:16 +00:00
|
|
|
"tailscale.com/types/logger"
|
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-03-05 18:29:19 +00:00
|
|
|
TLSConfig *tls.Config // for sever connection, optional, nil means default
|
|
|
|
DNSCache *dnscache.Resolver // optional; if nil, no caching
|
2020-03-03 21:48:57 +00:00
|
|
|
|
2020-02-17 21:52:11 +00:00
|
|
|
privateKey key.Private
|
2020-02-11 17:37:20 +00:00
|
|
|
logf logger.Logf
|
2020-02-05 22:16:58 +00:00
|
|
|
url *url.URL
|
|
|
|
|
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
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
mu sync.Mutex
|
|
|
|
preferred bool
|
|
|
|
closed bool
|
|
|
|
netConn io.Closer
|
|
|
|
client *derp.Client
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-18 16:57:11 +00:00
|
|
|
// NewClient returns a new DERP-over-HTTP client. It connects lazily.
|
|
|
|
// To trigger a connection use Connect.
|
2020-02-17 21:52:11 +00:00
|
|
|
func NewClient(privateKey key.Private, 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)
|
|
|
|
}
|
|
|
|
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,
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
_, err := c.connect(ctx, "derphttp.Client.Connect")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
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 ""
|
|
|
|
}
|
|
|
|
|
2020-02-18 16:57:11 +00:00
|
|
|
func (c *Client) connect(ctx context.Context, caller string) (client *derp.Client, err error) {
|
2020-02-28 21:18:10 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
if c.closed {
|
2020-02-05 22:16:58 +00:00
|
|
|
return nil, ErrClientClosed
|
|
|
|
}
|
|
|
|
if c.client != nil {
|
|
|
|
return c.client, nil
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
c.logf("%s: connecting to %v", caller, c.url)
|
|
|
|
|
|
|
|
// 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-02-28 21:18:10 +00:00
|
|
|
var tcpConn net.Conn
|
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)
|
|
|
|
}
|
|
|
|
err = fmt.Errorf("%s connect to %v: %v", caller, c.url, err)
|
|
|
|
if tcpConn != nil {
|
|
|
|
go tcpConn.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-03-05 18:29:19 +00:00
|
|
|
host := c.url.Hostname()
|
|
|
|
hostOrIP := host
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
var d net.Dialer
|
2020-03-05 18:29:19 +00:00
|
|
|
|
|
|
|
if c.DNSCache != nil {
|
|
|
|
ip, err := c.DNSCache.LookupIP(ctx, host)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
hostOrIP = ip.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
tcpConn, err = d.DialContext(ctx, "tcp", net.JoinHostPort(hostOrIP, urlPort(c.url)))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-03-05 20:34:57 +00:00
|
|
|
return nil, fmt.Errorf("dial of %q: %v", host, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
// Now that we have a TCP connection, force close it.
|
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
var httpConn net.Conn // a TCP conn or a TLS conn; what we speak HTTP to
|
|
|
|
if c.url.Scheme == "https" {
|
2020-03-03 21:48:57 +00:00
|
|
|
tlsConfig := &tls.Config{}
|
|
|
|
if c.TLSConfig != nil {
|
|
|
|
tlsConfig = c.TLSConfig.Clone()
|
|
|
|
}
|
|
|
|
tlsConfig.ServerName = c.url.Host
|
|
|
|
httpConn = tls.Client(tcpConn, tlsConfig)
|
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-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", c.url.String(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
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
|
|
|
|
|
|
|
if err := req.Write(brw); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
if err := brw.Flush(); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
resp, err := http.ReadResponse(brw.Reader, req)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusSwitchingProtocols {
|
|
|
|
b, _ := ioutil.ReadAll(resp.Body)
|
|
|
|
resp.Body.Close()
|
|
|
|
return nil, fmt.Errorf("GET failed: %v: %s", err, b)
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
derpClient, err := derp.NewClient(c.privateKey, httpConn, brw, c.logf)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
if c.preferred {
|
|
|
|
if err := derpClient.NotePreferred(true); err != nil {
|
|
|
|
go httpConn.Close()
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2020-02-28 21:18:10 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
c.client = derpClient
|
2020-02-28 21:18:10 +00:00
|
|
|
c.netConn = tcpConn
|
2020-02-05 22:16:58 +00:00
|
|
|
return c.client, nil
|
|
|
|
}
|
|
|
|
|
2020-02-17 21:52:11 +00:00
|
|
|
func (c *Client) Send(dstKey key.Public, b []byte) error {
|
2020-02-18 16:57:11 +00:00
|
|
|
client, err := c.connect(context.TODO(), "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-02-28 21:38:45 +00:00
|
|
|
c.closeForReconnect()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
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 {
|
|
|
|
c.closeForReconnect()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-21 03:10:54 +00:00
|
|
|
func (c *Client) Recv(b []byte) (derp.ReceivedMessage, error) {
|
2020-02-18 16:57:11 +00:00
|
|
|
client, err := c.connect(context.TODO(), "derphttp.Client.Recv")
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-02-21 03:10:54 +00:00
|
|
|
return nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-21 03:10:54 +00:00
|
|
|
m, err := client.Recv(b)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-02-28 21:38:45 +00:00
|
|
|
c.closeForReconnect()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-21 03:10:54 +00:00
|
|
|
return m, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
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 {
|
2020-02-28 21:18:10 +00:00
|
|
|
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.
|
|
|
|
func (c *Client) closeForReconnect() {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
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")
|