Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions addr.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,57 @@ func toAddrPortKey(addr netip.AddrPort) AddrPort {

return ap
}

// Address precedence values used in the low byte of an ICE-lite candidate's
// local preference. They mirror libwebrtc's IPAddressPrecedence, which follows
// the RFC 6724 policy table.
const (
addrPrecedenceIPv6Loopback = 60
addrPrecedenceIPv6ULA = 50
addrPrecedenceIPv6 = 40
addrPrecedenceIPv4 = 30
addrPrecedenceIPv6To4 = 20
addrPrecedenceIPv6Teredo = 10
addrPrecedenceIPv6Legacy = 1
)

var (
ipv6ULAPrefix = netip.MustParsePrefix("fc00::/7") //nolint:gochecknoglobals
ipv66To4Prefix = netip.MustParsePrefix("2002::/16") //nolint:gochecknoglobals
ipv6TeredoPrefix = netip.MustParsePrefix("2001::/32") //nolint:gochecknoglobals
ipv6V4CompatPrefix = netip.MustParsePrefix("::/96") //nolint:gochecknoglobals
ipv6SiteLocalPrefix = netip.MustParsePrefix("fec0::/10") //nolint:gochecknoglobals
ipv66BonePrefix = netip.MustParsePrefix("3ffe::/16") //nolint:gochecknoglobals
)

// ipAddressPrecedence returns the precedence of addr. If addr is not valid (for
// example an unresolved mDNS candidate) it falls back to the precedence of a
// native address of the candidate's family.
func ipAddressPrecedence(addr netip.Addr, networkType NetworkType) uint8 {
addr = addr.WithZone("")

switch {
case !addr.IsValid():
if networkType.IsIPv6() {
return addrPrecedenceIPv6
}

return addrPrecedenceIPv4
case addr.Is4(), addr.Is4In6():
return addrPrecedenceIPv4
case addr.IsLoopback():
return addrPrecedenceIPv6Loopback
case ipv6ULAPrefix.Contains(addr):
return addrPrecedenceIPv6ULA
case ipv66To4Prefix.Contains(addr):
return addrPrecedenceIPv6To4
case ipv6TeredoPrefix.Contains(addr):
return addrPrecedenceIPv6Teredo
case ipv6V4CompatPrefix.Contains(addr),
ipv6SiteLocalPrefix.Contains(addr),
ipv66BonePrefix.Contains(addr):
return addrPrecedenceIPv6Legacy
default:
return addrPrecedenceIPv6
}
}
25 changes: 25 additions & 0 deletions addr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,28 @@ func TestAsAddrPortReaderWriter(t *testing.T) {
wrapper := &embeddingUDPConnWrapper{UDPConn: udpConn}
require.Nil(t, asAddrPortReaderWriter(wrapper))
}

func TestIPAddressPrecedence(t *testing.T) {
for _, tc := range []struct {
addr string
precedence uint8
}{
{"192.0.2.1", addrPrecedenceIPv4},
{"::ffff:192.0.2.1", addrPrecedenceIPv4},
{"::1", addrPrecedenceIPv6Loopback},
{"fd00::1", addrPrecedenceIPv6ULA},
{"fd00::1%eth0", addrPrecedenceIPv6ULA},
{"2001:db8::1", addrPrecedenceIPv6},
{"fe80::1", addrPrecedenceIPv6},
{"2002:c000:201::1", addrPrecedenceIPv6To4},
{"2001:0:4136:e378::1", addrPrecedenceIPv6Teredo},
{"::192.0.2.1", addrPrecedenceIPv6Legacy},
{"fec0::1", addrPrecedenceIPv6Legacy},
{"3ffe::1", addrPrecedenceIPv6Legacy},
} {
require.Equal(t, tc.precedence, ipAddressPrecedence(netip.MustParseAddr(tc.addr), NetworkTypeUDP4), tc.addr)
}

require.Equal(t, uint8(addrPrecedenceIPv4), ipAddressPrecedence(netip.Addr{}, NetworkTypeUDP4))
require.Equal(t, uint8(addrPrecedenceIPv6), ipAddressPrecedence(netip.Addr{}, NetworkTypeTCP6))
}
36 changes: 26 additions & 10 deletions agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1382,10 +1382,15 @@ func (a *Agent) addRemoteCandidate(cand Candidate) bool { //nolint:cyclop
}

// setUniqueLiteCandidatePriority gives each local ICE-lite candidate a unique
// priority.
// priority that doesn't depend on gather order, so it stays stable across ICE
// restarts. Like libwebrtc, the local preference is
// (counter << 8) | address precedence: the precedence keeps address families
// apart, and the counter only drops to separate candidates of the same family.
// Unlike libwebrtc, the high byte is a counter rather than a network adapter
// preference, since Pion has no adapter types.
// https://datatracker.ietf.org/doc/html/rfc8445#section-5.1.2
func (a *Agent) setUniqueLiteCandidatePriority(cand Candidate) {
if !a.lite {
if !a.lite || cand.hasPriorityOverride() {
return
}

Expand All @@ -1396,22 +1401,33 @@ func (a *Agent) setUniqueLiteCandidatePriority(cand Candidate) {
}
}

const (
precedenceMask = 0xFF << 8 // low byte of the local preference.
counterMask = 0xFF << 16 // high byte of the local preference.
counterStep = 1 << 16
)

priority := cand.Priority()
// Reserve odd local preferences for IPv6 and even ones for IPv4. Otherwise,
// gathering the families in a different order on a migration target can
// lower its priority and let the client prune it in favor of the old path.
if cand.NetworkType().IsIPv4() {
priority -= 1 << 8
if cand.Type() != CandidateTypeRelay {
precedence := ipAddressPrecedence(cand.addrPort().Addr(), cand.NetworkType())
priority = (priority &^ precedenceMask) | uint32(precedence)<<8
}

for {
if _, ok := used[priority]; !ok {
cand.setPriority(priority)
break
}

return
if priority&counterMask == 0 {
a.log.Warnf("No unique priority left for ICE-lite candidate %s, using %d", cand, priority)

break
}

priority -= 2 << 8
priority -= counterStep
}

cand.setPriority(priority)
}

func (a *Agent) shouldAcceptRemoteCandidate(cand Candidate) bool {
Expand Down
81 changes: 57 additions & 24 deletions agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2174,56 +2174,89 @@ func TestLiteLocalCandidatePrioritiesAreUnique(t *testing.T) {
continue
}

require.Equal(t, previousPriority-(2<<8), candidate.Priority())
require.Equal(t, previousPriority-(1<<16), candidate.Priority())
previousPriority = candidate.Priority()
}
}

func TestLiteLocalCandidatePrioritiesDoNotDependOnAddressFamilyOrder(t *testing.T) {
func TestLiteLocalCandidatePrioritiesDoNotDependOnGatherOrder(t *testing.T) {
for _, tc := range []struct {
name string
network string
tcpType TCPType
}{
{name: "udp", network: "udp"},
{name: "passive tcp", network: "tcp", tcpType: TCPTypePassive},
{name: "active tcp", network: "tcp", tcpType: TCPTypeActive},
{name: "UDP", network: "udp"},
{name: "PassiveTCP", network: "tcp", tcpType: TCPTypePassive},
{name: "ActiveTCP", network: "tcp", tcpType: TCPTypeActive},
} {
t.Run(tc.name, func(t *testing.T) {
priorities := func(addresses []string) map[string]uint32 {
t.Helper()
newCandidate := func(address string) Candidate {
candidate, err := NewCandidateHost(&CandidateHostConfig{
Network: tc.network,
Address: address,
Port: 10000,
Component: ComponentRTP,
TCPType: tc.tcpType,
})
require.NoError(t, err)

return candidate
}

gather := func(addresses ...string) map[string]uint32 {
agent := &Agent{lite: true, localCandidates: make(map[NetworkType][]Candidate)}
result := make(map[string]uint32)
priorities := make(map[string]uint32)
for _, address := range addresses {
candidate, err := NewCandidateHost(&CandidateHostConfig{
Network: tc.network, Address: address, Port: 5000, Component: ComponentRTP, TCPType: tc.tcpType,
})
require.NoError(t, err)

candidate := newCandidate(address)
agent.setUniqueLiteCandidatePriority(candidate)
agent.localCandidates[candidate.NetworkType()] = append(agent.localCandidates[candidate.NetworkType()], candidate)
result[address] = candidate.Priority()
agent.localCandidates[candidate.NetworkType()] = append(
agent.localCandidates[candidate.NetworkType()], candidate,
)
priorities[address] = candidate.Priority()
}

return result
return priorities
}

ipv4First := priorities([]string{"192.0.2.1", "2001:db8::1", "192.0.2.2", "2001:db8::2"})
ipv6First := priorities([]string{"2001:db8::1", "192.0.2.1", "2001:db8::2", "192.0.2.2"})
require.Equal(t, ipv4First, ipv6First, "a migration must not lower candidate priorities when the address families gather in a different order")
require.Equal(t, ipv4First["192.0.2.1"], priorities([]string{"192.0.2.1"})["192.0.2.1"], "IPv4 priority must not depend on IPv6 being available")
require.Equal(t, ipv4First["2001:db8::1"], priorities([]string{"2001:db8::1"})["2001:db8::1"], "IPv6 priority must not depend on IPv4 being available")
ipv4First := gather("192.0.2.1", "192.0.2.2", "2001:db8::1", "2001:db8::2")
ipv6First := gather("2001:db8::1", "2001:db8::2", "192.0.2.1", "192.0.2.2")
interleaved := gather("2001:db8::1", "192.0.2.1", "2001:db8::2", "192.0.2.2")
require.Equal(t, ipv4First, ipv6First)
require.Equal(t, ipv4First, interleaved)

require.Equal(t, ipv4First["192.0.2.1"], gather("192.0.2.1")["192.0.2.1"])
require.Equal(t, ipv4First["2001:db8::1"], gather("2001:db8::1")["2001:db8::1"])

seen := make(map[uint32]bool)
unique := make(map[uint32]struct{})
for _, priority := range ipv4First {
require.False(t, seen[priority], "ICE-lite candidate priorities must remain unique")
seen[priority] = true
unique[priority] = struct{}{}
}
require.Len(t, unique, len(ipv4First))

require.Greater(t, ipv4First["2001:db8::1"], ipv4First["192.0.2.1"])
})
}
}

func TestLiteLocalCandidatePriorityKeepsOverride(t *testing.T) {
agent := &Agent{lite: true, localCandidates: make(map[NetworkType][]Candidate)}

for i := range 2 {
candidate, err := NewCandidateHost(&CandidateHostConfig{
Network: "udp",
Address: "192.0.2." + strconv.Itoa(i+1),
Port: 10000,
Component: ComponentRTP,
Priority: 200,
})
require.NoError(t, err)

agent.setUniqueLiteCandidatePriority(candidate)
agent.localCandidates[candidate.NetworkType()] = append(agent.localCandidates[candidate.NetworkType()], candidate)
require.Equal(t, uint32(200), candidate.Priority())
}
}

func TestCloseInConnectionStateCallback(t *testing.T) {
defer test.CheckRoutines(t)()

Expand Down
1 change: 1 addition & 0 deletions candidate.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ type Candidate interface {
start(a *Agent, conn net.PacketConn, initializedCh <-chan struct{})
writeTo(raw []byte, dst Candidate) (int, error)
setPriority(uint32)
hasPriorityOverride() bool
prflxPriority() uint32

replaceRemoteCandidateCacheValues(oldRemote, newRemote Candidate)
Expand Down
4 changes: 4 additions & 0 deletions candidate_base.go
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,10 @@ func (c *candidateBase) setPriority(priority uint32) {
c.priorityOverride = priority
}

func (c *candidateBase) hasPriorityOverride() bool {
return c.priorityOverride != 0
}

// prflxPriority returns the value a Binding request sent from this candidate
// carries in its PRIORITY attribute: the candidate's priority recomputed with
// the type preference of a peer-reflexive candidate.
Expand Down
Loading