WIP: pluggable transports

Signed-off-by: Adriano Sela Aviles <[email protected]>
This commit is contained in:
Adriano Sela Aviles authored and Adriano Sela Aviles committed 2026-10-21 00:01:33 -04:00
1 parent 47743a8b9a
commit ecd50ee2c1
14 files changed
+1330 -56

No files matched your search

+3
View File
@@ -195,6 +195,9 @@ func runStatus(ctx context.Context, args []string) error {
}
if relay != "" && ps.CurAddr == "" && ps.PeerRelay == "" {
f("relay %q", relay)
} else if ps.TransportName != "" {
// On a pluggable transport path; CurAddr is the real remote addr.
f("%s %s", ps.TransportName, ps.CurAddr)
} else if ps.CurAddr != "" {
f("direct %s", ps.CurAddr)
} else if ps.PeerRelay != "" {
+53
View File
@@ -20,6 +20,7 @@
package disco
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
@@ -51,6 +52,13 @@ const (
TypeCallMeMaybeVia = MessageType(0x07)
TypeAllocateUDPRelayEndpointRequest = MessageType(0x08)
TypeAllocateUDPRelayEndpointResponse = MessageType(0x09)
// TypeTransportSignal carries an opaque signaling message for a pluggable
// transport (see tailscale.com/wgengine/magicsock's RegisterTransport)
// between Tailscale peers via DERP, so a transport can negotiate without an
// external signaling server. The transport name and its opaque payload
// travel in the message body; see [TransportSignal]. disco does not
// interpret the payload.
TypeTransportSignal = MessageType(0x0A)
)
const v0 = byte(0)
@@ -103,6 +111,8 @@ func Parse(p []byte) (Message, error) {
return parseAllocateUDPRelayEndpointRequest(ver, p)
case TypeAllocateUDPRelayEndpointResponse:
return parseAllocateUDPRelayEndpointResponse(ver, p)
case TypeTransportSignal:
return parseTransportSignal(ver, p)
default:
return nil, fmt.Errorf("unknown message type 0x%02x", byte(t))
}
@@ -283,6 +293,47 @@ func parsePong(ver uint8, p []byte) (m *Pong, err error) {
return m, nil
}
// TransportSignal is sent only over DERP to deliver a pluggable transport's
// signaling message to a peer. Transport is the registered transport name that
// owns the message (used to dispatch it to the right transport on the receiving
// side); Payload is that transport's opaque signaling bytes, which disco does
// not interpret. A single disco message type carrying a transport-tagged
// payload keeps the disco protocol small and decouples it from any specific
// transport.
type TransportSignal struct {
Transport string
Payload []byte
}
func (m *TransportSignal) AppendMarshal(b []byte) []byte {
// Body is a 1-byte transport-name length, the transport name, then the raw
// payload. The name is bounded to 255 bytes, which is far more than any real
// transport name needs.
name := m.Transport
if len(name) > 255 {
name = name[:255]
}
ret, p := appendMsgHeader(b, TypeTransportSignal, v0, 1+len(name)+len(m.Payload))
p[0] = byte(len(name))
n := copy(p[1:], name)
copy(p[1+n:], m.Payload)
return ret
}
func parseTransportSignal(_ uint8, p []byte) (*TransportSignal, error) {
if len(p) < 1 {
return nil, errShort
}
nameLen := int(p[0])
if len(p) < 1+nameLen {
return nil, errShort
}
return &TransportSignal{
Transport: string(p[1 : 1+nameLen]),
Payload: bytes.Clone(p[1+nameLen:]),
}, nil
}
// MessageSummary returns a short summary of m for logging purposes.
func MessageSummary(m Message) string {
switch m := m.(type) {
@@ -304,6 +355,8 @@ func MessageSummary(m Message) string {
return "allocate-udp-relay-endpoint-request"
case *AllocateUDPRelayEndpointResponse:
return "allocate-udp-relay-endpoint-response"
case *TransportSignal:
return "transport-signal-" + m.Transport
default:
return fmt.Sprintf("%#v", m)
}
+1 -1
View File
@@ -173,4 +173,4 @@
});
};
}
# nix-direnv cache busting line: sha256-jrznfL26qyAGix9DVkmh0sLU2VvqeTNMdi6mPu9RlxM=
# nix-direnv cache busting line: sha256-n6gM53lsiy+0W/6hZsAZO5vHT0QhO2Xlw0n4Tg5xf3k=
+2 -2
View File
@@ -4,7 +4,7 @@
"sri": "sha256-sdlgTLTkdhTvGCeQTwAsR+Do8rNwBzBUp5QPc09BPgI="
},
"vendor": {
"goModSum": "sha256-DN+aQ2obBIjmj9TtvEA0+DYf+wIvpJ+MTg2+ZvYczkw=",
"sri": "sha256-jrznfL26qyAGix9DVkmh0sLU2VvqeTNMdi6mPu9RlxM="
"goModSum": "sha256-20ZG83WiS4q9EBkYwfhdh5P9p4C/VEutch0RxA/0Xws=",
"sri": "sha256-n6gM53lsiy+0W/6hZsAZO5vHT0QhO2Xlw0n4Tg5xf3k="
}
}
+8
View File
@@ -271,6 +271,11 @@ type PeerStatus struct {
Relay string // DERP region
PeerRelay string // peer relay address (ip:port:vni)
// TransportName, if non-empty, is the name of the pluggable transport
// (e.g. "webrtc") currently carrying traffic to this peer. When set, CurAddr
// holds the transport's real remote address rather than a direct UDP addr.
TransportName string `json:",omitempty"`
RxBytes int64
TxBytes int64
Created time.Time // time registered with tailcontrol
@@ -686,6 +691,9 @@ table tbody tr:nth-child(even) td { background-color: #f5f5f5; }
if ps.Active {
if ps.Relay != "" && ps.CurAddr == "" {
f("relay <b>%s</b>", html.EscapeString(ps.Relay))
} else if ps.TransportName != "" {
// On a pluggable transport path; CurAddr is the real remote addr.
f("%s <b>%s</b>", html.EscapeString(ps.TransportName), html.EscapeString(ps.CurAddr))
} else if ps.CurAddr != "" {
f("direct <b>%s</b>", html.EscapeString(ps.CurAddr))
}
+1 -1
View File
@@ -16,4 +16,4 @@
) {
src = ./.;
}).shellNix
# nix-direnv cache busting line: sha256-jrznfL26qyAGix9DVkmh0sLU2VvqeTNMdi6mPu9RlxM=
# nix-direnv cache busting line: sha256-n6gM53lsiy+0W/6hZsAZO5vHT0QhO2Xlw0n4Tg5xf3k=
+51
View File
@@ -3079,6 +3079,57 @@ const DerpMagicIP = "127.3.3.40"
var DerpMagicIPAddr = netip.MustParseAddr(DerpMagicIP)
// Pluggable-transport magic IPs are a reserved block of fake WireGuard
// endpoint IPs, one per registered pluggable transport (see
// tailscale.com/wgengine/magicsock's RegisterTransport). Like [DerpMagicIP],
// they are synthetic: they never appear on the wire, they only tag which local
// path a packet took inside magicsock. Index 0 maps to the base address.
//
// Mnemonic: 127.3.3.41 is one above DerpMagicIP (127.3.3.40); the block grows
// upward from there.
const (
// TransportMagicIPBase is the first address of the reserved block.
TransportMagicIPBase = "127.3.3.41"
// MaxPluggableTransports is the number of addresses reserved for pluggable
// transports, i.e. the maximum number that can be registered in one
// process (127.3.3.41 through 127.3.3.50).
MaxPluggableTransports = 10
)
var transportMagicIPBaseAddr = netip.MustParseAddr(TransportMagicIPBase)
// TransportMagicIP returns the synthetic magic IP for the pluggable transport
// at index i (0-based). It panics if i is negative or >= MaxPluggableTransports.
func TransportMagicIP(i int) netip.Addr {
if i < 0 || i >= MaxPluggableTransports {
panic("tailcfg: transport index out of range")
}
// The reserved block is contiguous within the final octet, so advancing by
// i addresses stays within 127.3.3.0/24.
a4 := transportMagicIPBaseAddr.As4()
a4[3] += byte(i)
return netip.AddrFrom4(a4)
}
// IsTransportMagicIP reports whether a is one of the reserved pluggable
// transport magic IPs, and if so returns its 0-based transport index.
func IsTransportMagicIP(a netip.Addr) (idx int, ok bool) {
if !a.Is4() {
return 0, false
}
base := transportMagicIPBaseAddr.As4()
got := a.As4()
// Must match on the first three octets (127.3.3) and the base of the block.
if got[0] != base[0] || got[1] != base[1] || got[2] != base[2] {
return 0, false
}
d := int(got[3]) - int(base[3])
if d < 0 || d >= MaxPluggableTransports {
return 0, false
}
return d, true
}
// EarlyNoise is the early payload that's sent over Noise but before the HTTP/2
// handshake when connecting to the coordination server.
//
+3
View File
@@ -66,6 +66,9 @@ var (
// suppressing/dropping inbound/outbound [disco.Ping] messages, forcing
// all peer communication over DERP or peer relay.
debugNeverDirectUDP = envknob.RegisterBool("TS_DEBUG_NEVER_DIRECT_UDP")
// debugDisablePluggableTransports disables all pluggable transports, so
// peers that would otherwise use one fall back to DERP.
debugDisablePluggableTransports = envknob.RegisterBool("TS_DEBUG_DISABLE_PLUGGABLE_TRANSPORTS")
// Hey you! Adding a new debugknob? Make sure to stub it out in the
// debugknobs_stubs.go file too.
)
+18 -17
View File
@@ -15,20 +15,21 @@ import (
//
// They're inlinable and the linker can deadcode that's guarded by them to make
// smaller binaries.
func debugBindSocket() bool { return false }
func debugDisco() bool { return false }
func debugOmitLocalAddresses() bool { return false }
func logDerpVerbose() bool { return false }
func debugReSTUNStopOnIdle() bool { return false }
func debugAlwaysDERP() bool { return false }
func debugUseDERPHTTP() bool { return false }
func debugEnableSilentDisco() bool { return false }
func debugSendCallMeUnknownPeer() bool { return false }
func debugPMTUD() bool { return false }
func debugUseDERPAddr() string { return "" }
func debugEnablePMTUD() opt.Bool { return "" }
func debugRingBufferMaxSizeBytes() int { return 0 }
func inTest() bool { return false }
func debugPeerMap() bool { return false }
func pretendpoints() []netip.AddrPort { return []netip.AddrPort{} }
func debugNeverDirectUDP() bool { return false }
func debugBindSocket() bool { return false }
func debugDisco() bool { return false }
func debugOmitLocalAddresses() bool { return false }
func logDerpVerbose() bool { return false }
func debugReSTUNStopOnIdle() bool { return false }
func debugAlwaysDERP() bool { return false }
func debugUseDERPHTTP() bool { return false }
func debugEnableSilentDisco() bool { return false }
func debugSendCallMeUnknownPeer() bool { return false }
func debugPMTUD() bool { return false }
func debugUseDERPAddr() string { return "" }
func debugEnablePMTUD() opt.Bool { return "" }
func debugRingBufferMaxSizeBytes() int { return 0 }
func inTest() bool { return false }
func debugPeerMap() bool { return false }
func pretendpoints() []netip.AddrPort { return []netip.AddrPort{} }
func debugNeverDirectUDP() bool { return false }
func debugDisablePluggableTransports() bool { return false }
+157 -21
View File
@@ -105,6 +105,15 @@ type endpoint struct {
expired bool // whether the node has expired
isWireguardOnly bool // whether the endpoint is WireGuard only. Must not be changed after initializing the endpont.
relayCapable bool // whether the node is capable of speaking via a [tailscale.com/net/udprelay.Server]
// transportChannelReady tracks, per pluggable transport index, whether that
// transport currently has an open channel to this peer (set by the transport
// via TransportHost.SetChannelReady on channel open/close). While an index is
// true, the heartbeat re-probes that transport's magic address so its path
// can be (re)selected even after a fallback to DERP or a relay path. Channel
// existence is event-driven; path selection remains pong-driven. The map is
// nil until the first transport reports readiness.
transportChannelReady map[int]bool
}
// udpRelayEndpointReady determines whether the given relay [addrQuality] should
@@ -754,6 +763,11 @@ func (de *endpoint) maybeProbeUDPLifetimeLocked() (afterInactivityFor time.Durat
if !de.bestAddr.ap.IsValid() {
return afterInactivityFor, false
}
if _, ok := tailcfg.IsTransportMagicIP(de.bestAddr.ap.Addr()); ok {
// A pluggable transport path is not a real UDP socket, so there are no
// stateful middleboxes whose UDP mapping lifetime we'd be probing.
return afterInactivityFor, false
}
epDisco := de.disco.Load()
if epDisco == nil {
// peer does not support disco
@@ -931,9 +945,17 @@ func (de *endpoint) heartbeat() {
udpAddr, _, _ := de.addrForSendLocked(now)
if udpAddr.ap.IsValid() {
// We have a preferred path. Ping that every 'heartbeatInterval'.
// This includes a transport magic address: like a peer-relay (VNI)
// path, a transport path is bestAddr-only (never in de.endpointState)
// but its liveness is driven by these disco pings over the transport,
// not by the transport's own connection-state callbacks.
// startDiscoPingLocked and handlePongConnLocked special-case the magic
// address the same way they special-case vni.IsSet().
de.startDiscoPingLocked(udpAddr, now, pingHeartbeat, 0, nil)
}
de.maybeProbeTransportsLocked(now)
if de.wantFullPingLocked(now) {
de.sendDiscoPingsLocked(now, true)
}
@@ -945,6 +967,50 @@ func (de *endpoint) heartbeat() {
de.heartBeatTimer = time.AfterFunc(heartbeatInterval, de.heartbeat)
}
// setTransportChannelReadyLocked records whether the pluggable transport at
// index idx currently has an open channel to this peer. de.mu must be held.
func (de *endpoint) setTransportChannelReadyLocked(idx int, ready bool) {
if ready {
if de.transportChannelReady == nil {
de.transportChannelReady = make(map[int]bool)
}
de.transportChannelReady[idx] = true
return
}
delete(de.transportChannelReady, idx)
}
// maybeProbeTransportsLocked sends a disco ping to each ready transport's magic
// address when that transport is not already our path, so that a pong can
// (re)promote it via betterAddr. It is the transport analogue of relay path
// re-discovery: without it, promotion would be one-shot (only on channel open)
// and a single late or dropped pong would wedge the peer on DERP for the rest
// of the session, since the heartbeat only pings the current bestAddr.
func (de *endpoint) maybeProbeTransportsLocked(now mono.Time) {
if len(de.transportChannelReady) == 0 {
return
}
onTrustedDirect := de.bestAddr.isDirect() && now.Before(de.trustBestAddrUntil)
bestIdx, bestIsTransport := tailcfg.IsTransportMagicIP(de.bestAddr.ap.Addr())
for idx, ready := range de.transportChannelReady {
if !ready {
continue
}
// If this transport is already our best path, the heartbeat ping to
// bestAddr keeps it alive; nothing extra to do.
if bestIsTransport && bestIdx == idx {
continue
}
// If we're on a trusted direct path, only keep probing transports that
// outrank direct; a below-direct transport could never win the
// promotion anyway (see betterAddr), so don't waste the probe on it.
if onTrustedDirect && !transportAboveDirect(tailcfg.TransportMagicIP(idx)) {
continue
}
de.startDiscoPingLocked(epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(idx), transportMagicPort)}, now, pingHeartbeat, 0, nil)
}
}
// setHeartbeatDisabled sets heartbeatDisabled to the provided value.
func (de *endpoint) setHeartbeatDisabled(v bool) {
de.mu.Lock()
@@ -1147,7 +1213,13 @@ func (de *endpoint) send(buffs [][]byte, offset int) error {
}
}
var err error
if hasUDPTransport && udpAddr.ap.IsValid() {
// Check if this is a pluggable transport address and route accordingly.
if tIdx, isTransport := tailcfg.IsTransportMagicIP(udpAddr.ap.Addr()); isTransport && udpAddr.ap.IsValid() {
// Pack all buffs into one message. See sendTransportBatch for why.
if err = de.c.sendTransportBatch(tIdx, de.publicKey, buffs, offset); err != nil {
return err
}
} else if hasUDPTransport && udpAddr.ap.IsValid() {
_, err = de.c.sendUDPBatch(udpAddr, buffs, offset)
// If the error is known to indicate that the endpoint is no longer
@@ -1187,6 +1259,12 @@ func (de *endpoint) send(buffs [][]byte, offset int) error {
}
}
if derpAddr.IsValid() {
// Traffic is flowing via DERP; opportunistically ask each pluggable
// transport to upgrade the path. Each transport decides for itself
// whether this peer is eligible.
for _, inst := range de.c.transports {
inst.t.EnsureConnecting(de)
}
allOk := true
var txBytes int
for _, buff := range buffs {
@@ -1359,7 +1437,12 @@ const (
// is interested in the result (such as a CLI "tailscale ping" or a c2n ping
// request, etc)
func (de *endpoint) startDiscoPingLocked(ep epAddr, now mono.Time, purpose discoPingPurpose, size int, resCB *pingResultAndCallback) {
if runtime.GOOS == "js" {
_, isTransport := tailcfg.IsTransportMagicIP(ep.ap.Addr())
if runtime.GOOS == "js" && !isTransport {
// A browser has no UDP socket, so it can't disco-ping a real endpoint.
// A pluggable transport (e.g. WebRTC) is a usable path though, so a ping
// to a transport magic address is valid on js: sendAddr routes it over
// the transport and never touches a UDP socket.
return
}
if debugNeverDirectUDP() && !ep.vni.IsSet() && ep.ap.Addr() != tailcfg.DerpMagicIPAddr {
@@ -1370,7 +1453,7 @@ func (de *endpoint) startDiscoPingLocked(ep epAddr, now mono.Time, purpose disco
return
}
if purpose != pingCLI &&
!ep.vni.IsSet() { // de.endpointState is only relevant for direct/non-vni epAddr's
!ep.vni.IsSet() && !isTransport { // de.endpointState is only relevant for direct/non-vni, non-transport epAddr's
st, ok := de.endpointState[ep.ap]
if !ok {
// Shouldn't happen. But don't ping an endpoint that's
@@ -1958,9 +2041,11 @@ func (de *endpoint) handlePongConnLocked(m *disco.Pong, di *discoInfo, src epAdd
de.c.reportExitNodePong(de.publicKey, now)
latency := now.Sub(sp.at)
if hasUDPTransport && !isDerp && !src.vni.IsSet() {
// Note: we check vni.isSet() as relay [epAddr]'s are not stored in
// endpointState, they are either de.bestAddr or not.
_, isTransport := tailcfg.IsTransportMagicIP(src.ap.Addr())
if hasUDPTransport && !isDerp && !src.vni.IsSet() && !isTransport {
// Note: we check vni.isSet() and the transport magic addresses as those
// [epAddr]'s are not stored in endpointState; they are either
// de.bestAddr or not. The promotion block below still runs for them.
st, ok := de.endpointState[sp.to.ap]
if !ok {
// This is no longer an endpoint we care about.
@@ -2034,10 +2119,14 @@ type epAddr struct {
vni packet.VirtualNetworkID // vni.IsSet() indicates if this [epAddr] involves a Geneve header
}
// isDirect returns true if e.ap is valid and not tailcfg.DerpMagicIPAddr,
// and a VNI is not set.
// isDirect returns true if e.ap is valid and not tailcfg.DerpMagicIPAddr or a
// pluggable transport magic IP, and a VNI is not set.
func (e epAddr) isDirect() bool {
return e.ap.IsValid() && e.ap.Addr() != tailcfg.DerpMagicIPAddr && !e.vni.IsSet()
if !e.ap.IsValid() || e.ap.Addr() == tailcfg.DerpMagicIPAddr || e.vni.IsSet() {
return false
}
_, isTransport := tailcfg.IsTransportMagicIP(e.ap.Addr())
return !isTransport
}
func (e epAddr) String() string {
@@ -2090,6 +2179,33 @@ func betterAddr(a, b addrQuality) bool {
return false
}
// Pluggable transport path priority. Whether an address is a transport path
// is structural (its magic IP is in the reserved block). A transport ranks
// either above or below a direct UDP path depending on whether it registered
// with [WithPriorityOverDirect] (default: below); either way it ranks above
// DERP and peer-relay. Between two transport paths, or two paths in the same
// tier, fall through to the normal latency comparison.
_, aIsTransport := tailcfg.IsTransportMagicIP(a.ap.Addr())
_, bIsTransport := tailcfg.IsTransportMagicIP(b.ap.Addr())
aIsDERP := a.ap.Addr() == tailcfg.DerpMagicIPAddr
bIsDERP := b.ap.Addr() == tailcfg.DerpMagicIPAddr
// Transport vs. direct UDP: the transport's priority decides.
if aIsTransport && b.isDirect() {
return transportAboveDirect(a.ap.Addr())
}
if bIsTransport && a.isDirect() {
return !transportAboveDirect(b.ap.Addr())
}
// Transport vs. DERP/relay: the transport always wins.
if aIsTransport && !bIsTransport && (bIsDERP || b.vni.IsSet()) {
return true
}
if bIsTransport && !aIsTransport && (aIsDERP || a.vni.IsSet()) {
return false
}
// Each address starts with a set of points (from 0 to 100) that
// represents how much faster they are than the highest-latency
// endpoint. For example, if a has latency 200ms and b has latency
@@ -2110,19 +2226,26 @@ func betterAddr(a, b addrQuality) bool {
// addresses, and prefer link-local unicast addresses over other types
// of private IP addresses since it's definitionally more likely that
// they'll be on the same network segment than a general private IP.
if a.ap.Addr().IsLoopback() {
aPoints += 50
} else if a.ap.Addr().IsLinkLocalUnicast() {
aPoints += 30
} else if a.ap.Addr().IsPrivate() {
aPoints += 20
//
// Exclude magic IPs (DERP, transports) from these bonuses as they're not
// real network paths.
if !aIsDERP && !aIsTransport {
if a.ap.Addr().IsLoopback() {
aPoints += 50
} else if a.ap.Addr().IsLinkLocalUnicast() {
aPoints += 30
} else if a.ap.Addr().IsPrivate() {
aPoints += 20
}
}
if b.ap.Addr().IsLoopback() {
bPoints += 50
} else if b.ap.Addr().IsLinkLocalUnicast() {
bPoints += 30
} else if b.ap.Addr().IsPrivate() {
bPoints += 20
if !bIsDERP && !bIsTransport {
if b.ap.Addr().IsLoopback() {
bPoints += 50
} else if b.ap.Addr().IsLinkLocalUnicast() {
bPoints += 30
} else if b.ap.Addr().IsPrivate() {
bPoints += 20
}
}
// Prefer IPv6 for being a bit more robust, as long as
@@ -2252,9 +2375,22 @@ func (de *endpoint) populatePeerStatus(ps *ipnstate.PeerStatus) {
if udpAddr, derpAddr, _ := de.addrForSendLocked(now); udpAddr.ap.IsValid() && !derpAddr.IsValid() {
if udpAddr.vni.IsSet() {
ps.PeerRelay = udpAddr.String()
} else if inst, ok := de.c.transportByMagicIP(udpAddr.ap.Addr()); ok {
// On a pluggable transport path. Report the transport name and its
// real remote address (not the synthetic magic IP).
ps.TransportName = inst.name
ps.CurAddr = udpAddr.String()
if disco := de.disco.Load(); disco != nil {
if remoteAddr := inst.t.GetRemoteAddr(disco.key()); remoteAddr != "" {
ps.CurAddr = remoteAddr
}
}
} else {
ps.CurAddr = udpAddr.String()
}
} else {
// Not on a direct or transport path; show the DERP relay being used.
ps.Relay = de.c.derpRegionCodeOfIDLocked(tailcfg.DERPRegionID(de.derpAddr.Port()))
}
}
+144 -14
View File
@@ -96,6 +96,7 @@ type Path string
const (
PathDirectIPv4 Path = "direct_ipv4"
PathDirectIPv6 Path = "direct_ipv6"
PathTransport Path = "transport"
PathDERP Path = "derp"
PathPeerRelayIPv4 Path = "peer_relay_ipv4"
PathPeerRelayIPv6 Path = "peer_relay_ipv6"
@@ -111,6 +112,15 @@ type pathLabel struct {
Path Path
}
// transportReadResult is the result of reading a packet from a pluggable
// transport. It is similar to derpReadResult but for transport connections.
type transportReadResult struct {
transportIdx int // which registered transport this came from
n int // length of data in buf
src key.NodePublic // sender's node public key
buf []byte // packet data; nil signals the receiver to ignore this message
}
// metrics in wgengine contains the usermetrics counters for magicsock, it
// is however a bit special. All them metrics are labeled, but looking up
// the metric everytime we need to record it has an overhead, and includes
@@ -121,6 +131,7 @@ type metrics struct {
// labeled by the path the packet took.
inboundPacketsIPv4Total expvar.Int
inboundPacketsIPv6Total expvar.Int
inboundPacketsTransportTotal expvar.Int
inboundPacketsDERPTotal expvar.Int
inboundPacketsPeerRelayIPv4Total expvar.Int
inboundPacketsPeerRelayIPv6Total expvar.Int
@@ -129,6 +140,7 @@ type metrics struct {
// labeled by the path the packet took.
inboundBytesIPv4Total expvar.Int
inboundBytesIPv6Total expvar.Int
inboundBytesTransportTotal expvar.Int
inboundBytesDERPTotal expvar.Int
inboundBytesPeerRelayIPv4Total expvar.Int
inboundBytesPeerRelayIPv6Total expvar.Int
@@ -137,6 +149,7 @@ type metrics struct {
// labeled by the path the packet took.
outboundPacketsIPv4Total expvar.Int
outboundPacketsIPv6Total expvar.Int
outboundPacketsTransportTotal expvar.Int
outboundPacketsDERPTotal expvar.Int
outboundPacketsPeerRelayIPv4Total expvar.Int
outboundPacketsPeerRelayIPv6Total expvar.Int
@@ -145,6 +158,7 @@ type metrics struct {
// labeled by the path the packet took.
outboundBytesIPv4Total expvar.Int
outboundBytesIPv6Total expvar.Int
outboundBytesTransportTotal expvar.Int
outboundBytesDERPTotal expvar.Int
outboundBytesPeerRelayIPv4Total expvar.Int
outboundBytesPeerRelayIPv6Total expvar.Int
@@ -211,6 +225,11 @@ type Conn struct {
// It must have buffer size > 0; see issue 3736.
derpRecvCh chan derpReadResult
// transportRecvCh is used by receiveTransport to read packets from all
// pluggable transports (multiplexed by transportReadResult.transportIdx).
// It must have buffer size > 0, similar to derpRecvCh.
transportRecvCh chan transportReadResult
// bind is the wireguard-go conn.Bind for Conn.
bind *connBind
@@ -334,6 +353,19 @@ type Conn struct {
// [tailscale.com/net/udprelay.Server] endpoints.
relayManager relayManager
// transports holds the pluggable transports linked into this binary, one
// per package that called RegisterTransport (e.g. a program blank-importing
// github.com/adrianosela/ts-transport-webrtc). It is keyed by the transport's registration
// index (its position in registeredTransports), which is the canonical
// identifier used throughout (magic IP, read-result tag, readiness map). The
// map is nil/empty when no transport package is linked in, or may skip an
// index whose constructor returned nil. magicIPToTransport maps each
// transport's synthetic magic IP to that same registration index, for fast
// send/receive lookup. Both are populated once in initTransports before the
// Conn is used and then only read.
transports map[int]transportInstance
magicIPToTransport map[netip.Addr]int
// discoInfo is the state for an active peer DiscoKey.
discoInfo map[key.DiscoPublic]*discoInfo
@@ -579,14 +611,15 @@ type UDPRelayAllocResp struct {
func newConn(logf logger.Logf) *Conn {
discoPrivate := key.NewDisco()
c := &Conn{
logf: logf,
derpRecvCh: make(chan derpReadResult, 1), // must be buffered, see issue 3736
derpStarted: make(chan struct{}),
peerLastDerp: make(map[key.NodePublic]tailcfg.DERPRegionID),
peerMap: newPeerMap(),
discoInfo: make(map[key.DiscoPublic]*discoInfo),
cloudInfo: cloudinfo.New(logf),
initializedAt: mono.Now(),
logf: logf,
derpRecvCh: make(chan derpReadResult, 1), // must be buffered, see issue 3736
transportRecvCh: make(chan transportReadResult, 64), // must be buffered, similar to derpRecvCh
derpStarted: make(chan struct{}),
peerLastDerp: make(map[key.NodePublic]tailcfg.DERPRegionID),
peerMap: newPeerMap(),
discoInfo: make(map[key.DiscoPublic]*discoInfo),
cloudInfo: cloudinfo.New(logf),
initializedAt: mono.Now(),
}
c.discoAtomic.Set(discoPrivate)
c.bind = &connBind{Conn: c, closed: true}
@@ -737,6 +770,11 @@ func NewConn(opts Options) (*Conn, error) {
}
c.logf("magicsock: disco key = %v", c.discoAtomic.Short())
// Initialize any pluggable transports (disco-based signaling) that are
// linked into this binary. No-op when none are registered.
c.initTransports()
return c, nil
}
@@ -746,6 +784,7 @@ func NewConn(opts Options) (*Conn, error) {
func registerMetrics(reg *usermetric.Registry) *metrics {
pathDirectV4 := pathLabel{Path: PathDirectIPv4}
pathDirectV6 := pathLabel{Path: PathDirectIPv6}
pathTransport := pathLabel{Path: PathTransport}
pathDERP := pathLabel{Path: PathDERP}
pathPeerRelayV4 := pathLabel{Path: PathPeerRelayIPv4}
pathPeerRelayV6 := pathLabel{Path: PathPeerRelayIPv6}
@@ -780,21 +819,25 @@ func registerMetrics(reg *usermetric.Registry) *metrics {
// Map clientmetrics to the usermetric counters.
metricRecvDataPacketsIPv4.Register(&m.inboundPacketsIPv4Total)
metricRecvDataPacketsIPv6.Register(&m.inboundPacketsIPv6Total)
metricRecvDataPacketsTransport.Register(&m.inboundPacketsTransportTotal)
metricRecvDataPacketsDERP.Register(&m.inboundPacketsDERPTotal)
metricRecvDataPacketsPeerRelayIPv4.Register(&m.inboundPacketsPeerRelayIPv4Total)
metricRecvDataPacketsPeerRelayIPv6.Register(&m.inboundPacketsPeerRelayIPv6Total)
metricRecvDataBytesIPv4.Register(&m.inboundBytesIPv4Total)
metricRecvDataBytesIPv6.Register(&m.inboundBytesIPv6Total)
metricRecvDataBytesTransport.Register(&m.inboundBytesTransportTotal)
metricRecvDataBytesDERP.Register(&m.inboundBytesDERPTotal)
metricRecvDataBytesPeerRelayIPv4.Register(&m.inboundBytesPeerRelayIPv4Total)
metricRecvDataBytesPeerRelayIPv6.Register(&m.inboundBytesPeerRelayIPv6Total)
metricSendDataPacketsIPv4.Register(&m.outboundPacketsIPv4Total)
metricSendDataPacketsIPv6.Register(&m.outboundPacketsIPv6Total)
metricSendDataPacketsTransport.Register(&m.outboundPacketsTransportTotal)
metricSendDataPacketsDERP.Register(&m.outboundPacketsDERPTotal)
metricSendDataPacketsPeerRelayIPv4.Register(&m.outboundPacketsPeerRelayIPv4Total)
metricSendDataPacketsPeerRelayIPv6.Register(&m.outboundPacketsPeerRelayIPv6Total)
metricSendDataBytesIPv4.Register(&m.outboundBytesIPv4Total)
metricSendDataBytesIPv6.Register(&m.outboundBytesIPv6Total)
metricSendDataBytesTransport.Register(&m.outboundBytesTransportTotal)
metricSendDataBytesDERP.Register(&m.outboundBytesDERPTotal)
metricSendDataBytesPeerRelayIPv4.Register(&m.outboundBytesPeerRelayIPv4Total)
metricSendDataBytesPeerRelayIPv6.Register(&m.outboundBytesPeerRelayIPv6Total)
@@ -806,24 +849,28 @@ func registerMetrics(reg *usermetric.Registry) *metrics {
inboundPacketsTotal.Set(pathDirectV4, &m.inboundPacketsIPv4Total)
inboundPacketsTotal.Set(pathDirectV6, &m.inboundPacketsIPv6Total)
inboundPacketsTotal.Set(pathTransport, &m.inboundPacketsTransportTotal)
inboundPacketsTotal.Set(pathDERP, &m.inboundPacketsDERPTotal)
inboundPacketsTotal.Set(pathPeerRelayV4, &m.inboundPacketsPeerRelayIPv4Total)
inboundPacketsTotal.Set(pathPeerRelayV6, &m.inboundPacketsPeerRelayIPv6Total)
inboundBytesTotal.Set(pathDirectV4, &m.inboundBytesIPv4Total)
inboundBytesTotal.Set(pathDirectV6, &m.inboundBytesIPv6Total)
inboundBytesTotal.Set(pathTransport, &m.inboundBytesTransportTotal)
inboundBytesTotal.Set(pathDERP, &m.inboundBytesDERPTotal)
inboundBytesTotal.Set(pathPeerRelayV4, &m.inboundBytesPeerRelayIPv4Total)
inboundBytesTotal.Set(pathPeerRelayV6, &m.inboundBytesPeerRelayIPv6Total)
outboundPacketsTotal.Set(pathDirectV4, &m.outboundPacketsIPv4Total)
outboundPacketsTotal.Set(pathDirectV6, &m.outboundPacketsIPv6Total)
outboundPacketsTotal.Set(pathTransport, &m.outboundPacketsTransportTotal)
outboundPacketsTotal.Set(pathDERP, &m.outboundPacketsDERPTotal)
outboundPacketsTotal.Set(pathPeerRelayV4, &m.outboundPacketsPeerRelayIPv4Total)
outboundPacketsTotal.Set(pathPeerRelayV6, &m.outboundPacketsPeerRelayIPv6Total)
outboundBytesTotal.Set(pathDirectV4, &m.outboundBytesIPv4Total)
outboundBytesTotal.Set(pathDirectV6, &m.outboundBytesIPv6Total)
outboundBytesTotal.Set(pathTransport, &m.outboundBytesTransportTotal)
outboundBytesTotal.Set(pathDERP, &m.outboundBytesDERPTotal)
outboundBytesTotal.Set(pathPeerRelayV4, &m.outboundBytesPeerRelayIPv4Total)
outboundBytesTotal.Set(pathPeerRelayV6, &m.outboundBytesPeerRelayIPv6Total)
@@ -838,21 +885,25 @@ func registerMetrics(reg *usermetric.Registry) *metrics {
func deregisterMetrics() {
metricRecvDataPacketsIPv4.UnregisterAll()
metricRecvDataPacketsIPv6.UnregisterAll()
metricRecvDataPacketsTransport.UnregisterAll()
metricRecvDataPacketsDERP.UnregisterAll()
metricRecvDataPacketsPeerRelayIPv4.UnregisterAll()
metricRecvDataPacketsPeerRelayIPv6.UnregisterAll()
metricRecvDataBytesIPv4.UnregisterAll()
metricRecvDataBytesIPv6.UnregisterAll()
metricRecvDataBytesTransport.UnregisterAll()
metricRecvDataBytesDERP.UnregisterAll()
metricRecvDataBytesPeerRelayIPv4.UnregisterAll()
metricRecvDataBytesPeerRelayIPv6.UnregisterAll()
metricSendDataPacketsIPv4.UnregisterAll()
metricSendDataPacketsIPv6.UnregisterAll()
metricSendDataPacketsTransport.UnregisterAll()
metricSendDataPacketsDERP.UnregisterAll()
metricSendDataPacketsPeerRelayIPv4.UnregisterAll()
metricSendDataPacketsPeerRelayIPv6.UnregisterAll()
metricSendDataBytesIPv4.UnregisterAll()
metricSendDataBytesIPv6.UnregisterAll()
metricSendDataBytesTransport.UnregisterAll()
metricSendDataBytesDERP.UnregisterAll()
metricSendDataBytesPeerRelayIPv4.UnregisterAll()
metricSendDataBytesPeerRelayIPv6.UnregisterAll()
@@ -1677,6 +1728,9 @@ func (c *Conn) sendUDPStd(addr netip.AddrPort, b []byte) (sent bool, err error)
// IPv6 address when the local machine doesn't have IPv6 support
// returns (false, nil); it's not an error, but nothing was sent.
func (c *Conn) sendAddr(addr netip.AddrPort, pubKey key.NodePublic, b []byte, isDisco bool, isGeneveEncap bool) (sent bool, err error) {
if idx, ok := c.magicIPToTransport[addr.Addr()]; ok {
return c.sendTransport(idx, addr, pubKey, b)
}
if addr.Addr() != tailcfg.DerpMagicIPAddr {
return c.sendUDP(addr, b, isDisco, isGeneveEncap)
}
@@ -2036,7 +2090,7 @@ func (c *Conn) sendDiscoMessage(dst epAddr, dstKey key.NodePublic, dstDisco key.
if !dstKey.IsZero() {
node = dstKey.ShortString()
}
c.dlogf("[v1] magicsock: disco: %v->%v (%v, %v) sent %v len %v\n", c.discoAtomic.Short(), dstDisco.ShortString(), node, derpStr(dst.String()), disco.MessageSummary(m), len(pkt))
c.dlogf("[v1] magicsock: disco: %v->%v (%v, %v) sent %v len %v\n", c.discoAtomic.Short(), dstDisco.ShortString(), node, pathStr(dst.String()), disco.MessageSummary(m), len(pkt))
}
if isDERP {
metricSentDiscoDERP.Add(1)
@@ -2076,6 +2130,7 @@ type discoRXPath string
const (
discoRXPathUDP discoRXPath = "UDP socket"
discoRXPathDERP discoRXPath = "DERP"
discoRXPathTransport discoRXPath = "transport"
discoRXPathRawSocket discoRXPath = "raw socket"
)
@@ -2411,13 +2466,13 @@ func (c *Conn) handleDiscoMessage(msg []byte, src epAddr, shouldBeRelayHandshake
if isVia {
c.dlogf("[v1] magicsock: disco: %v<-%v via %v (%v, %v) got call-me-maybe-via, %d endpoints",
c.discoAtomic.Short(), epDisco.shortString(), via.ServerDisco.ShortString(),
ep.publicKey.ShortString(), derpStr(src.String()),
ep.publicKey.ShortString(), pathStr(src.String()),
len(via.AddrPorts))
c.relayManager.handleCallMeMaybeVia(ep, lastBest, lastBestIsTrusted, via)
} else {
c.dlogf("[v1] magicsock: disco: %v<-%v (%v, %v) got call-me-maybe, %d endpoints",
c.discoAtomic.Short(), epDisco.shortString(),
ep.publicKey.ShortString(), derpStr(src.String()),
ep.publicKey.ShortString(), pathStr(src.String()),
len(cmm.MyNumber))
go ep.handleCallMeMaybe(cmm)
}
@@ -2472,7 +2527,7 @@ func (c *Conn) handleDiscoMessage(msg []byte, src epAddr, shouldBeRelayHandshake
}
c.dlogf("[v1] magicsock: disco: %v<-%v (%v, %v) got %s, %d endpoints",
c.discoAtomic.Short(), epDisco.shortString(),
ep.publicKey.ShortString(), derpStr(src.String()),
ep.publicKey.ShortString(), pathStr(src.String()),
msgType,
len(resp.AddrPorts))
c.relayManager.handleRxDiscoMsg(c, resp, nodeKey, di.discoKey, src)
@@ -2488,7 +2543,7 @@ func (c *Conn) handleDiscoMessage(msg []byte, src epAddr, shouldBeRelayHandshake
} else {
c.dlogf("[v1] magicsock: disco: %v<-%v (%v, %v) got %s disco[0]=%v disco[1]=%v",
c.discoAtomic.Short(), epDisco.shortString(),
ep.publicKey.ShortString(), derpStr(src.String()),
ep.publicKey.ShortString(), pathStr(src.String()),
msgType,
req.ClientDisco[0].ShortString(), req.ClientDisco[1].ShortString())
}
@@ -2512,6 +2567,20 @@ func (c *Conn) handleDiscoMessage(msg []byte, src epAddr, shouldBeRelayHandshake
RxFromNodeKey: nodeKey,
Message: req,
})
case *disco.TransportSignal:
if !isDERP {
c.logf("[unexpected] transport signaling message received via UDP, expected DERP only")
return
}
inst, ok := c.transportByName(dm.Transport)
if !ok {
// A transport we don't have linked in; ignore.
return
}
// Dispatch to the transport off the hot path; c.mu must not be held. The
// transport owns its payload format; magicsock only forwards the opaque
// bytes to the transport its name selected.
go inst.t.HandleSignal(sender, dm.Payload)
}
return
}
@@ -2612,7 +2681,15 @@ func (c *Conn) handlePingLocked(dm *disco.Ping, src epAddr, di *discoInfo, derpN
// Remember this route if not present.
var dup bool
if isDerp {
_, isTransport := tailcfg.IsTransportMagicIP(src.ap.Addr())
if isDerp || isTransport {
// Both DERP and pluggable transports carry the sender's node key out of
// band (derpNodeSrc), so we resolve the endpoint by node key and reply
// to src directly. Unlike a real UDP ping, we must NOT
// addCandidateEndpoint the magic address: it isn't a discoverable UDP
// endpoint, and a synthetic endpointState entry would be clobbered on
// the next netmap update. Transport liveness is bestAddr-only, like a
// peer-relay path.
if _, ok := c.peerMap.endpointForNodeKey(derpNodeSrc); ok {
numNodes = 1
}
@@ -3531,6 +3608,7 @@ func (c *connBind) Open(ignoredPort uint16) ([]conn.ReceiveFunc, uint16, error)
fns = append(fns, c.receiveIPv4(), c.receiveIPv6())
}
fns = append(fns, c.mkReceiveDERPFunc())
fns = append(fns, c.receiveTransport)
// TODO: Combine receiveIPv4 and receiveIPv6 and receiveIP into a single
// closure that closes over a *RebindingUDPConn?
return fns, c.LocalPort(), nil
@@ -3574,6 +3652,8 @@ func (c *connBind) Close() error {
// which will then check connBind.Closed.
// connBind.Closed takes c.mu, but c.derpRecvCh is buffered.
c.derpRecvCh <- derpReadResult{}
// Likewise unblock receiveTransport, whose channel is also buffered.
c.transportRecvCh <- transportReadResult{}
return nil
}
@@ -3595,6 +3675,17 @@ func (c *Conn) Close() error {
// Conn.Close() behaviors.
c.eventClient.Close()
// Close all pluggable transports before taking c.mu. A transport's Close
// may wait for its own run loop to stop, and that loop can still be running
// SendSignal (via the host), which takes c.mu. If we held c.mu here, that
// SendSignal would block on it while we block waiting for the loop, stalling
// shutdown. c.transports is write-once (set in initTransports before the
// Conn is used) so reading it without c.mu is safe, and transport Close is
// expected to be idempotent.
for _, inst := range c.transports {
inst.t.Close()
}
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
@@ -3613,6 +3704,11 @@ func (c *Conn) Close() error {
ep.stopAndReset()
})
// Note: we deliberately do not close(c.transportRecvCh). Like derpRecvCh, it
// is never closed; receiveTransport unblocks via the sentinel sent from
// connBind.Close and exits by observing connBind.isClosed. Closing it here
// would race with that sentinel send and panic.
c.closed = true
c.connCtxCancel()
c.closeAllDerpLocked("conn-close")
@@ -4183,9 +4279,25 @@ func trySetUDPSocketOptions(pconn nettype.PacketConn, logf logger.Logf) {
}
}
// pathStr formats endpoint addresses for display, replacing magic IPs with readable names.
// It replaces DERP IPs with "derp-" and pluggable transport magic IPs with "transport-".
func pathStr(s string) string {
s = derpStr(s)
s = transportStr(s)
return s
}
// derpStr replaces DERP IPs in s with "derp-".
func derpStr(s string) string { return strings.ReplaceAll(s, "127.3.3.40:", "derp-") }
// transportStr replaces pluggable transport magic IPs in s with "transport-".
func transportStr(s string) string {
for i := range tailcfg.MaxPluggableTransports {
s = strings.ReplaceAll(s, tailcfg.TransportMagicIP(i).String()+":", "transport-")
}
return s
}
// epAddrEndpointCache is a mutex-free single-element cache, mapping from
// a single [epAddr] to a single [*endpoint].
type epAddrEndpointCache struct {
@@ -4266,11 +4378,13 @@ var (
metricRecvDataPacketsDERP = clientmetric.NewAggregateCounter("magicsock_recv_data_derp")
metricRecvDataPacketsIPv4 = clientmetric.NewAggregateCounter("magicsock_recv_data_ipv4")
metricRecvDataPacketsIPv6 = clientmetric.NewAggregateCounter("magicsock_recv_data_ipv6")
metricRecvDataPacketsTransport = clientmetric.NewAggregateCounter("magicsock_recv_data_transport")
metricRecvDataPacketsPeerRelayIPv4 = clientmetric.NewAggregateCounter("magicsock_recv_data_peer_relay_ipv4")
metricRecvDataPacketsPeerRelayIPv6 = clientmetric.NewAggregateCounter("magicsock_recv_data_peer_relay_ipv6")
metricSendDataPacketsDERP = clientmetric.NewAggregateCounter("magicsock_send_data_derp")
metricSendDataPacketsIPv4 = clientmetric.NewAggregateCounter("magicsock_send_data_ipv4")
metricSendDataPacketsIPv6 = clientmetric.NewAggregateCounter("magicsock_send_data_ipv6")
metricSendDataPacketsTransport = clientmetric.NewAggregateCounter("magicsock_send_data_transport")
metricSendDataPacketsPeerRelayIPv4 = clientmetric.NewAggregateCounter("magicsock_send_data_peer_relay_ipv4")
metricSendDataPacketsPeerRelayIPv6 = clientmetric.NewAggregateCounter("magicsock_send_data_peer_relay_ipv6")
@@ -4278,11 +4392,13 @@ var (
metricRecvDataBytesDERP = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_derp")
metricRecvDataBytesIPv4 = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_ipv4")
metricRecvDataBytesIPv6 = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_ipv6")
metricRecvDataBytesTransport = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_transport")
metricRecvDataBytesPeerRelayIPv4 = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_peer_relay_ipv4")
metricRecvDataBytesPeerRelayIPv6 = clientmetric.NewAggregateCounter("magicsock_recv_data_bytes_peer_relay_ipv6")
metricSendDataBytesDERP = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_derp")
metricSendDataBytesIPv4 = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_ipv4")
metricSendDataBytesIPv6 = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_ipv6")
metricSendDataBytesTransport = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_transport")
metricSendDataBytesPeerRelayIPv4 = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_peer_relay_ipv4")
metricSendDataBytesPeerRelayIPv6 = clientmetric.NewAggregateCounter("magicsock_send_data_bytes_peer_relay_ipv6")
@@ -4433,6 +4549,20 @@ func (c *Conn) GetDERPRegionLatency() map[tailcfg.DERPRegionID]time.Duration {
return c.netChecker.RecentRegionLatency()
}
// findEndpointByDisco returns the first endpoint with the given disco key, or nil if not found.
func (c *Conn) findEndpointByDisco(dk key.DiscoPublic) *endpoint {
// peerMap access requires c.mu; forEachEndpointWithDiscoKey reads byNodeKey,
// which is only guarded by c.mu (not peerMap's own nodesMu).
c.mu.Lock()
defer c.mu.Unlock()
var found *endpoint
c.peerMap.forEachEndpointWithDiscoKey(dk, func(ep *endpoint) bool {
found = ep
return false // stop after first match
})
return found
}
// lazyEndpoint is a wireguard [conn.Endpoint] for when magicsock received a
// non-disco (presumably WireGuard) packet from a UDP address from which we
// can't map to a Tailscale peer. But WireGuard most likely can, once it
+298
View File
@@ -0,0 +1,298 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package magicsock
import (
"net/netip"
"tailscale.com/feature"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
// This file defines magicsock's extension point for pluggable third-party
// transports: alternative connectivity paths (e.g. WebRTC) that magicsock can
// send and receive WireGuard traffic over without having any compile-time
// dependency on their implementation.
//
// A transport implementation lives in its own package (e.g.
// github.com/adrianosela/ts-transport-webrtc) and registers itself from its init
// via [RegisterTransport]. magicsock has no knowledge of any concrete
// transport; it only ever sees the [Transport], [TransportHost], and
// [TransportPeer] interfaces. A transport is linked in only when a program
// blank-imports its package; otherwise it is simply not registered and the path
// is absent.
//
// Each registered transport is assigned a synthetic magic IP from the reserved
// block (see [tailcfg.TransportMagicIP]). That magic IP flows through the
// existing endpoint/disco path-selection machinery exactly like the DERP magic
// IP does: it is never sent on the wire, it only tags which local path a packet
// took.
// Transport is a pluggable connectivity path registered via [RegisterTransport]
// and consumed by magicsock. It is implemented by a transport package (e.g.
// github.com/adrianosela/ts-transport-webrtc) and constructed with a
// [TransportHost] giving it the magicsock capabilities it needs. All methods
// must be safe for concurrent use.
type Transport interface {
// Close shuts down the transport and all its peer connections.
Close() error
// EnsureConnecting starts (or retries) a connection to peer if one is not
// already in progress or established. Safe to call from the hot send path.
// The transport decides for itself whether a given peer is eligible.
EnsureConnecting(peer TransportPeer)
// SendPacket sends b to the connected peer identified by dst.
SendPacket(dst key.DiscoPublic, b []byte) error
// GetRemoteAddr returns the selected remote address (host:port) for a
// connected peer, or "" if not connected. Used for status display only.
GetRemoteAddr(dst key.DiscoPublic) string
// HandleSignal dispatches a signaling message (an opaque, transport-owned
// payload) received over disco from fromDisco. The payload is whatever the
// transport's own send side put in a [disco.TransportSignal]; magicsock does
// not interpret it.
HandleSignal(fromDisco key.DiscoPublic, payload []byte)
}
// TransportHost is the set of magicsock capabilities a [Transport] needs. One
// TransportHost is handed to each registered transport at construction time; it
// is bound to that transport's identity, so [TransportHost.SendSignal],
// [TransportHost.DeliverPacket], and [TransportHost.SetChannelReady] act on
// behalf of that specific transport. It is implemented by *Conn (via a small
// per-transport binding). All methods must be safe for concurrent use.
type TransportHost interface {
// LocalDiscoKey returns this node's current disco public key.
LocalDiscoKey() key.DiscoPublic
// PeerForDisco returns the [TransportPeer] for the given disco key, or
// ok=false if no endpoint is known for it.
PeerForDisco(key.DiscoPublic) (p TransportPeer, ok bool)
// SendSignal sends an opaque signaling payload to the peer identified by
// dst, over DERP. The host tags the message with this transport's name so
// the receiving side can dispatch it back to the right transport.
SendSignal(dst key.DiscoPublic, payload []byte) error
// DeliverPacket hands a decrypted data packet from this transport to the
// magicsock receive pipeline, attributed to the given source node key.
DeliverPacket(b []byte, src key.NodePublic)
// SetChannelReady reports whether this transport currently has an open
// channel to peer. While ready, magicsock re-probes this transport's path
// each disco heartbeat so it can be selected, and re-selected after any
// fallback, based on disco pong evidence. Path selection and liveness are
// otherwise driven entirely by disco ping/pong, not by this signal.
SetChannelReady(peer TransportPeer, ready bool)
// Disabled reports whether pluggable transports should be suppressed (e.g.
// a debug knob is set). When true the transport should fall back to DERP.
Disabled() bool
// Logf logs a message.
Logf(format string, args ...any)
}
// TransportPeer abstracts a single magicsock endpoint for a [Transport]. A
// TransportPeer is used as a map key by transports, so implementations must be
// comparable and stable for the lifetime of the endpoint. It is implemented by
// *endpoint.
type TransportPeer interface {
// DiscoKey returns the peer's current disco public key, or ok=false if the
// peer has no disco key yet.
DiscoKey() (dk key.DiscoPublic, ok bool)
// NodeKey returns the peer's node public key (used for WireGuard).
NodeKey() key.NodePublic
// NodeAddr returns the peer's Tailscale IP, for logging only.
NodeAddr() netip.Addr
// IsJS reports whether the peer runs on a JavaScript/Wasm platform (its
// last-known Hostinfo OS is "js"). A transport may use this to decide
// eligibility (e.g. WebRTC is only attempted when at least one side is JS).
IsJS() bool
// DERPReady reports whether the peer currently has a valid DERP address,
// which is required before disco-based signaling can succeed.
DERPReady() bool
}
// TransportBatchMagic is the first byte of a batched transport message, framed
// as [magic][2-byte BE len][pkt]... It must not collide with the first byte of
// the other things that can arrive on a transport: WireGuard packets start with
// 0x01–0x04 and disco packets start with 0x54 ('T'). 'W' collides with neither.
// It is the single source of truth for the framing byte, shared with each
// transport's receive path. (See [Conn.sendTransportBatch].)
const TransportBatchMagic = byte('W')
// Option customizes a transport registration. See [WithPriorityOverDirect].
type Option func(*registeredTransport)
// WithPriorityOverDirect ranks the transport's path above a direct UDP path
// during path selection (see [betterAddr]): transport > Direct > DERP. Use it
// for a transport expected to outperform direct UDP when available, e.g. a LAN
// TCP transport on an OS whose TCP stack is far faster than its UDP path.
//
// By default (without this option) a transport ranks below a direct UDP path
// but above DERP and peer-relay (Direct > transport > DERP), which is right for
// a transport that is a NAT-traversal aid (e.g. WebRTC), where a direct UDP
// path, when it exists, is still best. A direct UDP path is the natural pivot;
// finer ordering is decided by measured disco latency.
func WithPriorityOverDirect() Option {
return func(rt *registeredTransport) { rt.aboveDirect = true }
}
// registeredTransport is one entry in the process-global transport registry.
type registeredTransport struct {
name string
ctor func(TransportHost) Transport
aboveDirect bool // ranks above a direct UDP path; see WithPriorityOverDirect
}
// registeredTransports is the set of transports linked into the binary, in
// registration order. Registration happens from transport packages' init
// functions, before any [Conn] is created, so it needs no locking. The order is
// process-local; it only determines each transport's local magic-IP index and
// never goes on the wire (signaling is dispatched by transport name).
var registeredTransports []registeredTransport
// transportsFeatureName is the [tailscale.com/feature] capability name recorded
// when at least one pluggable transport is linked in. It is a single capability
// shared by all transports (an individual transport is identified by its own
// name, not a feature), so it is registered once here rather than by each
// transport package — [feature.Register] panics on a duplicate name.
const transportsFeatureName = "pluggable-transports"
// RegisterTransport registers a pluggable transport constructor under the given
// name. It is meant to be called from a transport package's init, e.g.:
//
// func init() {
// magicsock.RegisterTransport("webrtc", newTransport)
// }
//
// The name is the transport's identity: it selects the transport's magic-IP
// slot locally and is carried in [disco.TransportSignal] so the receiving side
// dispatches signaling back to the same transport. The first call also records
// the "pluggable-transports" feature (see [transportsFeatureName]); transport
// packages must not call [feature.Register] themselves.
//
// Options customize the registration; see [WithPriorityOverDirect]. By
// default a transport ranks below a direct UDP path (but above DERP).
//
// Every [Conn] created afterward constructs one instance of each registered
// transport. RegisterTransport panics if name is empty, already registered, or
// if more than [tailcfg.MaxPluggableTransports] transports are registered.
func RegisterTransport(name string, ctor func(TransportHost) Transport, opts ...Option) {
if name == "" {
panic("magicsock: RegisterTransport with empty name")
}
if ctor == nil {
panic("magicsock: RegisterTransport with nil constructor")
}
for _, rt := range registeredTransports {
if rt.name == name {
panic("magicsock: duplicate transport registration for " + name)
}
}
if len(registeredTransports) >= tailcfg.MaxPluggableTransports {
panic("magicsock: too many registered transports")
}
// Record the shared capability once, on the first registration.
if !feature.IsRegistered(transportsFeatureName) {
feature.Register(transportsFeatureName)
}
rt := registeredTransport{name: name, ctor: ctor}
for _, opt := range opts {
opt(&rt)
}
registeredTransports = append(registeredTransports, rt)
}
// transportAboveDirect reports whether the transport served by magic IP a was
// registered with [WithPriorityOverDirect]. It returns false when a is
// not a transport magic IP or its transport isn't registered (the default,
// below-direct, ranking). Used by [betterAddr] and the heartbeat probe.
func transportAboveDirect(a netip.Addr) bool {
idx, ok := tailcfg.IsTransportMagicIP(a)
if !ok || idx >= len(registeredTransports) {
return false
}
return registeredTransports[idx].aboveDirect
}
// transportInstance is one live transport within a [Conn]. idx is the
// transport's registration index (its position in registeredTransports), which
// is the canonical identifier used everywhere: it determines the magic IP (via
// [tailcfg.TransportMagicIP]), tags read results and signaling, and keys the
// per-endpoint readiness map. It is NOT necessarily a dense index, since a
// transport whose constructor returned nil is skipped.
type transportInstance struct {
name string
magicIP netip.Addr
idx int
t Transport
}
// transportHost is the per-transport [TransportHost] binding handed to a
// transport at construction. It carries the transport's index so host methods
// that are transport-specific (SendSignal, DeliverPacket, SetChannelReady) act
// on behalf of the right transport.
type transportHost struct {
c *Conn
idx int
}
// initTransports constructs one instance of each registered transport, assigns
// each a magic IP from the reserved block, and records them on c. It is a no-op
// (leaving c.transports empty) when no transport packages are linked in.
// magicsock has no compile-time dependency on any transport; an empty registry
// is what disables the feature.
func (c *Conn) initTransports() {
if len(registeredTransports) == 0 {
return
}
c.transports = make(map[int]transportInstance, len(registeredTransports))
c.magicIPToTransport = make(map[netip.Addr]int, len(registeredTransports))
for i, rt := range registeredTransports {
magicIP := tailcfg.TransportMagicIP(i)
host := &transportHost{c: c, idx: i}
t := rt.ctor(host)
if t == nil {
c.logf("magicsock: transport %q failed to initialize", rt.name)
continue
}
c.logf("magicsock: initialized pluggable transport %q at %v", rt.name, magicIP)
c.transports[i] = transportInstance{
name: rt.name,
magicIP: magicIP,
idx: i,
t: t,
}
c.magicIPToTransport[magicIP] = i
}
}
// transportByMagicIP returns the live transport instance whose magic IP is a,
// or ok=false if a is not a transport magic IP for a linked-in transport.
func (c *Conn) transportByMagicIP(a netip.Addr) (inst transportInstance, ok bool) {
idx, ok := c.magicIPToTransport[a]
if !ok {
return transportInstance{}, false
}
return c.transports[idx], true
}
// transportByName returns the live transport instance registered under name, or
// ok=false if no such transport is linked in.
func (c *Conn) transportByName(name string) (inst transportInstance, ok bool) {
for _, inst := range c.transports {
if inst.name == name {
return inst, true
}
}
return transportInstance{}, false
}
+370
View File
@@ -0,0 +1,370 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package magicsock
import (
"encoding/binary"
"fmt"
"net"
"net/netip"
"github.com/tailscale/wireguard-go/conn"
"tailscale.com/disco"
"tailscale.com/tstime/mono"
"tailscale.com/types/key"
)
// This file implements [TransportHost] (via *Conn and the per-transport
// transportHost binding) and [TransportPeer] (via *endpoint), plus the
// magicsock-side send and receive plumbing shared by all pluggable transports.
// It deals only in magicsock types; each transport's own implementation lives
// in its package.
// transportMagicPort is the fixed port used in the synthetic [epAddr] that
// represents a transport path. The magic IP identifies which transport; the
// port is arbitrary but stable.
const transportMagicPort = 12345
// The following methods implement the transport-independent parts of
// [TransportHost] on *Conn. The transport-specific parts (which need to know
// which transport is calling) are implemented on *transportHost below and
// delegate here with an explicit index.
// LocalDiscoKey implements [TransportHost].
func (c *Conn) LocalDiscoKey() key.DiscoPublic { return c.DiscoPublicKey() }
// Disabled implements [TransportHost]. Pluggable transports are suppressed when
// the operator has forced all traffic over DERP, or disabled pluggable
// transports, for debugging. In either case affected peers fall back to DERP.
func (c *Conn) Disabled() bool { return debugAlwaysDERP() || debugDisablePluggableTransports() }
// Logf implements [TransportHost].
func (c *Conn) Logf(format string, args ...any) { c.logf(format, args...) }
// PeerForDisco implements [TransportHost].
func (c *Conn) PeerForDisco(dk key.DiscoPublic) (TransportPeer, bool) {
if ep := c.findEndpointByDisco(dk); ep != nil {
return ep, true
}
return nil, false
}
// sendTransportSignal routes a transport signaling disco message to the peer
// identified by dst, via that peer's home DERP region, tagged with the given
// transport name so the receiver can dispatch it.
func (c *Conn) sendTransportSignal(name string, dst key.DiscoPublic, payload []byte) error {
// Find the endpoint and its home DERP address under the Conn lock.
c.mu.Lock()
var (
derpAddr netip.AddrPort
nodeKey key.NodePublic
found bool
)
c.peerMap.forEachEndpointWithDiscoKey(dst, func(ep *endpoint) bool {
ep.mu.Lock()
derpAddr = ep.derpAddr
ep.mu.Unlock()
nodeKey = ep.publicKey
found = true
return false // stop after first match
})
c.mu.Unlock()
if !found {
return fmt.Errorf("transport: no endpoint for disco key %v", dst.ShortString())
}
if !derpAddr.IsValid() {
return fmt.Errorf("transport: no DERP address for peer %v", dst.ShortString())
}
m := &disco.TransportSignal{Transport: name, Payload: payload}
_, err := c.sendDiscoMessage(epAddr{ap: derpAddr}, nodeKey, dst, m, discoLog)
return err
}
// deliverTransportPacket queues a decrypted transport data packet for processing
// by wireguard-go through transportRecvCh, tagged with the transport index so
// the receive path can attribute it to the right magic IP.
func (c *Conn) deliverTransportPacket(idx int, b []byte, src key.NodePublic) {
// Copy into a fresh slice: b belongs to the reader goroutine's reusable
// buffer which will be overwritten on the next Read call.
pkt := make([]byte, len(b))
copy(pkt, b)
select {
case c.transportRecvCh <- transportReadResult{transportIdx: idx, n: len(pkt), src: src, buf: pkt}:
case <-c.connCtx.Done():
default:
c.logf("transport: dropped packet from %v, receive channel full", src.ShortString())
}
}
// The following methods implement [TransportHost] on *transportHost, the
// per-transport binding. They forward to *Conn with this transport's identity.
func (h *transportHost) LocalDiscoKey() key.DiscoPublic { return h.c.LocalDiscoKey() }
func (h *transportHost) Disabled() bool { return h.c.Disabled() }
func (h *transportHost) Logf(format string, args ...any) {
h.c.Logf(format, args...)
}
func (h *transportHost) PeerForDisco(dk key.DiscoPublic) (TransportPeer, bool) {
return h.c.PeerForDisco(dk)
}
// SendSignal implements [TransportHost]. It tags the payload with this
// transport's registered name.
func (h *transportHost) SendSignal(dst key.DiscoPublic, payload []byte) error {
return h.c.sendTransportSignal(registeredTransports[h.idx].name, dst, payload)
}
// DeliverPacket implements [TransportHost]. It attributes the packet to this
// transport.
func (h *transportHost) DeliverPacket(b []byte, src key.NodePublic) {
h.c.deliverTransportPacket(h.idx, b, src)
}
// SetChannelReady implements [TransportHost]. It marks this transport's channel
// to peer open (ready=true) or closed (ready=false). While ready, the disco
// heartbeat re-probes this transport's magic address every interval (see
// maybeProbeTransportsLocked), so its path can be selected, and re-selected
// after any fallback, purely on disco pong evidence. This is the analogue of
// relay path re-discovery: a one-shot promotion would wedge on DERP the first
// time a pong arrived late.
func (h *transportHost) SetChannelReady(peer TransportPeer, ready bool) {
ep, ok := peer.(*endpoint)
if !ok {
return
}
ep.mu.Lock()
defer ep.mu.Unlock()
ep.setTransportChannelReadyLocked(h.idx, ready)
if ready {
// Send an immediate probe so promotion doesn't wait up to a full
// heartbeat interval.
ep.maybeProbeTransportsLocked(mono.Now())
}
}
// The following methods implement [TransportPeer] on *endpoint.
// DiscoKey implements [TransportPeer].
func (de *endpoint) DiscoKey() (key.DiscoPublic, bool) {
d := de.disco.Load()
if d == nil {
return key.DiscoPublic{}, false
}
return d.key(), true
}
// NodeKey implements [TransportPeer].
func (de *endpoint) NodeKey() key.NodePublic { return de.publicKey }
// NodeAddr implements [TransportPeer].
func (de *endpoint) NodeAddr() netip.Addr { return de.nodeAddr }
// IsJS implements [TransportPeer]. It reports whether the peer's last-known
// Hostinfo OS is "js", i.e. the peer is a browser/Wasm node (a node whose
// runtime.GOOS is "js").
func (de *endpoint) IsJS() bool {
de.c.mu.Lock()
defer de.c.mu.Unlock()
nv, ok := de.c.peersByID[de.nodeID]
if !ok || !nv.Valid() {
return false
}
hi := nv.Hostinfo()
return hi.Valid() && hi.OS() == "js"
}
// DERPReady implements [TransportPeer].
func (de *endpoint) DERPReady() bool {
de.mu.Lock()
defer de.mu.Unlock()
return de.derpAddr.IsValid()
}
// sendTransportBatch packs all buffs into a single message and sends it over the
// transport at index idx. Batching is the critical throughput optimization: a
// per-packet transport path typically produces one lower-layer send per
// WireGuard packet. Packing N packets into one message reduces that to a single
// write, the same advantage sendUDPBatch (sendmmsg) gives the regular UDP path.
//
// Wire format for N>1: [TransportBatchMagic][2-byte BE len][packet]...
// Single packet: sent as-is with no framing overhead.
func (c *Conn) sendTransportBatch(idx int, pubKey key.NodePublic, buffs [][]byte, offset int) error {
inst, ok := c.transports[idx]
if !ok {
return nil
}
t := inst.t
// Resolve endpoint and disco key once for the whole batch.
c.mu.Lock()
ep, ok := c.peerMap.endpointForNodeKey(pubKey)
c.mu.Unlock()
if !ok || ep == nil {
return nil
}
disco := ep.disco.Load()
if disco == nil {
return nil
}
if len(buffs) == 1 {
// Fast path: single packet, no framing overhead.
b := buffs[0][offset:]
if err := t.SendPacket(disco.key(), b); err != nil {
return err
}
c.metrics.outboundPacketsTransportTotal.Add(1)
c.metrics.outboundBytesTransportTotal.Add(int64(len(b)))
return nil
}
// Multi-packet batch path.
size := 1 // magic byte
for _, b := range buffs {
size += 2 + len(b[offset:])
}
batch := make([]byte, size)
batch[0] = TransportBatchMagic
pos := 1
var totalBytes int64
for _, b := range buffs {
pkt := b[offset:]
binary.BigEndian.PutUint16(batch[pos:], uint16(len(pkt)))
pos += 2
copy(batch[pos:], pkt)
pos += len(pkt)
totalBytes += int64(len(pkt))
}
if err := t.SendPacket(disco.key(), batch); err != nil {
return err
}
c.metrics.outboundPacketsTransportTotal.Add(int64(len(buffs)))
c.metrics.outboundBytesTransportTotal.Add(totalBytes)
return nil
}
// sendTransport sends a single packet over the transport at index idx to pubKey.
func (c *Conn) sendTransport(idx int, addr netip.AddrPort, pubKey key.NodePublic, b []byte) (sent bool, err error) {
inst, ok := c.transports[idx]
if !ok {
return false, nil
}
t := inst.t
c.mu.Lock()
ep, ok := c.peerMap.endpointForNodeKey(pubKey)
c.mu.Unlock()
if !ok {
return false, nil
}
disco := ep.disco.Load()
if disco == nil {
return false, nil
}
if err := t.SendPacket(disco.key(), b); err != nil {
return false, err
}
c.metrics.outboundPacketsTransportTotal.Add(1)
c.metrics.outboundBytesTransportTotal.Add(int64(len(b)))
return true, nil
}
// receiveTransport is the [conn.ReceiveFunc] for all pluggable transports. It
// reads packets queued by [Conn.deliverTransportPacket] from transportRecvCh,
// blocking until one carrying WireGuard data is available, and returns that
// single packet.
func (c *connBind) receiveTransport(slab []byte, packets []conn.ReceivedPacket) (int, error) {
// Mirror receiveDERP: block for messages and keep waiting when a message
// yields no WireGuard data (n == 0, e.g. a disco packet handled inline).
// A ReceiveFunc must never return (0, nil): wireguard-go treats that as a
// spurious wake and it stops delivering, which manifests as one packet
// getting through and then a stall.
for wr := range c.transportRecvCh {
if c.isClosed() {
break
}
n, ep := c.processTransportReadResult(wr, slab)
if n == 0 {
// No WireGuard data (disco packet, unknown peer, etc.). Wait for
// the next one.
continue
}
packets[0].Size = n
packets[0].Offset = 0
packets[0].Endpoint = ep
return 1, nil
}
return 0, net.ErrClosed
}
// processTransportReadResult processes a transport packet received from
// transportRecvCh. It's similar to processDERPReadResult but for pluggable
// transports, and tags the synthetic source address with the transport's magic
// IP so path selection attributes it correctly.
func (c *Conn) processTransportReadResult(wr transportReadResult, b []byte) (n int, ep *endpoint) {
if wr.buf == nil {
return 0, nil
}
inst, ok := c.transports[wr.transportIdx]
if !ok {
return 0, nil
}
magicIP := inst.magicIP
n = wr.n
ncopy := copy(b, wr.buf[:n])
if ncopy != n {
err := fmt.Errorf("received transport packet of length %d that's too big for WireGuard buf size %d", n, ncopy)
c.logf("magicsock: %v", err)
return 0, nil
}
srcAddr := epAddr{ap: netip.AddrPortFrom(magicIP, transportMagicPort)}
// Check if this looks like a disco packet.
pt, isGeneveEncap := packetLooksLike(b[:n])
if pt == packetLooksLikeDisco && !isGeneveEncap {
c.handleDiscoMessage(b[:n], srcAddr, false, wr.src, discoRXPathTransport)
return 0, nil
}
// Find the endpoint by node key.
c.mu.Lock()
ep, ok = c.peerMap.endpointForNodeKey(wr.src)
c.mu.Unlock()
if !ok {
// We don't know anything about this node key.
return 0, nil
}
ep.noteRecvActivity(srcAddr, mono.Now())
if update := c.connCounter.Load(); update != nil {
update(0, netip.AddrPortFrom(ep.nodeAddr, 0), srcAddr.ap, 1, n, true)
}
c.metrics.inboundPacketsTransportTotal.Add(1)
c.metrics.inboundBytesTransportTotal.Add(int64(n))
return n, ep
}
// transportRemoteAddrForDisco returns the selected remote address for the
// transport serving the given magic IP and disco key, or "" if unavailable. It
// is used by populatePeerStatus for display.
func (c *Conn) transportRemoteAddrForDisco(magicIP netip.Addr, dk key.DiscoPublic) string {
inst, ok := c.transportByMagicIP(magicIP)
if !ok {
return ""
}
return inst.t.GetRemoteAddr(dk)
}
+221
View File
@@ -0,0 +1,221 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package magicsock
import (
"net/netip"
"testing"
"time"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
)
// TestTransportMagicIP tests the pluggable transport magic IP block.
func TestTransportMagicIP(t *testing.T) {
if got := tailcfg.TransportMagicIP(0).String(); got != "127.3.3.41" {
t.Errorf("TransportMagicIP(0) = %v, want 127.3.3.41", got)
}
// Index 0 must be different from the DERP magic IP.
if tailcfg.TransportMagicIP(0) == tailcfg.DerpMagicIPAddr {
t.Error("transport magic IP should be different from DERP magic IP")
}
// Round-trip index detection.
for i := range tailcfg.MaxPluggableTransports {
ip := tailcfg.TransportMagicIP(i)
idx, ok := tailcfg.IsTransportMagicIP(ip)
if !ok || idx != i {
t.Errorf("IsTransportMagicIP(%v) = (%d, %v), want (%d, true)", ip, idx, ok, i)
}
}
// A non-transport address is rejected.
if _, ok := tailcfg.IsTransportMagicIP(tailcfg.DerpMagicIPAddr); ok {
t.Error("DERP magic IP should not be a transport magic IP")
}
if _, ok := tailcfg.IsTransportMagicIP(netip.MustParseAddr("192.168.1.1")); ok {
t.Error("a regular IP should not be a transport magic IP")
}
}
// TestTransportPriorityRanking tests that a transport registered with
// WithPriorityOverDirect beats a direct UDP path, while a default-priority
// transport loses to it.
func TestTransportPriorityRanking(t *testing.T) {
// Register two transports at distinct magic-IP slots with opposite
// priorities, then restore the registry so other tests are unaffected.
saved := registeredTransports
registeredTransports = []registeredTransport{
{name: "below", ctor: func(TransportHost) Transport { return nil }, aboveDirect: false},
{name: "above", ctor: func(TransportHost) Transport { return nil }, aboveDirect: true},
}
t.Cleanup(func() { registeredTransports = saved })
direct := addrQuality{epAddr: epAddr{ap: netip.MustParseAddrPort("192.168.1.100:41641")}, latency: 10 * time.Millisecond}
below := addrQuality{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(0), transportMagicPort)}, latency: 50 * time.Millisecond}
above := addrQuality{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(1), transportMagicPort)}, latency: 50 * time.Millisecond}
tests := []struct {
name string
a, b addrQuality
want bool
}{
{"direct beats below-direct transport", direct, below, true},
{"below-direct transport loses to direct", below, direct, false},
{"above-direct transport beats direct", above, direct, true},
{"direct loses to above-direct transport", direct, above, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := betterAddr(tt.a, tt.b); got != tt.want {
t.Errorf("betterAddr(%v, %v) = %v, want %v", tt.a.ap, tt.b.ap, got, tt.want)
}
})
}
}
// TestTransportPathPriority tests path preference logic: direct > transport > DERP.
func TestTransportPathPriority(t *testing.T) {
directV4 := addrQuality{
epAddr: epAddr{ap: netip.MustParseAddrPort("192.168.1.100:41641")},
latency: 10 * time.Millisecond,
}
transport := addrQuality{
epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(0), transportMagicPort)},
latency: 50 * time.Millisecond,
}
derp := addrQuality{
epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.DerpMagicIPAddr, 1)},
latency: 100 * time.Millisecond,
}
tests := []struct {
name string
a, b addrQuality
want bool // true if a is better than b
}{
{"direct beats transport", directV4, transport, true},
{"transport beats DERP", transport, derp, true},
{"direct beats DERP", directV4, derp, true},
{"DERP loses to transport", derp, transport, false},
{"transport loses to direct", transport, directV4, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := betterAddr(tt.a, tt.b)
if got != tt.want {
t.Errorf("betterAddr(%v, %v) = %v, want %v", tt.a.ap, tt.b.ap, got, tt.want)
}
})
}
}
// TestTransportPathSelection tests iterated path selection with a transport in the mix.
func TestTransportPathSelection(t *testing.T) {
tests := []struct {
name string
paths []addrQuality
wantBest string
}{
{
name: "direct_beats_all",
paths: []addrQuality{
{epAddr: epAddr{ap: netip.MustParseAddrPort("1.2.3.4:1234")}},
{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(0), transportMagicPort)}},
{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.DerpMagicIPAddr, 1)}},
},
wantBest: "1.2.3.4:1234",
},
{
name: "transport_beats_derp",
paths: []addrQuality{
{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.TransportMagicIP(0), transportMagicPort)}},
{epAddr: epAddr{ap: netip.AddrPortFrom(tailcfg.DerpMagicIPAddr, 1)}},
},
wantBest: "127.3.3.41:12345",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
best := tt.paths[0]
for _, path := range tt.paths[1:] {
if betterAddr(path, best) {
best = path
}
}
if best.ap.String() != tt.wantBest {
t.Errorf("Best path = %v, want %v", best.ap, tt.wantBest)
}
})
}
}
// TestTransportReadResult tests the transportReadResult structure.
func TestTransportReadResult(t *testing.T) {
nodeKey := key.NewNode()
testData := []byte("test packet data")
result := transportReadResult{
transportIdx: 0,
n: len(testData),
src: nodeKey.Public(),
buf: testData,
}
if result.n != len(testData) {
t.Errorf("result.n = %d, want %d", result.n, len(testData))
}
if result.src != nodeKey.Public() {
t.Errorf("result.src mismatch")
}
if string(result.buf) != string(testData) {
t.Errorf("result.buf = %q, want %q", result.buf, testData)
}
}
// TestDiscoRXPathTransport tests the transport disco path constant.
func TestDiscoRXPathTransport(t *testing.T) {
if discoRXPathTransport != "transport" {
t.Errorf("discoRXPathTransport = %q, want %q", discoRXPathTransport, "transport")
}
if discoRXPathTransport == discoRXPathDERP {
t.Error("transport path should be different from DERP path")
}
if discoRXPathTransport == discoRXPathUDP {
t.Error("transport path should be different from UDP path")
}
}
// TestTransportMetrics tests that transport metrics are properly defined.
func TestTransportMetrics(t *testing.T) {
if metricRecvDataPacketsTransport == nil {
t.Error("metricRecvDataPacketsTransport should be initialized")
}
if metricRecvDataBytesTransport == nil {
t.Error("metricRecvDataBytesTransport should be initialized")
}
if metricSendDataPacketsTransport == nil {
t.Error("metricSendDataPacketsTransport should be initialized")
}
if metricSendDataBytesTransport == nil {
t.Error("metricSendDataBytesTransport should be initialized")
}
}
// TestPathTransportConstant tests the PathTransport constant.
func TestPathTransportConstant(t *testing.T) {
if PathTransport != "transport" {
t.Errorf("PathTransport = %q, want %q", PathTransport, "transport")
}
if PathTransport == PathDERP {
t.Error("PathTransport should be different from PathDERP")
}
if PathTransport == PathDirectIPv4 {
t.Error("PathTransport should be different from PathDirectIPv4")
}
}