Files
syncthing/internal/dht/dht.go
T
Jakob Borg 7132c8fcdd wip
Signed-off-by: Jakob Borg <[email protected]>
2026-11-29 11:13:00 +01:00

420 lines
12 KiB
Go

// Copyright (C) 2026 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
package dht
import (
"context"
stdcrypto "crypto"
"errors"
"fmt"
"log/slog"
"net"
"net/netip"
"slices"
"time"
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
"github.com/libp2p/go-libp2p"
kad "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-kad-dht/amino"
record "github.com/libp2p/go-libp2p-record"
p2pcrypto "github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
libp2pprotocol "github.com/libp2p/go-libp2p/core/protocol"
"github.com/libp2p/go-libp2p/core/routing"
rcmgr "github.com/libp2p/go-libp2p/p2p/host/resource-manager"
"github.com/libp2p/go-libp2p/p2p/net/connmgr"
"github.com/libp2p/go-libp2p/p2p/net/swarm"
quic "github.com/libp2p/go-libp2p/p2p/transport/quic"
"github.com/libp2p/go-libp2p/p2p/transport/quicreuse"
ma "github.com/multiformats/go-multiaddr"
quicgo "github.com/quic-go/quic-go"
"github.com/syncthing/syncthing/internal/db"
"github.com/syncthing/syncthing/internal/gen/discoproto"
"github.com/syncthing/syncthing/lib/connections/registry"
"github.com/syncthing/syncthing/lib/protocol"
"github.com/syncthing/syncthing/lib/rand"
)
const (
p2pProtocolPrefix libp2pprotocol.ID = "/syncthing"
p2pProtocolID = p2pProtocolPrefix + "/kad/1.0.0"
)
var (
errNotFound = errors.New("discovery record not found")
errNoPeers = errors.New("no peers")
)
// Lookup is a utility function for creating a single-use DHT instance and
// performing a lookup, without starting the full discovery machinery.
func Lookup(ctx context.Context, deviceID protocol.DeviceID, bootstrapPeers []string) ([]string, error) {
dht, err := NewSyncthingDHT(Options{BootstrapPeers: bootstrapPeers})
if err != nil {
return nil, err
}
defer dht.Close()
for !dht.Connected() {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(100 * time.Millisecond):
}
}
return dht.Lookup(ctx, deviceID)
}
type Options struct {
// UDPReuseManager for sharing an UDP socket with BEP QUIC connections
UDP *registry.UDPReuseManager
// Listen addresses for incoming QUIC connections; required for server
// mode
ListenAddresses []netip.AddrPort
// Set of bootstrap peers for initial connection, in libp2p "multiaddr"
// string format
BootstrapPeers []string
// Set of listen addresses to announce to peers, in libp2p "multiaddr"
// string format (without /p2p/ ID)
AdvertiseAddresses []string
// Private Ed25519 key to use as libp2p identity
Identity []byte
// Set to force server mode, assuming global reachability
ForceServer bool
// Set to enforce client mode, the opposite of ForceServer
ClientOnly bool
// Data store for peer discovery records (server mode); use nil to not
// persist records
ValueDatastore *db.Typed
// Data store for routing table; use nil to not persist routing table
RoutingDatastore *db.Typed
// Max number of allowed peer connections total, zero for default
MaxConnections int
// Max number of allowed peer connections per subnet, zero for default
MaxConnectionsPerSubnet int
}
type DHT struct {
host host.Host
ipfs *kad.IpfsDHT
}
func NewSyncthingDHT(options Options) (*DHT, error) {
if options.MaxConnectionsPerSubnet < 0 || options.MaxConnectionsPerSubnet > int(^uint(0)>>1)/8 {
return nil, errors.New("invalid per-subnet connection limit")
}
if options.ForceServer && len(options.ListenAddresses) == 0 {
return nil, errors.New("DHT server requires a QUIC listener")
}
if options.ForceServer && options.ClientOnly {
return nil, errors.New("client only or forced server, pick one")
}
if options.UDP == nil {
options.UDP = registry.NewUDPReuseManager()
}
peers := make([]peer.AddrInfo, 0, len(options.BootstrapPeers))
peerIndices := make(map[peer.ID]int)
for _, address := range options.BootstrapPeers {
info, err := peer.AddrInfoFromString(address)
if err != nil {
return nil, fmt.Errorf("invalid DHT bootstrap peer: %w", err)
}
if index, ok := peerIndices[info.ID]; ok {
peers[index].Addrs = append(peers[index].Addrs, info.Addrs...)
} else {
peerIndices[info.ID] = len(peers)
peers = append(peers, *info)
}
}
hostOptions := []libp2p.Option{
libp2p.DisableRelay(),
libp2p.EnableNATService(),
libp2p.Transport(quic.NewTransport),
libp2p.QUICReuse(options.UDP.QUICReuse),
libp2p.SwarmOpts(swarm.WithUDPBlackHoleSuccessCounter(nil)),
}
var listen []ma.Multiaddr
for _, address := range options.ListenAddresses {
addr, err := quicreuse.ToQuicMultiaddr(net.UDPAddrFromAddrPort(address), quicgo.Version1)
if err != nil {
return nil, err
}
listen = append(listen, addr)
}
if len(listen) == 0 {
hostOptions = append(hostOptions, libp2p.NoListenAddrs)
} else {
hostOptions = append(hostOptions, libp2p.ListenAddrs(listen...))
}
if options.ForceServer {
hostOptions = append(hostOptions, libp2p.ForceReachabilityPublic())
}
if options.Identity != nil {
key, err := p2pcrypto.UnmarshalPrivateKey(options.Identity)
if err != nil {
return nil, err
}
hostOptions = append(hostOptions, libp2p.Identity(key))
}
if len(options.AdvertiseAddresses) == 0 {
// For each listen address, try to look up external addresses (port
// mappings, STUN, ...) and add those to the set of advertised
// listen addresses.
hostOptions = append(hostOptions, libp2p.AddrsFactory(func(addresses []ma.Multiaddr) []ma.Multiaddr {
addresses = slices.Clone(addresses)
for _, address := range options.UDP.ExternalAddresses(options.ListenAddresses...) {
if mapped, err := quicreuse.ToQuicMultiaddr(net.UDPAddrFromAddrPort(address), quicgo.Version1); err == nil {
addresses = append(addresses, mapped)
}
}
return ma.Unique(addresses)
}))
} else {
// Use the defined set of advertised addresses
var advertised []ma.Multiaddr
for _, address := range options.AdvertiseAddresses {
a, err := ma.NewMultiaddr(address)
if err != nil {
return nil, err
}
advertised = append(advertised, a)
}
hostOptions = append(hostOptions, libp2p.AddrsFactory(func([]ma.Multiaddr) []ma.Multiaddr {
return slices.Clone(advertised)
}))
}
var connections *connmgr.BasicConnMgr
var resources network.ResourceManager
if limit := options.MaxConnections; limit > 0 {
var err error
// Prune at 90% down to 80%, leaving headroom below the hard limit.
connections, err = connmgr.NewConnManager(limit-limit/5, limit-limit/10)
if err != nil {
return nil, err
}
hostOptions = append(hostOptions, libp2p.ConnectionManager(connections))
}
if options.MaxConnections > 0 || options.MaxConnectionsPerSubnet > 0 {
defaults := rcmgr.DefaultLimits
libp2p.SetDefaultServiceLimits(&defaults)
limits := defaults.AutoScale()
if limit := options.MaxConnections; limit > 0 {
limits = rcmgr.PartialLimitConfig{
System: rcmgr.ResourceLimits{
Conns: rcmgr.LimitVal(limit),
ConnsInbound: rcmgr.LimitVal(limit),
ConnsOutbound: rcmgr.LimitVal(limit),
},
}.Build(limits)
}
var resourceOptions []rcmgr.Option
if limit := options.MaxConnectionsPerSubnet; limit > 0 {
// Keep libp2p's prefix sizes and the wider IPv6 prefix's 8:1 ratio.
// This resource manager is also used for AutoNAT dial-back connections.
resourceOptions = append(resourceOptions, rcmgr.WithLimitPerSubnet(
[]rcmgr.ConnLimitPerSubnet{{PrefixLength: 32, ConnCount: limit}},
[]rcmgr.ConnLimitPerSubnet{{PrefixLength: 56, ConnCount: limit}, {PrefixLength: 48, ConnCount: 8 * limit}},
))
}
var err error
resources, err = rcmgr.NewResourceManager(rcmgr.NewFixedLimiter(limits), resourceOptions...)
if err != nil {
if connections != nil {
connections.Close()
}
return nil, err
}
hostOptions = append(hostOptions, libp2p.ResourceManager(resources))
}
h, err := libp2p.New(hostOptions...)
if err != nil {
if connections != nil {
connections.Close()
}
if resources != nil {
resources.Close()
}
return nil, err
}
mode := kad.ModeAuto
if options.ForceServer {
mode = kad.ModeServer
} else if options.ClientOnly {
mode = kad.ModeClient
}
opts := []kad.Option{
kad.BootstrapPeers(peers...),
kad.DisableProviders(), // we do not use IPFS provider records
kad.MaxRecordAge(MaxRecordLifetime), // max time we keep a discovery record
kad.ValueGCInterval(MaxRecordLifetime), // how often to run GC
kad.Mode(mode), // client/server/auto
kad.ProtocolPrefix(p2pProtocolPrefix), // "/syncthing/kad/1.0.0"
// validate discovery records
kad.Validator(record.NamespacedValidator{dhtRecordNamespace: dhtRecordValidator{}}),
// diversity filter helps prevent some attacks
kad.RoutingTablePeerDiversityFilter(kad.NewRTPeerDiversityFilter(h, amino.DefaultMaxPeersPerIPGroupPerCpl, amino.DefaultMaxPeersPerIPGroup)),
kad.OnRequestHook(countIncomingRecordRequest), // logging
}
if options.ValueDatastore != nil {
opts = append(opts, kad.ValueDatastore(newDatastore(options.ValueDatastore)))
} else {
opts = append(opts, kad.ValueDatastore(dssync.MutexWrap(ds.NewMapDatastore())))
}
if options.RoutingDatastore != nil {
opts = append(
opts, kad.Datastore(newDatastore(options.RoutingDatastore)),
kad.BootstrapOrder(kad.PersistedFirst), // try known non-bootstrap peers first when starting up
kad.RoutingTablePersistence(5*time.Minute), // how often to store peers to db
)
} else {
opts = append(opts, kad.Datastore(dssync.MutexWrap(ds.NewMapDatastore())))
}
d, err := kad.New(h, opts...)
if err != nil {
h.Close()
return nil, err
}
return &DHT{
host: h,
ipfs: d,
}, nil
}
func (s *DHT) ID() string {
return s.host.ID().String()
}
func (s *DHT) Connected() bool {
return s.ipfs.RoutingTable().Size() > 0
}
func (s *DHT) Mode() string {
// The query handler is registered only in server mode.
if slices.Contains(s.host.Mux().Protocols(), p2pProtocolID) {
return "server"
}
return "client"
}
func (s *DHT) Peers() int {
return s.ipfs.RoutingTable().Size()
}
func (s *DHT) Addrs() []string {
addrs := s.ipfs.FilteredAddrs()
straddrs := make([]string, len(addrs))
for i, a := range addrs {
straddrs[i] = a.String()
}
return straddrs
}
func (s *DHT) Close() error {
return errors.Join(s.ipfs.Close(), s.host.Close())
}
func (s *DHT) Lookup(ctx context.Context, deviceID protocol.DeviceID) (addresses []string, err error) {
now := time.Now()
var errs []error
for _, timeValue := range discoveryTimeValues(deviceID, now) {
key := dhtRecordKey(deviceID, timeValue)
slog.Debug("Look up record", "device", deviceID, "key", key)
value, err := s.ipfs.GetValue(ctx, key)
if errors.Is(err, routing.ErrNotFound) {
continue
}
if err != nil && !(errors.Is(err, context.DeadlineExceeded) && len(value) > 0) {
errs = append(errs, err)
if ctx.Err() != nil {
break
}
continue
}
r, err := validateRecord(key, value, now)
if err != nil {
errs = append(errs, err)
continue
}
slog.DebugContext(ctx, "Got DHT result", "device", deviceID, "key", key, "expires", r.ExpiresUnix)
return r.Addresses, nil
}
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return nil, errNotFound
}
func (s *DHT) Announce(ctx context.Context, deviceID protocol.DeviceID, addresses []string, certificate []byte, privateKey stdcrypto.Signer) error {
if s.ipfs.RoutingTable().Size() == 0 {
return errNoPeers
}
now := time.Now()
timeValue := discoveryTimeValue(deviceID, now)
r := &discoproto.DHTPayload{
Certificate: certificate,
Addresses: addresses,
ExpiresUnix: uint64(now.Add(MaxRecordLifetime).Unix()), //nolint:gosec // does not wrap
TimeValue: timeValue,
}
value, err := encodeRecord(r, privateKey)
if err != nil {
return err
}
key := dhtRecordKey(deviceID, timeValue)
if err := s.ipfs.PutValue(ctx, key, value); err != nil {
return err
}
slog.Debug("Announced record", "key", key)
return nil
}
// NewIdentity returns the bytes for a new Ed25519 key usable as
// Options.Identity
func NewIdentity() ([]byte, error) {
priv, _, err := p2pcrypto.GenerateEd25519Key(rand.Reader)
if err != nil {
return nil, err
}
return p2pcrypto.MarshalPrivateKey(priv)
}