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 derp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2021-08-31 20:27:24 +01:00
|
|
|
"encoding/binary"
|
2020-02-05 22:16:58 +00:00
|
|
|
"encoding/json"
|
2020-02-20 20:27:12 +00:00
|
|
|
"errors"
|
2020-02-05 22:16:58 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-07-26 04:55:44 +01:00
|
|
|
"net/netip"
|
2020-03-05 23:00:56 +00:00
|
|
|
"sync"
|
2020-02-05 22:16:58 +00:00
|
|
|
"time"
|
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
"go4.org/mem"
|
2021-08-19 19:51:08 +01:00
|
|
|
"golang.org/x/time/rate"
|
2022-08-04 18:43:49 +01:00
|
|
|
"tailscale.com/syncs"
|
2023-07-27 20:56:33 +01:00
|
|
|
"tailscale.com/tstime"
|
2020-02-17 21:17:40 +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
|
|
|
)
|
|
|
|
|
2020-06-03 22:42:20 +01:00
|
|
|
// Client is a DERP client.
|
2020-02-05 22:16:58 +00:00
|
|
|
type Client struct {
|
2021-10-28 23:42:50 +01:00
|
|
|
serverKey key.NodePublic // of the DERP server; not a machine or node key
|
|
|
|
privateKey key.NodePrivate
|
|
|
|
publicKey key.NodePublic // of privateKey
|
2021-03-12 17:45:37 +00:00
|
|
|
logf logger.Logf
|
|
|
|
nc Conn
|
|
|
|
br *bufio.Reader
|
|
|
|
meshKey string
|
|
|
|
canAckPings bool
|
2021-07-13 06:04:16 +01:00
|
|
|
isProber bool
|
2020-03-05 23:00:56 +00:00
|
|
|
|
2021-08-19 19:51:08 +01:00
|
|
|
wmu sync.Mutex // hold while writing to bw
|
|
|
|
bw *bufio.Writer
|
|
|
|
rate *rate.Limiter // if non-nil, rate limiter to use
|
2020-06-15 18:26:50 +01:00
|
|
|
|
|
|
|
// Owned by Recv:
|
2022-08-04 18:43:49 +01:00
|
|
|
peeked int // bytes to discard on next Recv
|
|
|
|
readErr syncs.AtomicValue[error] // sticky (set by Recv)
|
2023-07-27 20:56:33 +01:00
|
|
|
|
|
|
|
clock tstime.Clock
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-06-04 19:40:12 +01:00
|
|
|
// ClientOpt is an option passed to NewClient.
|
|
|
|
type ClientOpt interface {
|
|
|
|
update(*clientOpt)
|
2020-06-01 23:19:41 +01:00
|
|
|
}
|
|
|
|
|
2020-06-04 19:40:12 +01:00
|
|
|
type clientOptFunc func(*clientOpt)
|
|
|
|
|
|
|
|
func (f clientOptFunc) update(o *clientOpt) { f(o) }
|
|
|
|
|
|
|
|
// clientOpt are the options passed to newClient.
|
|
|
|
type clientOpt struct {
|
2021-03-12 17:45:37 +00:00
|
|
|
MeshKey string
|
2021-10-28 23:42:50 +01:00
|
|
|
ServerPub key.NodePublic
|
2021-03-12 17:45:37 +00:00
|
|
|
CanAckPings bool
|
2021-07-13 06:04:16 +01:00
|
|
|
IsProber bool
|
2020-06-04 19:40:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// MeshKey returns a ClientOpt to pass to the DERP server during connect to get
|
|
|
|
// access to join the mesh.
|
2020-06-01 23:19:41 +01:00
|
|
|
//
|
2020-06-04 19:40:12 +01:00
|
|
|
// An empty key means to not use a mesh key.
|
|
|
|
func MeshKey(key string) ClientOpt { return clientOptFunc(func(o *clientOpt) { o.MeshKey = key }) }
|
|
|
|
|
2021-07-13 06:04:16 +01:00
|
|
|
// IsProber returns a ClientOpt to pass to the DERP server during connect to
|
|
|
|
// declare that this client is a a prober.
|
|
|
|
func IsProber(v bool) ClientOpt { return clientOptFunc(func(o *clientOpt) { o.IsProber = v }) }
|
|
|
|
|
2020-08-18 23:32:32 +01:00
|
|
|
// ServerPublicKey returns a ClientOpt to declare that the server's DERP public key is known.
|
|
|
|
// If key is the zero value, the returned ClientOpt is a no-op.
|
2021-10-28 23:42:50 +01:00
|
|
|
func ServerPublicKey(key key.NodePublic) ClientOpt {
|
2020-08-18 23:32:32 +01:00
|
|
|
return clientOptFunc(func(o *clientOpt) { o.ServerPub = key })
|
|
|
|
}
|
|
|
|
|
2021-03-12 17:45:37 +00:00
|
|
|
// CanAckPings returns a ClientOpt to set whether it advertises to the
|
|
|
|
// server that it's capable of acknowledging ping requests.
|
|
|
|
func CanAckPings(v bool) ClientOpt {
|
|
|
|
return clientOptFunc(func(o *clientOpt) { o.CanAckPings = v })
|
|
|
|
}
|
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
func NewClient(privateKey key.NodePrivate, nc Conn, brw *bufio.ReadWriter, logf logger.Logf, opts ...ClientOpt) (*Client, error) {
|
2020-06-04 19:40:12 +01:00
|
|
|
var opt clientOpt
|
|
|
|
for _, o := range opts {
|
|
|
|
if o == nil {
|
|
|
|
return nil, errors.New("nil ClientOpt")
|
|
|
|
}
|
|
|
|
o.update(&opt)
|
|
|
|
}
|
|
|
|
return newClient(privateKey, nc, brw, logf, opt)
|
|
|
|
}
|
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
func newClient(privateKey key.NodePrivate, nc Conn, brw *bufio.ReadWriter, logf logger.Logf, opt clientOpt) (*Client, error) {
|
2020-02-05 22:16:58 +00:00
|
|
|
c := &Client{
|
2021-03-12 17:45:37 +00:00
|
|
|
privateKey: privateKey,
|
|
|
|
publicKey: privateKey.Public(),
|
|
|
|
logf: logf,
|
|
|
|
nc: nc,
|
|
|
|
br: brw.Reader,
|
|
|
|
bw: brw.Writer,
|
|
|
|
meshKey: opt.MeshKey,
|
|
|
|
canAckPings: opt.CanAckPings,
|
2021-07-13 06:04:16 +01:00
|
|
|
isProber: opt.IsProber,
|
2023-07-27 20:56:33 +01:00
|
|
|
clock: tstime.StdClock{},
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-08-18 23:32:32 +01:00
|
|
|
if opt.ServerPub.IsZero() {
|
|
|
|
if err := c.recvServerKey(); err != nil {
|
|
|
|
return nil, fmt.Errorf("derp.Client: failed to receive server key: %v", err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
c.serverKey = opt.ServerPub
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if err := c.sendClientKey(); err != nil {
|
|
|
|
return nil, fmt.Errorf("derp.Client: failed to send client key: %v", err)
|
|
|
|
}
|
|
|
|
return c, nil
|
|
|
|
}
|
|
|
|
|
2024-09-12 16:44:07 +01:00
|
|
|
func (c *Client) PublicKey() key.NodePublic { return c.publicKey }
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
func (c *Client) recvServerKey() error {
|
2020-02-20 20:27:12 +00:00
|
|
|
var buf [40]byte
|
|
|
|
t, flen, err := readFrame(c.br, 1<<10, buf[:])
|
|
|
|
if err == io.ErrShortBuffer {
|
|
|
|
// For future-proofing, allow server to send more in its greeting.
|
|
|
|
err = nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
if err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
if flen < uint32(len(buf)) || t != frameServerKey || string(buf[:len(magic)]) != magic {
|
|
|
|
return errors.New("invalid server greeting")
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
c.serverKey = key.NodePublicFromRaw32(mem.B(buf[len(magic):]))
|
2020-02-05 22:16:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-08-18 00:14:07 +01:00
|
|
|
func (c *Client) parseServerInfo(b []byte) (*serverInfo, error) {
|
2020-02-20 20:27:12 +00:00
|
|
|
const maxLength = nonceLen + maxInfoLen
|
2020-08-18 00:14:07 +01:00
|
|
|
fl := len(b)
|
2020-02-20 20:27:12 +00:00
|
|
|
if fl < nonceLen {
|
|
|
|
return nil, fmt.Errorf("short serverInfo frame")
|
|
|
|
}
|
|
|
|
if fl > maxLength {
|
|
|
|
return nil, fmt.Errorf("long serverInfo frame")
|
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
msg, ok := c.privateKey.OpenFrom(c.serverKey, b)
|
2020-02-05 22:16:58 +00:00
|
|
|
if !ok {
|
2021-10-28 23:42:50 +01:00
|
|
|
return nil, fmt.Errorf("failed to open naclbox from server key %s", c.serverKey)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
info := new(serverInfo)
|
|
|
|
if err := json.Unmarshal(msg, info); err != nil {
|
2020-08-18 00:14:07 +01:00
|
|
|
return nil, fmt.Errorf("invalid JSON: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return info, nil
|
|
|
|
}
|
|
|
|
|
2020-03-04 17:35:32 +00:00
|
|
|
type clientInfo struct {
|
2020-06-01 23:19:41 +01:00
|
|
|
// MeshKey optionally specifies a pre-shared key used by
|
|
|
|
// trusted clients. It's required to subscribe to the
|
|
|
|
// connection list & forward packets. It's empty for regular
|
|
|
|
// users.
|
2020-08-19 22:36:43 +01:00
|
|
|
MeshKey string `json:"meshKey,omitempty"`
|
2021-03-12 17:45:37 +00:00
|
|
|
|
2024-01-12 20:46:23 +00:00
|
|
|
// Version is the DERP protocol version that the client was built with.
|
|
|
|
// See the ProtocolVersion const.
|
|
|
|
Version int `json:"version,omitempty"`
|
|
|
|
|
2021-03-12 17:45:37 +00:00
|
|
|
// CanAckPings is whether the client declares it's able to ack
|
|
|
|
// pings.
|
|
|
|
CanAckPings bool
|
2021-07-13 06:04:16 +01:00
|
|
|
|
|
|
|
// IsProber is whether this client is a prober.
|
|
|
|
IsProber bool `json:",omitempty"`
|
2020-03-04 17:35:32 +00:00
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
func (c *Client) sendClientKey() error {
|
2020-06-01 23:19:41 +01:00
|
|
|
msg, err := json.Marshal(clientInfo{
|
2021-03-12 17:45:37 +00:00
|
|
|
Version: ProtocolVersion,
|
|
|
|
MeshKey: c.meshKey,
|
|
|
|
CanAckPings: c.canAckPings,
|
2021-07-13 06:04:16 +01:00
|
|
|
IsProber: c.isProber,
|
2020-06-01 23:19:41 +01:00
|
|
|
})
|
2020-03-04 17:35:32 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
msgbox := c.privateKey.SealTo(c.serverKey, msg)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
buf := make([]byte, 0, keyLen+len(msgbox))
|
|
|
|
buf = c.publicKey.AppendTo(buf)
|
2020-02-20 20:27:12 +00:00
|
|
|
buf = append(buf, msgbox...)
|
|
|
|
return writeFrame(c.bw, frameClientInfo, buf)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-06-03 22:42:20 +01:00
|
|
|
// ServerPublicKey returns the server's public key.
|
2021-10-28 23:42:50 +01:00
|
|
|
func (c *Client) ServerPublicKey() key.NodePublic { return c.serverKey }
|
2020-06-03 22:42:20 +01:00
|
|
|
|
2020-02-20 20:27:12 +00:00
|
|
|
// Send sends a packet to the Tailscale node identified by dstKey.
|
|
|
|
//
|
|
|
|
// It is an error if the packet is larger than 64KB.
|
2021-10-28 23:42:50 +01:00
|
|
|
func (c *Client) Send(dstKey key.NodePublic, pkt []byte) error { return c.send(dstKey, pkt) }
|
2020-02-20 20:27:12 +00:00
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
func (c *Client) send(dstKey key.NodePublic, pkt []byte) (ret error) {
|
2020-02-05 22:16:58 +00:00
|
|
|
defer func() {
|
2020-02-20 20:27:12 +00:00
|
|
|
if ret != nil {
|
2020-03-12 15:05:03 +00:00
|
|
|
ret = fmt.Errorf("derp.Send: %w", ret)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-02-21 03:10:54 +00:00
|
|
|
if len(pkt) > MaxPacketSize {
|
2020-02-20 20:27:12 +00:00
|
|
|
return fmt.Errorf("packet too big: %d", len(pkt))
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
2021-08-19 19:51:08 +01:00
|
|
|
if c.rate != nil {
|
2021-10-30 01:35:51 +01:00
|
|
|
pktLen := frameHeaderLen + key.NodePublicRawLen + len(pkt)
|
2023-07-27 20:56:33 +01:00
|
|
|
if !c.rate.AllowN(c.clock.Now(), pktLen) {
|
2021-08-19 19:51:08 +01:00
|
|
|
return nil // drop
|
|
|
|
}
|
|
|
|
}
|
2021-10-30 01:35:51 +01:00
|
|
|
if err := writeFrameHeader(c.bw, frameSendPacket, uint32(key.NodePublicRawLen+len(pkt))); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
if _, err := c.bw.Write(dstKey.AppendTo(nil)); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
if _, err := c.bw.Write(pkt); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 17:11:43 +00:00
|
|
|
return c.bw.Flush()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-10-28 23:42:50 +01:00
|
|
|
func (c *Client) ForwardPacket(srcKey, dstKey key.NodePublic, pkt []byte) (err error) {
|
2020-06-03 22:42:20 +01:00
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("derp.ForwardPacket: %w", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if len(pkt) > MaxPacketSize {
|
|
|
|
return fmt.Errorf("packet too big: %d", len(pkt))
|
|
|
|
}
|
|
|
|
|
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
|
|
|
|
2023-07-27 20:56:33 +01:00
|
|
|
timer := c.clock.AfterFunc(5*time.Second, c.writeTimeoutFired)
|
2020-06-03 22:42:20 +01:00
|
|
|
defer timer.Stop()
|
|
|
|
|
|
|
|
if err := writeFrameHeader(c.bw, frameForwardPacket, uint32(keyLen*2+len(pkt))); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
if _, err := c.bw.Write(srcKey.AppendTo(nil)); err != nil {
|
2020-06-03 22:42:20 +01:00
|
|
|
return err
|
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
if _, err := c.bw.Write(dstKey.AppendTo(nil)); err != nil {
|
2020-06-03 22:42:20 +01:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := c.bw.Write(pkt); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.bw.Flush()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) writeTimeoutFired() { c.nc.Close() }
|
|
|
|
|
2021-12-27 19:58:09 +00:00
|
|
|
func (c *Client) SendPing(data [8]byte) error {
|
|
|
|
return c.sendPingOrPong(framePing, data)
|
|
|
|
}
|
|
|
|
|
2021-03-09 20:53:02 +00:00
|
|
|
func (c *Client) SendPong(data [8]byte) error {
|
2021-12-27 19:58:09 +00:00
|
|
|
return c.sendPingOrPong(framePong, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) sendPingOrPong(typ frameType, data [8]byte) error {
|
2021-03-09 20:53:02 +00:00
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
2021-12-27 19:58:09 +00:00
|
|
|
if err := writeFrameHeader(c.bw, typ, 8); err != nil {
|
2021-03-09 20:53:02 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := c.bw.Write(data[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.bw.Flush()
|
|
|
|
}
|
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
// NotePreferred sends a packet that tells the server whether this
|
|
|
|
// client is the user's preferred server. This is only used in the
|
|
|
|
// server for stats.
|
|
|
|
func (c *Client) NotePreferred(preferred bool) (err error) {
|
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("derp.NotePreferred: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
|
|
|
|
|
|
|
if err := writeFrameHeader(c.bw, frameNotePreferred, 1); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
var b byte = 0x00
|
|
|
|
if preferred {
|
|
|
|
b = 0x01
|
|
|
|
}
|
|
|
|
if err := c.bw.WriteByte(b); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.bw.Flush()
|
|
|
|
}
|
|
|
|
|
2020-06-01 23:19:41 +01:00
|
|
|
// WatchConnectionChanges sends a request to subscribe to the peer's connection list.
|
2020-06-25 17:33:10 +01:00
|
|
|
// It's a fatal error if the client wasn't created using MeshKey.
|
2020-06-01 23:19:41 +01:00
|
|
|
func (c *Client) WatchConnectionChanges() error {
|
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
|
|
|
if err := writeFrameHeader(c.bw, frameWatchConns, 0); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return c.bw.Flush()
|
|
|
|
}
|
|
|
|
|
2020-06-25 17:33:10 +01:00
|
|
|
// ClosePeer asks the server to close target's TCP connection.
|
|
|
|
// It's a fatal error if the client wasn't created using MeshKey.
|
2021-10-28 23:42:50 +01:00
|
|
|
func (c *Client) ClosePeer(target key.NodePublic) error {
|
2020-06-25 17:33:10 +01:00
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
2021-10-28 23:42:50 +01:00
|
|
|
return writeFrame(c.bw, frameClosePeer, target.AppendTo(nil))
|
2020-06-25 17:33:10 +01:00
|
|
|
}
|
|
|
|
|
2020-02-21 03:10:54 +00:00
|
|
|
// ReceivedMessage represents a type returned by Client.Recv. Unless
|
|
|
|
// otherwise documented, the returned message aliases the byte slice
|
|
|
|
// provided to Recv and thus the message is only as good as that
|
|
|
|
// buffer, which is up to the caller.
|
|
|
|
type ReceivedMessage interface {
|
|
|
|
msg()
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReceivedPacket is a ReceivedMessage representing an incoming packet.
|
2020-03-04 17:35:32 +00:00
|
|
|
type ReceivedPacket struct {
|
2021-10-28 23:42:50 +01:00
|
|
|
Source key.NodePublic
|
2020-03-04 17:35:32 +00:00
|
|
|
// Data is the received packet bytes. It aliases the memory
|
|
|
|
// passed to Client.Recv.
|
|
|
|
Data []byte
|
|
|
|
}
|
2020-02-21 03:10:54 +00:00
|
|
|
|
|
|
|
func (ReceivedPacket) msg() {}
|
|
|
|
|
2020-03-22 01:24:28 +00:00
|
|
|
// PeerGoneMessage is a ReceivedMessage that indicates that the client
|
2023-03-25 02:11:48 +00:00
|
|
|
// identified by the underlying public key is not connected to this
|
|
|
|
// server.
|
2024-09-24 23:11:31 +01:00
|
|
|
//
|
|
|
|
// It has only historically been sent by the server when the client
|
|
|
|
// connection count decremented from 1 to 0 and not from e.g. 2 to 1.
|
|
|
|
// See https://github.com/tailscale/tailscale/issues/13566 for details.
|
2023-03-25 02:11:48 +00:00
|
|
|
type PeerGoneMessage struct {
|
|
|
|
Peer key.NodePublic
|
|
|
|
Reason PeerGoneReasonType
|
|
|
|
}
|
2020-03-22 01:24:28 +00:00
|
|
|
|
|
|
|
func (PeerGoneMessage) msg() {}
|
|
|
|
|
2024-09-24 23:11:31 +01:00
|
|
|
// PeerPresentMessage is a ReceivedMessage that indicates that the client is
|
|
|
|
// connected to the server. (Only used by trusted mesh clients)
|
|
|
|
//
|
|
|
|
// It will be sent to client watchers for every new connection from a client,
|
|
|
|
// even if the client's already connected with that public key.
|
|
|
|
// See https://github.com/tailscale/tailscale/issues/13566 for PeerPresentMessage
|
|
|
|
// and PeerGoneMessage not being 1:1.
|
2023-08-16 03:35:24 +01:00
|
|
|
type PeerPresentMessage struct {
|
|
|
|
// Key is the public key of the client.
|
|
|
|
Key key.NodePublic
|
|
|
|
// IPPort is the remote IP and port of the client.
|
|
|
|
IPPort netip.AddrPort
|
2024-06-22 17:17:51 +01:00
|
|
|
// Flags is a bitmask of info about the client.
|
|
|
|
Flags PeerPresentFlags
|
2023-08-16 03:35:24 +01:00
|
|
|
}
|
2020-06-01 23:19:41 +01:00
|
|
|
|
|
|
|
func (PeerPresentMessage) msg() {}
|
|
|
|
|
2020-08-18 00:14:07 +01:00
|
|
|
// ServerInfoMessage is sent by the server upon first connect.
|
2021-08-19 19:51:08 +01:00
|
|
|
type ServerInfoMessage struct {
|
|
|
|
// TokenBucketBytesPerSecond is how many bytes per second the
|
|
|
|
// server says it will accept, including all framing bytes.
|
|
|
|
//
|
|
|
|
// Zero means unspecified. There might be a limit, but the
|
|
|
|
// client need not try to respect it.
|
|
|
|
TokenBucketBytesPerSecond int
|
|
|
|
|
|
|
|
// TokenBucketBytesBurst is how many bytes the server will
|
|
|
|
// allow to burst, temporarily violating
|
|
|
|
// TokenBucketBytesPerSecond.
|
|
|
|
//
|
|
|
|
// Zero means unspecified. There might be a limit, but the
|
|
|
|
// client need not try to respect it.
|
|
|
|
TokenBucketBytesBurst int
|
|
|
|
}
|
2020-08-18 00:14:07 +01:00
|
|
|
|
|
|
|
func (ServerInfoMessage) msg() {}
|
|
|
|
|
2021-03-09 20:53:02 +00:00
|
|
|
// PingMessage is a request from a client or server to reply to the
|
|
|
|
// other side with a PongMessage with the given payload.
|
|
|
|
type PingMessage [8]byte
|
|
|
|
|
|
|
|
func (PingMessage) msg() {}
|
|
|
|
|
2021-12-27 19:58:09 +00:00
|
|
|
// PongMessage is a reply to a PingMessage from a client or server
|
|
|
|
// with the payload sent previously in a PingMessage.
|
|
|
|
type PongMessage [8]byte
|
|
|
|
|
|
|
|
func (PongMessage) msg() {}
|
|
|
|
|
2021-03-15 16:58:52 +00:00
|
|
|
// KeepAliveMessage is a one-way empty message from server to client, just to
|
|
|
|
// keep the connection alive. It's like a PingMessage, but doesn't solicit
|
|
|
|
// a reply from the client.
|
|
|
|
type KeepAliveMessage struct{}
|
|
|
|
|
|
|
|
func (KeepAliveMessage) msg() {}
|
|
|
|
|
2021-08-31 20:27:24 +01:00
|
|
|
// HealthMessage is a one-way message from server to client, declaring the
|
|
|
|
// connection health state.
|
|
|
|
type HealthMessage struct {
|
|
|
|
// Problem, if non-empty, is a description of why the connection
|
|
|
|
// is unhealthy.
|
|
|
|
//
|
|
|
|
// The empty string means the connection is healthy again.
|
|
|
|
//
|
|
|
|
// The default condition is healthy, so the server doesn't
|
|
|
|
// broadcast a HealthMessage until a problem exists.
|
|
|
|
Problem string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (HealthMessage) msg() {}
|
|
|
|
|
|
|
|
// ServerRestartingMessage is a one-way message from server to client,
|
|
|
|
// advertising that the server is restarting.
|
|
|
|
type ServerRestartingMessage struct {
|
|
|
|
// ReconnectIn is an advisory duration that the client should wait
|
|
|
|
// before attempting to reconnect. It might be zero.
|
|
|
|
// It exists for the server to smear out the reconnects.
|
|
|
|
ReconnectIn time.Duration
|
|
|
|
|
|
|
|
// TryFor is an advisory duration for how long the client
|
|
|
|
// should attempt to reconnect before giving up and proceeding
|
|
|
|
// with its normal connection failure logic. The interval
|
|
|
|
// between retries is undefined for now.
|
|
|
|
// A server should not send a TryFor duration more than a few
|
|
|
|
// seconds.
|
|
|
|
TryFor time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ServerRestartingMessage) msg() {}
|
|
|
|
|
2020-02-21 03:10:54 +00:00
|
|
|
// Recv reads a message from the DERP server.
|
2020-06-15 18:26:50 +01:00
|
|
|
//
|
|
|
|
// The returned message may alias memory owned by the Client; it
|
|
|
|
// should only be accessed until the next call to Client.
|
|
|
|
//
|
2020-02-20 17:11:43 +00:00
|
|
|
// Once Recv returns an error, the Client is dead forever.
|
2020-06-15 18:26:50 +01:00
|
|
|
func (c *Client) Recv() (m ReceivedMessage, err error) {
|
|
|
|
return c.recvTimeout(120 * time.Second)
|
2020-06-01 23:19:41 +01:00
|
|
|
}
|
|
|
|
|
2020-06-15 18:26:50 +01:00
|
|
|
func (c *Client) recvTimeout(timeout time.Duration) (m ReceivedMessage, err error) {
|
2022-08-04 18:43:49 +01:00
|
|
|
readErr := c.readErr.Load()
|
2021-12-28 19:26:19 +00:00
|
|
|
if readErr != nil {
|
|
|
|
return nil, readErr
|
2020-02-20 17:11:43 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
defer func() {
|
|
|
|
if err != nil {
|
2020-03-12 15:05:03 +00:00
|
|
|
err = fmt.Errorf("derp.Recv: %w", err)
|
2021-12-28 19:26:19 +00:00
|
|
|
c.readErr.Store(err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
for {
|
2020-06-01 23:19:41 +01:00
|
|
|
c.nc.SetReadDeadline(time.Now().Add(timeout))
|
2020-06-15 18:26:50 +01:00
|
|
|
|
|
|
|
// Discard any peeked bytes from a previous Recv call.
|
|
|
|
if c.peeked != 0 {
|
|
|
|
if n, err := c.br.Discard(c.peeked); err != nil || n != c.peeked {
|
|
|
|
// Documented to never fail, but might as well check.
|
2020-06-15 19:04:19 +01:00
|
|
|
return nil, fmt.Errorf("bufio.Reader.Discard(%d bytes): got %v, %v", c.peeked, n, err)
|
2020-06-15 18:26:50 +01:00
|
|
|
}
|
|
|
|
c.peeked = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
t, n, err := readFrameHeader(c.br)
|
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-06-15 18:26:50 +01:00
|
|
|
if n > 1<<20 {
|
|
|
|
return nil, fmt.Errorf("unexpectedly large frame of %d bytes returned", n)
|
|
|
|
}
|
|
|
|
|
|
|
|
var b []byte // frame payload (past the 5 byte header)
|
|
|
|
|
|
|
|
// If the frame fits in our bufio.Reader buffer, just use it.
|
|
|
|
// In practice it's 4KB (from derphttp.Client's bufio.NewReader(httpConn)) and
|
|
|
|
// in practive, WireGuard packets (and thus DERP frames) are under 1.5KB.
|
2020-08-18 00:14:07 +01:00
|
|
|
// So this is the common path.
|
2020-06-15 18:26:50 +01:00
|
|
|
if int(n) <= c.br.Size() {
|
|
|
|
b, err = c.br.Peek(int(n))
|
|
|
|
c.peeked = int(n)
|
|
|
|
} else {
|
|
|
|
// But if for some reason we read a large DERP message (which isn't necessarily
|
2022-05-04 20:10:17 +01:00
|
|
|
// a WireGuard packet), then just allocate memory for it.
|
2020-06-15 18:26:50 +01:00
|
|
|
// TODO(bradfitz): use a pool if large frames ever happen in practice.
|
|
|
|
b = make([]byte, n)
|
|
|
|
_, err = io.ReadFull(c.br, b)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2020-02-20 20:27:12 +00:00
|
|
|
switch t {
|
2020-02-05 22:16:58 +00:00
|
|
|
default:
|
2020-02-20 20:27:12 +00:00
|
|
|
continue
|
2020-08-18 00:14:07 +01:00
|
|
|
case frameServerInfo:
|
|
|
|
// Server sends this at start-up. Currently unused.
|
|
|
|
// Just has a JSON message saying "version: 2",
|
|
|
|
// but the protocol seems extensible enough as-is without
|
|
|
|
// needing to wait an RTT to discover the version at startup.
|
|
|
|
// We'd prefer to give the connection to the client (magicsock)
|
|
|
|
// to start writing as soon as possible.
|
2021-08-19 19:51:08 +01:00
|
|
|
si, err := c.parseServerInfo(b)
|
2020-08-18 00:14:07 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid server info frame: %v", err)
|
|
|
|
}
|
2021-08-19 19:51:08 +01:00
|
|
|
sm := ServerInfoMessage{
|
|
|
|
TokenBucketBytesPerSecond: si.TokenBucketBytesPerSecond,
|
|
|
|
TokenBucketBytesBurst: si.TokenBucketBytesBurst,
|
|
|
|
}
|
|
|
|
c.setSendRateLimiter(sm)
|
|
|
|
return sm, nil
|
2020-02-20 20:27:12 +00:00
|
|
|
case frameKeepAlive:
|
2021-03-09 20:53:02 +00:00
|
|
|
// A one-way keep-alive message that doesn't require an acknowledgement.
|
|
|
|
// This predated framePing/framePong.
|
2021-03-15 16:58:52 +00:00
|
|
|
return KeepAliveMessage{}, nil
|
2020-03-22 01:24:28 +00:00
|
|
|
case framePeerGone:
|
|
|
|
if n < keyLen {
|
|
|
|
c.logf("[unexpected] dropping short peerGone frame from DERP server")
|
|
|
|
continue
|
|
|
|
}
|
2023-03-25 02:11:48 +00:00
|
|
|
// Backward compatibility for the older peerGone without reason byte
|
|
|
|
reason := PeerGoneReasonDisconnected
|
|
|
|
if n > keyLen {
|
|
|
|
reason = PeerGoneReasonType(b[keyLen])
|
|
|
|
}
|
|
|
|
pg := PeerGoneMessage{
|
|
|
|
Peer: key.NodePublicFromRaw32(mem.B(b[:keyLen])),
|
|
|
|
Reason: reason,
|
|
|
|
}
|
2020-03-22 01:24:28 +00:00
|
|
|
return pg, nil
|
|
|
|
|
2020-06-01 23:19:41 +01:00
|
|
|
case framePeerPresent:
|
2024-06-22 17:17:51 +01:00
|
|
|
remain := b
|
|
|
|
chunk, remain, ok := cutLeadingN(remain, keyLen)
|
|
|
|
if !ok {
|
2020-06-01 23:19:41 +01:00
|
|
|
c.logf("[unexpected] dropping short peerPresent frame from DERP server")
|
|
|
|
continue
|
|
|
|
}
|
2023-08-16 03:35:24 +01:00
|
|
|
var msg PeerPresentMessage
|
2024-06-22 17:17:51 +01:00
|
|
|
msg.Key = key.NodePublicFromRaw32(mem.B(chunk))
|
|
|
|
|
|
|
|
const ipLen = 16
|
|
|
|
const portLen = 2
|
|
|
|
chunk, remain, ok = cutLeadingN(remain, ipLen+portLen)
|
|
|
|
if !ok {
|
|
|
|
// Older server which didn't send the IP.
|
|
|
|
return msg, nil
|
|
|
|
}
|
|
|
|
msg.IPPort = netip.AddrPortFrom(
|
|
|
|
netip.AddrFrom16([16]byte(chunk[:ipLen])).Unmap(),
|
|
|
|
binary.BigEndian.Uint16(chunk[ipLen:]),
|
|
|
|
)
|
|
|
|
|
|
|
|
chunk, _, ok = cutLeadingN(remain, 1)
|
|
|
|
if !ok {
|
|
|
|
// Older server which doesn't send PeerPresentFlags.
|
|
|
|
return msg, nil
|
2023-08-16 03:35:24 +01:00
|
|
|
}
|
2024-06-22 17:17:51 +01:00
|
|
|
msg.Flags = PeerPresentFlags(chunk[0])
|
2023-08-16 03:35:24 +01:00
|
|
|
return msg, nil
|
2020-06-01 23:19:41 +01:00
|
|
|
|
2020-02-20 20:27:12 +00:00
|
|
|
case frameRecvPacket:
|
2020-03-04 17:35:32 +00:00
|
|
|
var rp ReceivedPacket
|
2020-08-18 00:14:07 +01:00
|
|
|
if n < keyLen {
|
|
|
|
c.logf("[unexpected] dropping short packet from DERP server")
|
|
|
|
continue
|
2020-03-04 17:35:32 +00:00
|
|
|
}
|
2021-10-28 23:42:50 +01:00
|
|
|
rp.Source = key.NodePublicFromRaw32(mem.B(b[:keyLen]))
|
2020-08-18 00:14:07 +01:00
|
|
|
rp.Data = b[keyLen:n]
|
2020-03-04 17:35:32 +00:00
|
|
|
return rp, nil
|
2021-03-09 20:53:02 +00:00
|
|
|
|
|
|
|
case framePing:
|
|
|
|
var pm PingMessage
|
|
|
|
if n < 8 {
|
|
|
|
c.logf("[unexpected] dropping short ping frame")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
copy(pm[:], b[:])
|
|
|
|
return pm, nil
|
2021-08-31 20:27:24 +01:00
|
|
|
|
2021-12-27 19:58:09 +00:00
|
|
|
case framePong:
|
|
|
|
var pm PongMessage
|
|
|
|
if n < 8 {
|
|
|
|
c.logf("[unexpected] dropping short ping frame")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
copy(pm[:], b[:])
|
|
|
|
return pm, nil
|
|
|
|
|
2021-08-31 20:27:24 +01:00
|
|
|
case frameHealth:
|
|
|
|
return HealthMessage{Problem: string(b[:])}, nil
|
|
|
|
|
|
|
|
case frameRestarting:
|
|
|
|
var m ServerRestartingMessage
|
|
|
|
if n < 8 {
|
|
|
|
c.logf("[unexpected] dropping short server restarting frame")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
m.ReconnectIn = time.Duration(binary.BigEndian.Uint32(b[0:4])) * time.Millisecond
|
|
|
|
m.TryFor = time.Duration(binary.BigEndian.Uint32(b[4:8])) * time.Millisecond
|
|
|
|
return m, nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-08-19 19:51:08 +01:00
|
|
|
|
|
|
|
func (c *Client) setSendRateLimiter(sm ServerInfoMessage) {
|
|
|
|
c.wmu.Lock()
|
|
|
|
defer c.wmu.Unlock()
|
|
|
|
|
|
|
|
if sm.TokenBucketBytesPerSecond == 0 {
|
|
|
|
c.rate = nil
|
|
|
|
} else {
|
|
|
|
c.rate = rate.NewLimiter(
|
|
|
|
rate.Limit(sm.TokenBucketBytesPerSecond),
|
|
|
|
sm.TokenBucketBytesBurst)
|
|
|
|
}
|
|
|
|
}
|
2021-12-28 19:26:19 +00:00
|
|
|
|
|
|
|
// LocalAddr returns the TCP connection's local address.
|
|
|
|
//
|
|
|
|
// If the client is broken in some previously detectable way, it
|
|
|
|
// returns an error.
|
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 05:14:09 +01:00
|
|
|
func (c *Client) LocalAddr() (netip.AddrPort, error) {
|
2021-12-28 19:26:19 +00:00
|
|
|
readErr, _ := c.readErr.Load().(error)
|
|
|
|
if readErr != 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 05:14:09 +01:00
|
|
|
return netip.AddrPort{}, readErr
|
2021-12-28 19:26:19 +00:00
|
|
|
}
|
|
|
|
if c.nc == 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 05:14:09 +01:00
|
|
|
return netip.AddrPort{}, errors.New("nil conn")
|
2021-12-28 19:26:19 +00:00
|
|
|
}
|
|
|
|
a := c.nc.LocalAddr()
|
|
|
|
if a == 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 05:14:09 +01:00
|
|
|
return netip.AddrPort{}, errors.New("nil addr")
|
2021-12-28 19:26:19 +00:00
|
|
|
}
|
2022-07-26 04:55:44 +01:00
|
|
|
return netip.ParseAddrPort(a.String())
|
2021-12-28 19:26:19 +00:00
|
|
|
}
|
2024-06-22 17:17:51 +01:00
|
|
|
|
|
|
|
func cutLeadingN(b []byte, n int) (chunk, remain []byte, ok bool) {
|
|
|
|
if len(b) >= n {
|
|
|
|
return b[:n], b[n:], true
|
|
|
|
}
|
|
|
|
return nil, b, false
|
|
|
|
}
|