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 derp
|
|
|
|
|
|
|
|
// TODO(crawshaw): send srcKey with packets to clients?
|
|
|
|
// TODO(crawshaw): with predefined serverKey in clients and HMAC on packets we could skip TLS
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"context"
|
2020-02-17 21:52:11 +00:00
|
|
|
crand "crypto/rand"
|
2020-02-05 22:16:58 +00:00
|
|
|
"encoding/json"
|
2020-02-20 20:27:12 +00:00
|
|
|
"errors"
|
2020-02-21 17:35:53 +00:00
|
|
|
"expvar"
|
2020-02-05 22:16:58 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2020-03-05 23:00:56 +00:00
|
|
|
"io/ioutil"
|
2020-02-05 22:16:58 +00:00
|
|
|
"math/big"
|
2020-02-28 21:33:47 +00:00
|
|
|
"os"
|
|
|
|
"strconv"
|
2020-02-05 22:16:58 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"golang.org/x/crypto/nacl/box"
|
2020-02-20 23:14:24 +00:00
|
|
|
"golang.org/x/time/rate"
|
2020-03-03 19:33:22 +00:00
|
|
|
"tailscale.com/metrics"
|
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
|
|
|
)
|
|
|
|
|
2020-02-28 21:33:47 +00:00
|
|
|
var debug, _ = strconv.ParseBool(os.Getenv("DERP_DEBUG_LOGS"))
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
// Server is a DERP server.
|
2020-02-05 22:16:58 +00:00
|
|
|
type Server struct {
|
2020-02-20 23:14:24 +00:00
|
|
|
// BytesPerSecond, if non-zero, specifies how many bytes per
|
|
|
|
// second to cap per-client reads at.
|
|
|
|
BytesPerSecond int
|
|
|
|
|
2020-03-12 15:13:07 +00:00
|
|
|
// WriteTimeout, if non-zero, specifies how long to wait
|
|
|
|
// before failing when writing to a client.
|
|
|
|
WriteTimeout time.Duration
|
|
|
|
|
2020-02-17 21:52:11 +00:00
|
|
|
privateKey key.Private
|
|
|
|
publicKey key.Public
|
2020-02-11 17:37:20 +00:00
|
|
|
logf logger.Logf
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-02-21 17:35:53 +00:00
|
|
|
// Counters:
|
2020-03-03 19:33:22 +00:00
|
|
|
packetsSent, bytesSent expvar.Int
|
|
|
|
packetsRecv, bytesRecv expvar.Int
|
|
|
|
packetsDropped expvar.Int
|
|
|
|
accepts expvar.Int
|
2020-03-05 23:00:56 +00:00
|
|
|
curClients expvar.Int
|
|
|
|
curHomeClients expvar.Int // ones with preferred
|
2020-03-11 18:53:13 +00:00
|
|
|
clientsReplaced expvar.Int
|
2020-03-05 23:00:56 +00:00
|
|
|
unknownFrames expvar.Int
|
2020-03-09 17:25:04 +00:00
|
|
|
homeMovesIn expvar.Int // established clients announce home server moves in
|
|
|
|
homeMovesOut expvar.Int // established clients announce home server moves out
|
2020-02-21 17:35:53 +00:00
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
closed bool
|
2020-03-12 15:05:03 +00:00
|
|
|
netConns map[Conn]chan struct{} // chan is closed when conn closes
|
2020-02-21 17:35:53 +00:00
|
|
|
clients map[key.Public]*sclient
|
|
|
|
clientsEver map[key.Public]bool // never deleted from, for stats; fine for now
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-03-12 15:05:03 +00:00
|
|
|
// Conn is the subset of the underlying net.Conn the DERP Server needs.
|
|
|
|
// It is a defined type so that non-net connections can be used.
|
|
|
|
type Conn interface {
|
|
|
|
io.Closer
|
|
|
|
|
|
|
|
// The *Deadline methods follow the semantics of net.Conn.
|
|
|
|
|
|
|
|
SetDeadline(time.Time) error
|
|
|
|
SetReadDeadline(time.Time) error
|
|
|
|
SetWriteDeadline(time.Time) error
|
|
|
|
}
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
// NewServer returns a new DERP server. It doesn't listen on its own.
|
|
|
|
// Connections are given to it via Server.Accept.
|
2020-02-17 21:52:11 +00:00
|
|
|
func NewServer(privateKey key.Private, logf logger.Logf) *Server {
|
2020-02-05 22:16:58 +00:00
|
|
|
s := &Server{
|
2020-02-21 17:35:53 +00:00
|
|
|
privateKey: privateKey,
|
|
|
|
publicKey: privateKey.Public(),
|
|
|
|
logf: logf,
|
|
|
|
clients: make(map[key.Public]*sclient),
|
|
|
|
clientsEver: make(map[key.Public]bool),
|
2020-03-12 15:05:03 +00:00
|
|
|
netConns: make(map[Conn]chan struct{}),
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
// Close closes the server and waits for the connections to disconnect.
|
2020-02-05 22:16:58 +00:00
|
|
|
func (s *Server) Close() error {
|
2020-02-20 22:27:28 +00:00
|
|
|
s.mu.Lock()
|
|
|
|
wasClosed := s.closed
|
|
|
|
s.closed = true
|
|
|
|
s.mu.Unlock()
|
|
|
|
if wasClosed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
var closedChs []chan struct{}
|
|
|
|
|
|
|
|
s.mu.Lock()
|
2020-02-20 16:50:25 +00:00
|
|
|
for nc, closed := range s.netConns {
|
|
|
|
nc.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
closedChs = append(closedChs, closed)
|
|
|
|
}
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
for _, closed := range closedChs {
|
|
|
|
<-closed
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-20 22:27:28 +00:00
|
|
|
func (s *Server) isClosed() bool {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
return s.closed
|
|
|
|
}
|
|
|
|
|
2020-02-28 21:18:10 +00:00
|
|
|
// Accept adds a new connection to the server and serves it.
|
|
|
|
//
|
2020-02-20 16:50:25 +00:00
|
|
|
// The provided bufio ReadWriter must be already connected to nc.
|
|
|
|
// Accept blocks until the Server is closed or the connection closes
|
|
|
|
// on its own.
|
2020-02-28 21:18:10 +00:00
|
|
|
//
|
|
|
|
// Accept closes nc.
|
2020-03-12 15:05:03 +00:00
|
|
|
func (s *Server) Accept(nc Conn, brw *bufio.ReadWriter, remoteAddr string) {
|
2020-02-05 22:16:58 +00:00
|
|
|
closed := make(chan struct{})
|
|
|
|
|
2020-03-03 19:33:22 +00:00
|
|
|
s.accepts.Add(1)
|
2020-02-05 22:16:58 +00:00
|
|
|
s.mu.Lock()
|
2020-02-20 16:50:25 +00:00
|
|
|
s.netConns[nc] = closed
|
2020-02-05 22:16:58 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
defer func() {
|
2020-02-20 16:50:25 +00:00
|
|
|
nc.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
close(closed)
|
|
|
|
|
|
|
|
s.mu.Lock()
|
2020-02-20 16:50:25 +00:00
|
|
|
delete(s.netConns, nc)
|
2020-02-05 22:16:58 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
}()
|
|
|
|
|
2020-03-12 15:05:03 +00:00
|
|
|
if err := s.accept(nc, brw, remoteAddr); err != nil && !s.isClosed() {
|
|
|
|
s.logf("derp: %s: %v", remoteAddr, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-20 17:56:19 +00:00
|
|
|
// registerClient notes that client c is now authenticated and ready for packets.
|
|
|
|
// If c's public key was already connected with a different connection, the prior one is closed.
|
|
|
|
func (s *Server) registerClient(c *sclient) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
old := s.clients[c.key]
|
|
|
|
if old == nil {
|
2020-03-05 23:00:56 +00:00
|
|
|
c.logf("adding connection")
|
2020-02-20 17:56:19 +00:00
|
|
|
} else {
|
2020-03-11 18:53:13 +00:00
|
|
|
s.clientsReplaced.Add(1)
|
2020-03-12 15:05:03 +00:00
|
|
|
c.logf("adding connection, replacing %s", old.remoteAddr)
|
|
|
|
go old.nc.Close()
|
2020-02-20 17:56:19 +00:00
|
|
|
}
|
|
|
|
s.clients[c.key] = c
|
2020-02-21 17:35:53 +00:00
|
|
|
s.clientsEver[c.key] = true
|
2020-03-05 23:00:56 +00:00
|
|
|
s.curClients.Add(1)
|
2020-02-20 17:56:19 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 20:27:12 +00:00
|
|
|
// unregisterClient removes a client from the server.
|
2020-02-20 17:56:19 +00:00
|
|
|
func (s *Server) unregisterClient(c *sclient) {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
cur := s.clients[c.key]
|
|
|
|
if cur == c {
|
2020-03-05 23:00:56 +00:00
|
|
|
c.logf("removing connection")
|
2020-02-20 17:56:19 +00:00
|
|
|
delete(s.clients, c.key)
|
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
|
|
|
|
s.curClients.Add(-1)
|
|
|
|
if c.preferred {
|
|
|
|
s.curHomeClients.Add(-1)
|
|
|
|
}
|
2020-02-20 17:56:19 +00:00
|
|
|
}
|
|
|
|
|
2020-03-12 15:05:03 +00:00
|
|
|
func (s *Server) accept(nc Conn, brw *bufio.ReadWriter, remoteAddr string) error {
|
2020-02-20 16:50:25 +00:00
|
|
|
br, bw := brw.Reader, brw.Writer
|
|
|
|
nc.SetDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
if err := s.sendServerKey(bw); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return fmt.Errorf("send server key: %v", err)
|
|
|
|
}
|
2020-02-20 16:50:25 +00:00
|
|
|
nc.SetDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
clientKey, clientInfo, err := s.recvClientKey(br)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("receive client key: %v", err)
|
|
|
|
}
|
|
|
|
if err := s.verifyClient(clientKey, clientInfo); err != nil {
|
|
|
|
return fmt.Errorf("client %x rejected: %v", clientKey, err)
|
|
|
|
}
|
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
lim := rate.Inf
|
|
|
|
if s.BytesPerSecond != 0 {
|
|
|
|
lim = rate.Limit(s.BytesPerSecond)
|
|
|
|
}
|
|
|
|
const burstBytes = 1 << 20 // generous bandwidth delay product? must be over 64k max packet size.
|
|
|
|
limiter := rate.NewLimiter(lim, burstBytes)
|
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
// At this point we trust the client so we don't time out.
|
2020-02-20 16:50:25 +00:00
|
|
|
nc.SetDeadline(time.Time{})
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
c := &sclient{
|
2020-03-09 17:25:04 +00:00
|
|
|
s: s,
|
|
|
|
key: clientKey,
|
|
|
|
nc: nc,
|
|
|
|
br: br,
|
|
|
|
bw: bw,
|
|
|
|
limiter: limiter,
|
2020-03-12 15:05:03 +00:00
|
|
|
logf: logger.WithPrefix(s.logf, fmt.Sprintf("derp client %v/%x: ", remoteAddr, clientKey)),
|
|
|
|
remoteAddr: remoteAddr,
|
2020-03-09 17:25:04 +00:00
|
|
|
connectedAt: time.Now(),
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
if clientInfo != nil {
|
|
|
|
c.info = *clientInfo
|
|
|
|
}
|
|
|
|
|
2020-02-20 22:27:28 +00:00
|
|
|
// Once the client is registered, it can start receiving
|
|
|
|
// traffic, but we want to make sure the first thing it
|
|
|
|
// receives after its frameClientInfo is our frameServerInfo,
|
|
|
|
// so acquire the c.mu lock (which guards writing to c.bw)
|
|
|
|
// while we register.
|
|
|
|
c.mu.Lock()
|
2020-02-20 17:56:19 +00:00
|
|
|
s.registerClient(c)
|
2020-02-20 22:27:28 +00:00
|
|
|
err = s.sendServerInfo(bw, clientKey)
|
|
|
|
c.mu.Unlock()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("send server info: %v", err)
|
|
|
|
}
|
2020-02-20 17:56:19 +00:00
|
|
|
defer s.unregisterClient(c)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
return c.run()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sclient) run() error {
|
|
|
|
s := c.s
|
2020-02-20 17:56:19 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
2020-02-20 17:34:01 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
go s.sendClientKeepAlives(ctx, c)
|
2020-02-20 23:14:24 +00:00
|
|
|
|
2020-02-05 22:16:58 +00:00
|
|
|
for {
|
2020-02-20 20:27:12 +00:00
|
|
|
ft, fl, err := readFrameHeader(c.br)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2020-02-20 20:27:12 +00:00
|
|
|
return fmt.Errorf("client %x: readFrameHeader: %v", c.key, err)
|
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
switch ft {
|
|
|
|
case frameNotePreferred:
|
|
|
|
err = c.handleFrameNotePreferred(ft, fl)
|
|
|
|
case frameSendPacket:
|
|
|
|
err = c.handleFrameSendPacket(ctx, ft, fl)
|
|
|
|
default:
|
|
|
|
err = c.handleUnknownFrame(ctx, ft, fl)
|
2020-02-20 20:27:12 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
2020-03-05 23:00:56 +00:00
|
|
|
return err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
}
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
func (c *sclient) handleUnknownFrame(ctx context.Context, ft frameType, fl uint32) error {
|
|
|
|
if err := c.limiter.WaitN(ctx, int(fl)); err != nil {
|
|
|
|
return fmt.Errorf("rate limit: %v", err)
|
|
|
|
}
|
|
|
|
_, err := io.CopyN(ioutil.Discard, c.br, int64(fl))
|
|
|
|
return err
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
func (c *sclient) handleFrameNotePreferred(ft frameType, fl uint32) error {
|
|
|
|
if fl != 1 {
|
|
|
|
return fmt.Errorf("frameNotePreferred wrong size")
|
|
|
|
}
|
|
|
|
v, err := c.br.ReadByte()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("frameNotePreferred ReadByte: %v", err)
|
|
|
|
}
|
|
|
|
c.setPreferred(v != 0)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sclient) handleFrameSendPacket(ctx context.Context, ft frameType, fl uint32) error {
|
|
|
|
s := c.s
|
|
|
|
|
|
|
|
dstKey, contents, err := s.recvPacket(ctx, c.br, fl, c.limiter)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("client %x: recvPacket: %v", c.key, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
dst := s.clients[dstKey]
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
if dst == nil {
|
|
|
|
s.packetsDropped.Add(1)
|
|
|
|
if debug {
|
|
|
|
c.logf("dropping packet for unknown %x", dstKey)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
return nil
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
dst.mu.Lock()
|
2020-03-12 15:13:07 +00:00
|
|
|
if s.WriteTimeout != 0 {
|
|
|
|
dst.nc.SetWriteDeadline(time.Now().Add(s.WriteTimeout))
|
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
err = s.sendPacket(dst.bw, &dst.info, c.key, contents)
|
|
|
|
dst.mu.Unlock()
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
if err != nil {
|
|
|
|
c.logf("write error sending packet to %x: %v", dstKey, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
// If we cannot send to a destination, shut it down.
|
|
|
|
// Let its receive loop do the cleanup.
|
|
|
|
s.mu.Lock()
|
|
|
|
if s.clients[dstKey] == dst {
|
|
|
|
s.clients[dstKey].nc.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-05 23:00:56 +00:00
|
|
|
s.mu.Unlock()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-12 15:10:55 +00:00
|
|
|
|
|
|
|
// Do not treat a send error as an error with this transmitting client.
|
|
|
|
return nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 17:56:19 +00:00
|
|
|
func (s *Server) sendClientKeepAlives(ctx context.Context, c *sclient) {
|
|
|
|
if err := c.keepAliveLoop(ctx); err != nil {
|
2020-03-05 23:00:56 +00:00
|
|
|
c.logf("keep alive failed: %v", err)
|
2020-02-20 17:56:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-04 17:35:32 +00:00
|
|
|
func (s *Server) verifyClient(clientKey key.Public, info *clientInfo) error {
|
2020-02-05 22:16:58 +00:00
|
|
|
// TODO(crawshaw): implement policy constraints on who can use the DERP server
|
2020-02-20 23:14:24 +00:00
|
|
|
// TODO(bradfitz): ... and at what rate.
|
2020-02-05 22:16:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-02-18 18:08:51 +00:00
|
|
|
func (s *Server) sendServerKey(bw *bufio.Writer) error {
|
2020-02-20 20:27:12 +00:00
|
|
|
buf := make([]byte, 0, len(magic)+len(s.publicKey))
|
|
|
|
buf = append(buf, magic...)
|
|
|
|
buf = append(buf, s.publicKey[:]...)
|
|
|
|
return writeFrame(bw, frameServerKey, buf)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-03-04 17:35:32 +00:00
|
|
|
type serverInfo struct {
|
|
|
|
Version int // `json:"version,omitempty"`
|
|
|
|
}
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
func (s *Server) sendServerInfo(bw *bufio.Writer, clientKey key.Public) error {
|
2020-02-05 22:16:58 +00:00
|
|
|
var nonce [24]byte
|
2020-02-17 21:52:11 +00:00
|
|
|
if _, err := crand.Read(nonce[:]); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-03-04 17:35:32 +00:00
|
|
|
msg, err := json.Marshal(serverInfo{Version: protocolVersion})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-02-17 21:52:11 +00:00
|
|
|
msgbox := box.Seal(nil, msg, &nonce, clientKey.B32(), s.privateKey.B32())
|
2020-02-20 20:27:12 +00:00
|
|
|
if err := writeFrameHeader(bw, frameServerInfo, nonceLen+uint32(len(msgbox))); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 16:50:25 +00:00
|
|
|
if _, err := bw.Write(nonce[:]); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 16:50:25 +00:00
|
|
|
if _, err := bw.Write(msgbox); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-20 16:50:25 +00:00
|
|
|
return bw.Flush()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 20:27:12 +00:00
|
|
|
// recvClientKey reads the frameClientInfo frame from the client (its
|
|
|
|
// proof of identity) upon its initial connection. It should be
|
|
|
|
// considered especially untrusted at this point.
|
2020-03-04 17:35:32 +00:00
|
|
|
func (s *Server) recvClientKey(br *bufio.Reader) (clientKey key.Public, info *clientInfo, err error) {
|
2020-02-20 20:27:12 +00:00
|
|
|
fl, err := readFrameTypeHeader(br, frameClientInfo)
|
|
|
|
if err != nil {
|
|
|
|
return key.Public{}, nil, err
|
|
|
|
}
|
|
|
|
const minLen = keyLen + nonceLen
|
|
|
|
if fl < minLen {
|
|
|
|
return key.Public{}, nil, errors.New("short client info")
|
|
|
|
}
|
|
|
|
// We don't trust the client at all yet, so limit its input size to limit
|
|
|
|
// things like JSON resource exhausting (http://github.com/golang/go/issues/31789).
|
|
|
|
if fl > 256<<10 {
|
|
|
|
return key.Public{}, nil, errors.New("long client info")
|
|
|
|
}
|
2020-02-18 18:08:51 +00:00
|
|
|
if _, err := io.ReadFull(br, clientKey[:]); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
var nonce [24]byte
|
2020-02-18 18:08:51 +00:00
|
|
|
if _, err := io.ReadFull(br, nonce[:]); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, fmt.Errorf("nonce: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
msgLen := int(fl - minLen)
|
2020-02-05 22:16:58 +00:00
|
|
|
msgbox := make([]byte, msgLen)
|
2020-02-18 18:08:51 +00:00
|
|
|
if _, err := io.ReadFull(br, msgbox); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, fmt.Errorf("msgbox: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-17 21:52:11 +00:00
|
|
|
msg, ok := box.Open(nil, msgbox, &nonce, (*[32]byte)(&clientKey), s.privateKey.B32())
|
2020-02-05 22:16:58 +00:00
|
|
|
if !ok {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, fmt.Errorf("msgbox: cannot open len=%d with client key %x", msgLen, clientKey[:])
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-04 17:35:32 +00:00
|
|
|
info = new(clientInfo)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err := json.Unmarshal(msg, info); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, fmt.Errorf("msg: %v", err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
return clientKey, info, nil
|
|
|
|
}
|
|
|
|
|
2020-03-04 17:35:32 +00:00
|
|
|
func (s *Server) sendPacket(bw *bufio.Writer, dstInfo *clientInfo, srcKey key.Public, contents []byte) error {
|
2020-03-03 19:33:22 +00:00
|
|
|
s.packetsSent.Add(1)
|
|
|
|
s.bytesSent.Add(int64(len(contents)))
|
2020-03-04 17:35:32 +00:00
|
|
|
|
|
|
|
sendSrc := dstInfo.Version >= protocolSrcAddrs
|
|
|
|
|
|
|
|
pktLen := len(contents)
|
|
|
|
if sendSrc {
|
|
|
|
pktLen += len(srcKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := writeFrameHeader(bw, frameRecvPacket, uint32(pktLen)); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-03-04 17:35:32 +00:00
|
|
|
if sendSrc {
|
|
|
|
if _, err := bw.Write(srcKey[:]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2020-02-17 21:52:11 +00:00
|
|
|
if _, err := bw.Write(contents); err != nil {
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
2020-02-17 21:52:11 +00:00
|
|
|
return bw.Flush()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-20 23:14:24 +00:00
|
|
|
func (s *Server) recvPacket(ctx context.Context, br *bufio.Reader, frameLen uint32, limiter *rate.Limiter) (dstKey key.Public, contents []byte, err error) {
|
2020-02-20 20:27:12 +00:00
|
|
|
if frameLen < keyLen {
|
|
|
|
return key.Public{}, nil, errors.New("short send packet frame")
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-18 18:08:51 +00:00
|
|
|
if _, err := io.ReadFull(br, dstKey[:]); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
packetLen := frameLen - keyLen
|
2020-02-21 03:10:54 +00:00
|
|
|
if packetLen > MaxPacketSize {
|
|
|
|
return key.Public{}, nil, fmt.Errorf("data packet longer (%d) than max of %v", packetLen, MaxPacketSize)
|
2020-02-20 23:14:24 +00:00
|
|
|
}
|
|
|
|
if err := limiter.WaitN(ctx, int(packetLen)); err != nil {
|
|
|
|
return key.Public{}, nil, fmt.Errorf("rate limit: %v", err)
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
contents = make([]byte, packetLen)
|
2020-02-18 18:08:51 +00:00
|
|
|
if _, err := io.ReadFull(br, contents); err != nil {
|
2020-02-17 21:52:11 +00:00
|
|
|
return key.Public{}, nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2020-03-03 19:33:22 +00:00
|
|
|
s.packetsRecv.Add(1)
|
|
|
|
s.bytesRecv.Add(int64(len(contents)))
|
2020-02-05 22:16:58 +00:00
|
|
|
return dstKey, contents, nil
|
|
|
|
}
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
// sclient is a client connection to the server.
|
|
|
|
//
|
|
|
|
// (The "s" prefix is to more explicitly distinguish it from Client in derp_client.go)
|
|
|
|
type sclient struct {
|
2020-03-09 17:25:04 +00:00
|
|
|
s *Server
|
2020-03-12 15:05:03 +00:00
|
|
|
nc Conn
|
2020-03-09 17:25:04 +00:00
|
|
|
key key.Public
|
|
|
|
info clientInfo
|
|
|
|
logf logger.Logf
|
|
|
|
limiter *rate.Limiter
|
2020-03-12 15:05:03 +00:00
|
|
|
remoteAddr string // usually ip:port from net.Conn.RemoteAddr().String()
|
2020-03-09 17:25:04 +00:00
|
|
|
connectedAt time.Time
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
keepAliveTimer *time.Timer
|
|
|
|
keepAliveReset chan struct{}
|
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
preferred bool
|
|
|
|
|
2020-02-20 16:50:25 +00:00
|
|
|
mu sync.Mutex // mu guards writing to bw
|
|
|
|
br *bufio.Reader
|
|
|
|
bw *bufio.Writer
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-03-05 23:00:56 +00:00
|
|
|
func (c *sclient) setPreferred(v bool) {
|
|
|
|
if c.preferred == v {
|
|
|
|
return
|
|
|
|
}
|
2020-03-06 03:02:54 +00:00
|
|
|
c.preferred = v
|
2020-03-09 17:25:04 +00:00
|
|
|
var homeMove *expvar.Int
|
2020-03-05 23:00:56 +00:00
|
|
|
if v {
|
|
|
|
c.s.curHomeClients.Add(1)
|
2020-03-09 17:25:04 +00:00
|
|
|
homeMove = &c.s.homeMovesIn
|
2020-03-05 23:00:56 +00:00
|
|
|
} else {
|
|
|
|
c.s.curHomeClients.Add(-1)
|
2020-03-09 17:25:04 +00:00
|
|
|
homeMove = &c.s.homeMovesOut
|
|
|
|
}
|
|
|
|
|
|
|
|
// Keep track of varz for home serve moves in/out. But ignore
|
|
|
|
// the initial packet set when a client connects, which we
|
|
|
|
// assume happens within 5 seconds. In any case, just for
|
|
|
|
// graphs, so not important to miss a move. But it shouldn't:
|
|
|
|
// the netcheck/re-STUNs in magicsock only happen about every
|
|
|
|
// 30 seconds.
|
|
|
|
if time.Since(c.connectedAt) > 5*time.Second {
|
|
|
|
homeMove.Add(1)
|
2020-03-05 23:00:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-20 17:56:19 +00:00
|
|
|
func (c *sclient) keepAliveLoop(ctx context.Context) error {
|
2020-02-17 21:52:11 +00:00
|
|
|
jitterMs, err := crand.Int(crand.Reader, big.NewInt(5000))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
jitter := time.Duration(jitterMs.Int64()) * time.Millisecond
|
|
|
|
c.keepAliveTimer = time.NewTimer(keepAlive + jitter)
|
2020-02-20 17:56:19 +00:00
|
|
|
defer c.keepAliveTimer.Stop()
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
case <-c.keepAliveReset:
|
|
|
|
if c.keepAliveTimer.Stop() {
|
|
|
|
<-c.keepAliveTimer.C
|
|
|
|
}
|
|
|
|
c.keepAliveTimer.Reset(keepAlive + jitter)
|
|
|
|
case <-c.keepAliveTimer.C:
|
|
|
|
c.mu.Lock()
|
2020-03-12 15:13:07 +00:00
|
|
|
if c.s.WriteTimeout != 0 {
|
|
|
|
c.nc.SetWriteDeadline(time.Now().Add(c.s.WriteTimeout))
|
|
|
|
}
|
2020-02-20 20:27:12 +00:00
|
|
|
err := writeFrame(c.bw, frameKeepAlive, nil)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err == nil {
|
2020-02-20 16:50:25 +00:00
|
|
|
err = c.bw.Flush()
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
c.mu.Unlock()
|
|
|
|
|
|
|
|
if err != nil {
|
2020-02-20 16:50:25 +00:00
|
|
|
c.nc.Close()
|
2020-02-05 22:16:58 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-03 19:33:22 +00:00
|
|
|
func (s *Server) expVarFunc(f func() interface{}) expvar.Func {
|
|
|
|
return expvar.Func(func() interface{} {
|
|
|
|
s.mu.Lock()
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
return f()
|
|
|
|
})
|
2020-02-21 17:35:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ExpVar returns an expvar variable suitable for registering with expvar.Publish.
|
|
|
|
func (s *Server) ExpVar() expvar.Var {
|
2020-03-03 19:33:22 +00:00
|
|
|
m := new(metrics.Set)
|
|
|
|
m.Set("counter_unique_clients_ever", s.expVarFunc(func() interface{} { return len(s.clientsEver) }))
|
2020-03-05 23:00:56 +00:00
|
|
|
m.Set("gauge_current_connnections", &s.curClients)
|
|
|
|
m.Set("gauge_current_home_connnections", &s.curHomeClients)
|
2020-03-03 19:33:22 +00:00
|
|
|
m.Set("accepts", &s.accepts)
|
2020-03-11 18:53:13 +00:00
|
|
|
m.Set("clients_replaced", &s.clientsReplaced)
|
2020-03-03 19:33:22 +00:00
|
|
|
m.Set("bytes_received", &s.bytesRecv)
|
|
|
|
m.Set("bytes_sent", &s.bytesSent)
|
|
|
|
m.Set("packets_dropped", &s.packetsDropped)
|
|
|
|
m.Set("packets_sent", &s.packetsSent)
|
|
|
|
m.Set("packets_received", &s.packetsRecv)
|
2020-03-05 23:00:56 +00:00
|
|
|
m.Set("unknown_frames", &s.unknownFrames)
|
2020-03-09 17:25:04 +00:00
|
|
|
m.Set("home_moves_in", &s.homeMovesIn)
|
|
|
|
m.Set("home_moves_out", &s.homeMovesOut)
|
2020-03-03 19:33:22 +00:00
|
|
|
return m
|
2020-02-21 17:35:53 +00:00
|
|
|
}
|