all: convert more code to use net/netip directly

perl -i -npe 's,netaddr.IPPrefixFrom,netip.PrefixFrom,' $(git grep -l -F netaddr.)
    perl -i -npe 's,netaddr.IPPortFrom,netip.AddrPortFrom,' $(git grep -l -F netaddr. )
    perl -i -npe 's,netaddr.IPPrefix,netip.Prefix,g' $(git grep -l -F netaddr. )
    perl -i -npe 's,netaddr.IPPort,netip.AddrPort,g' $(git grep -l -F netaddr. )
    perl -i -npe 's,netaddr.IP\b,netip.Addr,g' $(git grep -l -F netaddr. )
    perl -i -npe 's,netaddr.IPv6Raw\b,netip.AddrFrom16,g' $(git grep -l -F netaddr. )
    goimports -w .

Then delete some stuff from the net/netaddr shim package which is no
longer neeed.

Updates #5162

Change-Id: Ia7a86893fe21c7e3ee1ec823e8aba288d4566cd8
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick
2022-07-25 21:14:09 -07:00
committed by Brad Fitzpatrick
parent 6a396731eb
commit a12aad6b47
148 changed files with 1117 additions and 1200 deletions
+2 -2
View File
@@ -8,10 +8,10 @@ import (
"encoding/binary"
"fmt"
"log"
"net/netip"
"sync"
"time"
"tailscale.com/net/netaddr"
"tailscale.com/net/packet"
"tailscale.com/types/ipproto"
)
@@ -94,7 +94,7 @@ func NewTrafficGen(onFirstPacket func()) *TrafficGen {
// Start starts the traffic generator. It assumes mu is already locked,
// and unlocks it.
func (t *TrafficGen) Start(src, dst netaddr.IP, bytesPerPacket int, maxPackets int64) {
func (t *TrafficGen) Start(src, dst netip.Addr, bytesPerPacket int, maxPackets int64) {
h12 := packet.ICMP4Header{
IP4Header: packet.IP4Header{
IPProto: ipproto.ICMPv4,
+10 -10
View File
@@ -8,12 +8,12 @@ import (
"errors"
"io"
"log"
"net/netip"
"os"
"sync"
"testing"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/net/netaddr"
"tailscale.com/net/dns"
"tailscale.com/tailcfg"
@@ -26,14 +26,14 @@ import (
"tailscale.com/wgengine/wgcfg"
)
func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netaddr.IPPrefix) {
func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netip.Prefix) {
l1 := logger.WithPrefix(logf, "e1: ")
k1 := key.NewNode()
c1 := wgcfg.Config{
Name: "e1",
PrivateKey: k1,
Addresses: []netaddr.IPPrefix{a1},
Addresses: []netip.Prefix{a1},
}
t1 := &sourceTun{
logf: logger.WithPrefix(logf, "tun1: "),
@@ -57,7 +57,7 @@ func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netadd
c2 := wgcfg.Config{
Name: "e2",
PrivateKey: k2,
Addresses: []netaddr.IPPrefix{a2},
Addresses: []netip.Prefix{a2},
}
t2 := &sinkTun{
logf: logger.WithPrefix(logf, "tun2: "),
@@ -100,8 +100,8 @@ func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netadd
n := tailcfg.Node{
ID: tailcfg.NodeID(0),
Name: "n1",
Addresses: []netaddr.IPPrefix{a1},
AllowedIPs: []netaddr.IPPrefix{a1},
Addresses: []netip.Prefix{a1},
AllowedIPs: []netip.Prefix{a1},
Endpoints: eps,
}
e2.SetNetworkMap(&netmap.NetworkMap{
@@ -112,7 +112,7 @@ func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netadd
p := wgcfg.Peer{
PublicKey: c1.PrivateKey.Public(),
AllowedIPs: []netaddr.IPPrefix{a1},
AllowedIPs: []netip.Prefix{a1},
}
c2.Peers = []wgcfg.Peer{p}
e2.Reconfig(&c2, &router.Config{}, new(dns.Config), nil)
@@ -137,8 +137,8 @@ func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netadd
n := tailcfg.Node{
ID: tailcfg.NodeID(0),
Name: "n2",
Addresses: []netaddr.IPPrefix{a2},
AllowedIPs: []netaddr.IPPrefix{a2},
Addresses: []netip.Prefix{a2},
AllowedIPs: []netip.Prefix{a2},
Endpoints: eps,
}
e1.SetNetworkMap(&netmap.NetworkMap{
@@ -149,7 +149,7 @@ func setupWGTest(b *testing.B, logf logger.Logf, traf *TrafficGen, a1, a2 netadd
p := wgcfg.Peer{
PublicKey: c2.PrivateKey.Public(),
AllowedIPs: []netaddr.IPPrefix{a2},
AllowedIPs: []netip.Prefix{a2},
}
c1.Peers = []wgcfg.Peer{p}
e1.Reconfig(&c1, &router.Config{}, new(dns.Config), nil)
+15 -14
View File
@@ -7,6 +7,7 @@ package filter
import (
"fmt"
"net/netip"
"sync"
"time"
@@ -107,12 +108,12 @@ const (
// everything. Use in tests only, as it permits some kinds of spoofing
// attacks to reach the OS network stack.
func NewAllowAllForTest(logf logger.Logf) *Filter {
any4 := netaddr.IPPrefixFrom(netaddr.IPv4(0, 0, 0, 0), 0)
any6 := netaddr.IPPrefixFrom(netaddr.IPFrom16([16]byte{}), 0)
any4 := netip.PrefixFrom(netaddr.IPv4(0, 0, 0, 0), 0)
any6 := netip.PrefixFrom(netaddr.IPFrom16([16]byte{}), 0)
ms := []Match{
{
IPProto: []ipproto.Proto{ipproto.TCP, ipproto.UDP, ipproto.ICMPv4},
Srcs: []netaddr.IPPrefix{any4},
Srcs: []netip.Prefix{any4},
Dsts: []NetPortRange{
{
Net: any4,
@@ -125,7 +126,7 @@ func NewAllowAllForTest(logf logger.Logf) *Filter {
},
{
IPProto: []ipproto.Proto{ipproto.TCP, ipproto.UDP, ipproto.ICMPv6},
Srcs: []netaddr.IPPrefix{any6},
Srcs: []netip.Prefix{any6},
Dsts: []NetPortRange{
{
Net: any6,
@@ -180,10 +181,10 @@ func New(matches []Match, localNets *netipx.IPSet, logIPs *netipx.IPSet, shareSt
}
f := &Filter{
logf: logf,
matches4: matchesFamily(matches, netaddr.IP.Is4),
matches6: matchesFamily(matches, netaddr.IP.Is6),
cap4: capMatchesFunc(matches, netaddr.IP.Is4),
cap6: capMatchesFunc(matches, netaddr.IP.Is6),
matches4: matchesFamily(matches, netip.Addr.Is4),
matches6: matchesFamily(matches, netip.Addr.Is6),
cap4: capMatchesFunc(matches, netip.Addr.Is4),
cap6: capMatchesFunc(matches, netip.Addr.Is6),
local: localNets,
logIPs: logIPs,
state: state,
@@ -193,7 +194,7 @@ func New(matches []Match, localNets *netipx.IPSet, logIPs *netipx.IPSet, shareSt
// matchesFamily returns the subset of ms for which keep(srcNet.IP)
// and keep(dstNet.IP) are both true.
func matchesFamily(ms matches, keep func(netaddr.IP) bool) matches {
func matchesFamily(ms matches, keep func(netip.Addr) bool) matches {
var ret matches
for _, m := range ms {
var retm Match
@@ -217,7 +218,7 @@ func matchesFamily(ms matches, keep func(netaddr.IP) bool) matches {
// capMatchesFunc returns a copy of the subset of ms for which keep(srcNet.IP)
// and the match is a capability grant.
func capMatchesFunc(ms matches, keep func(netaddr.IP) bool) matches {
func capMatchesFunc(ms matches, keep func(netip.Addr) bool) matches {
var ret matches
for _, m := range ms {
if len(m.Caps) == 0 {
@@ -299,7 +300,7 @@ var dummyPacket = []byte{
// CheckTCP determines whether TCP traffic from srcIP to dstIP:dstPort
// is allowed.
func (f *Filter) CheckTCP(srcIP, dstIP netaddr.IP, dstPort uint16) Response {
func (f *Filter) CheckTCP(srcIP, dstIP netip.Addr, dstPort uint16) Response {
pkt := &packet.Parsed{}
pkt.Decode(dummyPacket) // initialize private fields
switch {
@@ -314,8 +315,8 @@ func (f *Filter) CheckTCP(srcIP, dstIP netaddr.IP, dstPort uint16) Response {
default:
panic("unreachable")
}
pkt.Src = netaddr.IPPortFrom(srcIP, 0)
pkt.Dst = netaddr.IPPortFrom(dstIP, dstPort)
pkt.Src = netip.AddrPortFrom(srcIP, 0)
pkt.Dst = netip.AddrPortFrom(dstIP, dstPort)
pkt.IPProto = ipproto.TCP
pkt.TCPFlags = packet.TCPSyn
@@ -324,7 +325,7 @@ func (f *Filter) CheckTCP(srcIP, dstIP netaddr.IP, dstPort uint16) Response {
// AppendCaps appends to base the capabilities that srcIP has talking
// to dstIP.
func (f *Filter) AppendCaps(base []string, srcIP, dstIP netaddr.IP) []string {
func (f *Filter) AppendCaps(base []string, srcIP, dstIP netip.Addr) []string {
ret := base
var mm matches
switch {
+21 -22
View File
@@ -15,7 +15,6 @@ import (
"github.com/google/go-cmp/cmp"
"go4.org/netipx"
"tailscale.com/net/netaddr"
"tailscale.com/net/packet"
"tailscale.com/net/tsaddr"
"tailscale.com/tailcfg"
@@ -32,7 +31,7 @@ const (
testDeniedProto ipproto.Proto = 127 // CRUDP, appropriately cruddy
)
func m(srcs []netaddr.IPPrefix, dsts []NetPortRange, protos ...ipproto.Proto) Match {
func m(srcs []netip.Prefix, dsts []NetPortRange, protos ...ipproto.Proto) Match {
if protos == nil {
protos = defaultProtos
}
@@ -243,7 +242,7 @@ func TestParseIPSet(t *testing.T) {
tests := []struct {
host string
bits int
want []netaddr.IPPrefix
want []netip.Prefix
wantErr string
}{
{"8.8.8.8", 24, pfx("8.8.8.8/24"), ""},
@@ -273,8 +272,8 @@ func TestParseIPSet(t *testing.T) {
}
t.Errorf("parseIPSet(%q, %v) error: %v; want error %q", tt.host, tt.bits, err, tt.wantErr)
}
compareIP := cmp.Comparer(func(a, b netaddr.IP) bool { return a == b })
compareIPPrefix := cmp.Comparer(func(a, b netaddr.IPPrefix) bool { return a == b })
compareIP := cmp.Comparer(func(a, b netip.Addr) bool { return a == b })
compareIPPrefix := cmp.Comparer(func(a, b netip.Prefix) bool { return a == b })
if diff := cmp.Diff(got, tt.want, compareIP, compareIPPrefix); diff != "" {
t.Errorf("parseIPSet(%q, %v) = %s; want %s", tt.host, tt.bits, got, tt.want)
continue
@@ -446,10 +445,10 @@ func TestLoggingPrivacy(t *testing.T) {
f.logIPs, _ = logB.IPSet()
var (
ts4 = netaddr.IPPortFrom(tsaddr.CGNATRange().Addr().Next(), 1234)
internet4 = netaddr.IPPortFrom(netip.MustParseAddr("8.8.8.8"), 1234)
ts6 = netaddr.IPPortFrom(tsaddr.TailscaleULARange().Addr().Next(), 1234)
internet6 = netaddr.IPPortFrom(netip.MustParseAddr("2001::1"), 1234)
ts4 = netip.AddrPortFrom(tsaddr.CGNATRange().Addr().Next(), 1234)
internet4 = netip.AddrPortFrom(netip.MustParseAddr("8.8.8.8"), 1234)
ts6 = netip.AddrPortFrom(tsaddr.TailscaleULARange().Addr().Next(), 1234)
internet6 = netip.AddrPortFrom(netip.MustParseAddr("2001::1"), 1234)
)
tests := []struct {
@@ -560,8 +559,8 @@ func parsed(proto ipproto.Proto, src, dst string, sport, dport uint16) packet.Pa
var ret packet.Parsed
ret.Decode(dummyPacket)
ret.IPProto = proto
ret.Src = netaddr.IPPortFrom(sip, sport)
ret.Dst = netaddr.IPPortFrom(dip, dport)
ret.Src = netip.AddrPortFrom(sip, sport)
ret.Dst = netip.AddrPortFrom(dip, dport)
ret.TCPFlags = packet.TCPSyn
if sip.Is4() {
@@ -657,7 +656,7 @@ func parseHexPkt(t *testing.T, h string) *packet.Parsed {
return p
}
func mustIPPort(s string) netaddr.IPPort {
func mustIPPort(s string) netip.AddrPort {
ipp, err := netip.ParseAddrPort(s)
if err != nil {
panic(err)
@@ -665,7 +664,7 @@ func mustIPPort(s string) netaddr.IPPort {
return ipp
}
func pfx(strs ...string) (ret []netaddr.IPPrefix) {
func pfx(strs ...string) (ret []netip.Prefix) {
for _, s := range strs {
pfx, err := netip.ParsePrefix(s)
if err != nil {
@@ -676,7 +675,7 @@ func pfx(strs ...string) (ret []netaddr.IPPrefix) {
return ret
}
func nets(nets ...string) (ret []netaddr.IPPrefix) {
func nets(nets ...string) (ret []netip.Prefix) {
for _, s := range nets {
if !strings.Contains(s, "/") {
ip, err := netip.ParseAddr(s)
@@ -687,7 +686,7 @@ func nets(nets ...string) (ret []netaddr.IPPrefix) {
if ip.Is6() {
bits = 128
}
ret = append(ret, netaddr.IPPrefixFrom(ip, bits))
ret = append(ret, netip.PrefixFrom(ip, int(bits)))
} else {
pfx, err := netip.ParsePrefix(s)
if err != nil {
@@ -779,7 +778,7 @@ func TestMatchesFromFilterRules(t *testing.T) {
Ports: PortRange{22, 22},
},
},
Srcs: []netaddr.IPPrefix{
Srcs: []netip.Prefix{
netip.MustParsePrefix("100.64.1.1/32"),
},
Caps: []CapMatch{},
@@ -809,7 +808,7 @@ func TestMatchesFromFilterRules(t *testing.T) {
Ports: PortRange{22, 22},
},
},
Srcs: []netaddr.IPPrefix{
Srcs: []netip.Prefix{
netip.MustParsePrefix("100.64.1.1/32"),
},
Caps: []CapMatch{},
@@ -824,8 +823,8 @@ func TestMatchesFromFilterRules(t *testing.T) {
t.Fatal(err)
}
compareIP := cmp.Comparer(func(a, b netaddr.IP) bool { return a == b })
compareIPPrefix := cmp.Comparer(func(a, b netaddr.IPPrefix) bool { return a == b })
compareIP := cmp.Comparer(func(a, b netip.Addr) bool { return a == b })
compareIPPrefix := cmp.Comparer(func(a, b netip.Prefix) bool { return a == b })
if diff := cmp.Diff(got, tt.want, compareIP, compareIPPrefix); diff != "" {
t.Errorf("wrong (-got+want)\n%s", diff)
}
@@ -885,7 +884,7 @@ func TestCaps(t *testing.T) {
{
SrcIPs: []string{"*"},
CapGrant: []tailcfg.CapGrant{{
Dsts: []netaddr.IPPrefix{
Dsts: []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/0"),
},
Caps: []string{"is_ipv4"},
@@ -894,7 +893,7 @@ func TestCaps(t *testing.T) {
{
SrcIPs: []string{"*"},
CapGrant: []tailcfg.CapGrant{{
Dsts: []netaddr.IPPrefix{
Dsts: []netip.Prefix{
netip.MustParsePrefix("::/0"),
},
Caps: []string{"is_ipv6"},
@@ -903,7 +902,7 @@ func TestCaps(t *testing.T) {
{
SrcIPs: []string{"100.199.0.0/16"},
CapGrant: []tailcfg.CapGrant{{
Dsts: []netaddr.IPPrefix{
Dsts: []netip.Prefix{
netip.MustParsePrefix("100.200.0.0/16"),
},
Caps: []string{"some_super_admin"},
+5 -5
View File
@@ -6,9 +6,9 @@ package filter
import (
"fmt"
"net/netip"
"strings"
"tailscale.com/net/netaddr"
"tailscale.com/net/packet"
"tailscale.com/types/ipproto"
)
@@ -39,7 +39,7 @@ func (pr PortRange) contains(port uint16) bool {
// NetPortRange combines an IP address prefix and PortRange.
type NetPortRange struct {
Net netaddr.IPPrefix
Net netip.Prefix
Ports PortRange
}
@@ -51,7 +51,7 @@ func (npr NetPortRange) String() string {
type CapMatch struct {
// Dst is the IP prefix that the destination IP address matches against
// to get the capability.
Dst netaddr.IPPrefix
Dst netip.Prefix
// Cap is the capability that's granted if the destination IP addresses
// matches Dst.
@@ -62,7 +62,7 @@ type CapMatch struct {
// Dsts.
type Match struct {
IPProto []ipproto.Proto // required set (no default value at this layer)
Srcs []netaddr.IPPrefix
Srcs []netip.Prefix
Dsts []NetPortRange // optional, if Srcs match
Caps []CapMatch // optional, if Srcs match
}
@@ -152,7 +152,7 @@ func (ms matches) matchProtoAndIPsOnlyIfAllPorts(q *packet.Parsed) bool {
return false
}
func ipInList(ip netaddr.IP, netlist []netaddr.IPPrefix) bool {
func ipInList(ip netip.Addr, netlist []netip.Prefix) bool {
for _, net := range netlist {
if net.Contains(ip) {
return true
+7 -7
View File
@@ -34,7 +34,7 @@ func MatchesFromFilterRules(pf []tailcfg.FilterRule) ([]Match, error) {
// of time in runtime.growslice. As such, we attempt to
// pre-allocate some slices. Multipliers were chosen arbitrarily.
m := Match{
Srcs: make([]netaddr.IPPrefix, 0, len(r.SrcIPs)),
Srcs: make([]netip.Prefix, 0, len(r.SrcIPs)),
Dsts: make([]NetPortRange, 0, 2*len(r.DstPorts)),
Caps: make([]CapMatch, 0, 3*len(r.CapGrant)),
}
@@ -114,12 +114,12 @@ var (
// around, and ultimately use a new version of IPSet.ContainsFunc like
// Contains16Func that works in [16]byte address, so we we can match
// at runtime without allocating?
func parseIPSet(arg string, bits *int) ([]netaddr.IPPrefix, error) {
func parseIPSet(arg string, bits *int) ([]netip.Prefix, error) {
if arg == "*" {
// User explicitly requested wildcard.
return []netaddr.IPPrefix{
netaddr.IPPrefixFrom(zeroIP4, 0),
netaddr.IPPrefixFrom(zeroIP6, 0),
return []netip.Prefix{
netip.PrefixFrom(zeroIP4, 0),
netip.PrefixFrom(zeroIP6, 0),
}, nil
}
if strings.Contains(arg, "/") {
@@ -130,7 +130,7 @@ func parseIPSet(arg string, bits *int) ([]netaddr.IPPrefix, error) {
if pfx != pfx.Masked() {
return nil, fmt.Errorf("%v contains non-network bits set", pfx)
}
return []netaddr.IPPrefix{pfx}, nil
return []netip.Prefix{pfx}, nil
}
if strings.Count(arg, "-") == 1 {
ip1s, ip2s, _ := strings.Cut(arg, "-")
@@ -159,5 +159,5 @@ func parseIPSet(arg string, bits *int) ([]netaddr.IPPrefix, error) {
}
bits8 = uint8(*bits)
}
return []netaddr.IPPrefix{netaddr.IPPrefixFrom(ip, bits8)}, nil
return []netip.Prefix{netip.PrefixFrom(ip, int(bits8))}, nil
}
+5 -5
View File
@@ -9,11 +9,11 @@ import (
"html"
"io"
"net/http"
"net/netip"
"sort"
"strings"
"time"
"tailscale.com/net/netaddr"
"tailscale.com/tailcfg"
"tailscale.com/tstime/mono"
"tailscale.com/types/key"
@@ -73,7 +73,7 @@ func (c *Conn) ServeHTTPDebug(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h2 id=ipport><a href=#ipport>#</a> ip:port to endpoint</h2><ul>")
{
type kv struct {
ipp netaddr.IPPort
ipp netip.AddrPort
pi *peerInfo
}
ent := make([]kv, 0, len(c.peerMap.byIPPort))
@@ -147,7 +147,7 @@ func printEndpointHTML(w io.Writer, ep *endpoint) {
fmt.Fprintf(w, "<p>lastSend: %v ago</p>\n", fmtMono(ep.lastSend))
fmt.Fprintf(w, "<p>lastFullPing: %v ago</p>\n", fmtMono(ep.lastFullPing))
eps := make([]netaddr.IPPort, 0, len(ep.endpointState))
eps := make([]netip.AddrPort, 0, len(ep.endpointState))
for ipp := range ep.endpointState {
eps = append(eps, ipp)
}
@@ -155,7 +155,7 @@ func printEndpointHTML(w io.Writer, ep *endpoint) {
io.WriteString(w, "<p>Endpoints:</p><ul>")
for _, ipp := range eps {
s := ep.endpointState[ipp]
if ipp == ep.bestAddr.IPPort {
if ipp == ep.bestAddr.AddrPort {
fmt.Fprintf(w, "<li><b>%s</b>: (best)<ul>", ipp)
} else {
fmt.Fprintf(w, "<li>%s: ...<ul>", ipp)
@@ -194,7 +194,7 @@ func peerDebugName(p *tailcfg.Node) string {
return p.Hostinfo.Hostname()
}
func ipPortLess(a, b netaddr.IPPort) bool {
func ipPortLess(a, b netip.AddrPort) bool {
if v := a.Addr().Compare(b.Addr()); v != 0 {
return v < 0
}
+64 -64
View File
@@ -81,13 +81,13 @@ type peerInfo struct {
// that when we're deleting this node, we can rapidly find out the
// keys that need deleting from peerMap.byIPPort without having to
// iterate over every IPPort known for any peer.
ipPorts map[netaddr.IPPort]bool
ipPorts map[netip.AddrPort]bool
}
func newPeerInfo(ep *endpoint) *peerInfo {
return &peerInfo{
ep: ep,
ipPorts: map[netaddr.IPPort]bool{},
ipPorts: map[netip.AddrPort]bool{},
}
}
@@ -97,7 +97,7 @@ func newPeerInfo(ep *endpoint) *peerInfo {
// Doesn't do any locking, all access must be done with Conn.mu held.
type peerMap struct {
byNodeKey map[key.NodePublic]*peerInfo
byIPPort map[netaddr.IPPort]*peerInfo
byIPPort map[netip.AddrPort]*peerInfo
// nodesOfDisco contains the set of nodes that are using a
// DiscoKey. Usually those sets will be just one node.
@@ -107,7 +107,7 @@ type peerMap struct {
func newPeerMap() peerMap {
return peerMap{
byNodeKey: map[key.NodePublic]*peerInfo{},
byIPPort: map[netaddr.IPPort]*peerInfo{},
byIPPort: map[netip.AddrPort]*peerInfo{},
nodesOfDisco: map[key.DiscoPublic]map[key.NodePublic]bool{},
}
}
@@ -137,7 +137,7 @@ func (m *peerMap) endpointForNodeKey(nk key.NodePublic) (ep *endpoint, ok bool)
// endpointForIPPort returns the endpoint for the peer we
// believe to be at ipp, or nil if we don't know of any such peer.
func (m *peerMap) endpointForIPPort(ipp netaddr.IPPort) (ep *endpoint, ok bool) {
func (m *peerMap) endpointForIPPort(ipp netip.AddrPort) (ep *endpoint, ok bool) {
if info, ok := m.byIPPort[ipp]; ok {
return info.ep, true
}
@@ -194,7 +194,7 @@ func (m *peerMap) upsertEndpoint(ep *endpoint, oldDiscoKey key.DiscoPublic) {
// This should only be called with a fully verified mapping of ipp to
// nk, because calling this function defines the endpoint we hand to
// WireGuard for packets received from ipp.
func (m *peerMap) setNodeKeyForIPPort(ipp netaddr.IPPort, nk key.NodePublic) {
func (m *peerMap) setNodeKeyForIPPort(ipp netip.AddrPort, nk key.NodePublic) {
if pi := m.byIPPort[ipp]; pi != nil {
delete(pi.ipPorts, ipp)
delete(m.byIPPort, ipp)
@@ -579,7 +579,7 @@ func NewConn(opts Options) (*Conn, error) {
// ignoreSTUNPackets sets a STUN packet processing func that does nothing.
func (c *Conn) ignoreSTUNPackets() {
c.stunReceiveFunc.Store(func([]byte, netaddr.IPPort) {})
c.stunReceiveFunc.Store(func([]byte, netip.AddrPort) {})
}
// doPeriodicSTUN is called (in a new goroutine) by
@@ -843,7 +843,7 @@ func (c *Conn) callNetInfoCallbackLocked(ni *tailcfg.NetInfo) {
// discoKey. It's used in tests to enable receiving of packets from
// addr without having to spin up the entire active discovery
// machinery.
func (c *Conn) addValidDiscoPathForTest(nodeKey key.NodePublic, addr netaddr.IPPort) {
func (c *Conn) addValidDiscoPathForTest(nodeKey key.NodePublic, addr netip.AddrPort) {
c.mu.Lock()
defer c.mu.Unlock()
c.peerMap.setNodeKeyForIPPort(addr, nodeKey)
@@ -908,7 +908,7 @@ func (c *Conn) Ping(peer *tailcfg.Node, res *ipnstate.PingResult, cb func(*ipnst
}
// c.mu must be held
func (c *Conn) populateCLIPingResponseLocked(res *ipnstate.PingResult, latency time.Duration, ep netaddr.IPPort) {
func (c *Conn) populateCLIPingResponseLocked(res *ipnstate.PingResult, latency time.Duration, ep netip.AddrPort) {
res.LatencySeconds = latency.Seconds()
if ep.Addr() != derpMagicIPAddr {
res.Endpoint = ep.String()
@@ -1008,7 +1008,7 @@ func (c *Conn) goDerpConnect(node int) {
if node == 0 {
return
}
go c.derpWriteChanOfAddr(netaddr.IPPortFrom(derpMagicIPAddr, uint16(node)), key.NodePublic{})
go c.derpWriteChanOfAddr(netip.AddrPortFrom(derpMagicIPAddr, uint16(node)), key.NodePublic{})
}
// determineEndpoints returns the machine's endpoint addresses. It
@@ -1017,7 +1017,7 @@ func (c *Conn) goDerpConnect(node int) {
// c.mu must NOT be held.
func (c *Conn) determineEndpoints(ctx context.Context) ([]tailcfg.Endpoint, error) {
var havePortmap bool
var portmapExt netaddr.IPPort
var portmapExt netip.AddrPort
if runtime.GOOS != "js" {
portmapExt, havePortmap = c.portMapper.GetCachedMappingOrStartCreatingOne()
}
@@ -1040,14 +1040,14 @@ func (c *Conn) determineEndpoints(ctx context.Context) ([]tailcfg.Endpoint, erro
}, nil
}
var already map[netaddr.IPPort]tailcfg.EndpointType // endpoint -> how it was found
var already map[netip.AddrPort]tailcfg.EndpointType // endpoint -> how it was found
var eps []tailcfg.Endpoint // unique endpoints
ipp := func(s string) (ipp netaddr.IPPort) {
ipp := func(s string) (ipp netip.AddrPort) {
ipp, _ = netip.ParseAddrPort(s)
return
}
addAddr := func(ipp netaddr.IPPort, et tailcfg.EndpointType) {
addAddr := func(ipp netip.AddrPort, et tailcfg.EndpointType) {
if !ipp.IsValid() || (debugOmitLocalAddresses && et == tailcfg.EndpointLocal) {
return
}
@@ -1100,7 +1100,7 @@ func (c *Conn) determineEndpoints(ctx context.Context) ([]tailcfg.Endpoint, erro
ips = loopback
}
for _, ip := range ips {
addAddr(netaddr.IPPortFrom(ip, uint16(localAddr.Port)), tailcfg.EndpointLocal)
addAddr(netip.AddrPortFrom(ip, uint16(localAddr.Port)), tailcfg.EndpointLocal)
}
} else {
// Our local endpoint is bound to a particular address.
@@ -1186,7 +1186,7 @@ var errNoUDP = errors.New("no UDP available on platform")
// sendUDP sends UDP packet b to ipp.
// See sendAddr's docs on the return value meanings.
func (c *Conn) sendUDP(ipp netaddr.IPPort, b []byte) (sent bool, err error) {
func (c *Conn) sendUDP(ipp netip.AddrPort, b []byte) (sent bool, err error) {
if runtime.GOOS == "js" {
return false, errNoUDP
}
@@ -1235,7 +1235,7 @@ func (c *Conn) sendUDPStd(addr netip.AddrPort, b []byte) (sent bool, err error)
// An example of when they might be different: sending to an
// 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 netaddr.IPPort, pubKey key.NodePublic, b []byte) (sent bool, err error) {
func (c *Conn) sendAddr(addr netip.AddrPort, pubKey key.NodePublic, b []byte) (sent bool, err error) {
if addr.Addr() != derpMagicIPAddr {
return c.sendUDP(addr, b)
}
@@ -1281,7 +1281,7 @@ const bufferedDerpWritesBeforeDrop = 32
//
// If peer is non-zero, it can be used to find an active reverse
// path, without using addr.
func (c *Conn) derpWriteChanOfAddr(addr netaddr.IPPort, peer key.NodePublic) chan<- derpWriteRequest {
func (c *Conn) derpWriteChanOfAddr(addr netip.AddrPort, peer key.NodePublic) chan<- derpWriteRequest {
if addr.Addr() != derpMagicIPAddr {
return nil
}
@@ -1468,7 +1468,7 @@ type derpReadResult struct {
// runDerpReader runs in a goroutine for the life of a DERP
// connection, handling received packets.
func (c *Conn) runDerpReader(ctx context.Context, derpFakeAddr netaddr.IPPort, dc *derphttp.Client, wg *syncs.WaitGroupChan, startGate <-chan struct{}) {
func (c *Conn) runDerpReader(ctx context.Context, derpFakeAddr netip.AddrPort, dc *derphttp.Client, wg *syncs.WaitGroupChan, startGate <-chan struct{}) {
defer wg.Decr()
defer dc.Close()
@@ -1599,7 +1599,7 @@ func (c *Conn) runDerpReader(ctx context.Context, derpFakeAddr netaddr.IPPort, d
}
type derpWriteRequest struct {
addr netaddr.IPPort
addr netip.AddrPort
pubKey key.NodePublic
b []byte // copied; ownership passed to receiver
}
@@ -1666,9 +1666,9 @@ func (c *Conn) receiveIPv4(b []byte) (n int, ep conn.Endpoint, err error) {
//
// ok is whether this read should be reported up to wireguard-go (our
// caller).
func (c *Conn) receiveIP(b []byte, ipp netaddr.IPPort, cache *ippEndpointCache) (ep *endpoint, ok bool) {
func (c *Conn) receiveIP(b []byte, ipp netip.AddrPort, cache *ippEndpointCache) (ep *endpoint, ok bool) {
if stun.Is(b) {
c.stunReceiveFunc.Load().(func([]byte, netaddr.IPPort))(b, ipp)
c.stunReceiveFunc.Load().(func([]byte, netip.AddrPort))(b, ipp)
return nil, false
}
if c.handleDiscoMessage(b, ipp, key.NodePublic{}) {
@@ -1734,7 +1734,7 @@ func (c *Conn) processDERPReadResult(dm derpReadResult, b []byte) (n int, ep *en
return 0, nil
}
ipp := netaddr.IPPortFrom(derpMagicIPAddr, uint16(regionID))
ipp := netip.AddrPortFrom(derpMagicIPAddr, uint16(regionID))
if c.handleDiscoMessage(b[:n], ipp, dm.src) {
return 0, nil
}
@@ -1771,7 +1771,7 @@ const (
//
// The dstKey should only be non-zero if the dstDisco key
// unambiguously maps to exactly one peer.
func (c *Conn) sendDiscoMessage(dst netaddr.IPPort, dstKey key.NodePublic, dstDisco key.DiscoPublic, m disco.Message, logLevel discoLogLevel) (sent bool, err error) {
func (c *Conn) sendDiscoMessage(dst netip.AddrPort, dstKey key.NodePublic, dstDisco key.DiscoPublic, m disco.Message, logLevel discoLogLevel) (sent bool, err error) {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
@@ -1842,7 +1842,7 @@ func (c *Conn) sendDiscoMessage(dst netaddr.IPPort, dstKey key.NodePublic, dstDi
// src.Port() being the region ID) and the derpNodeSrc will be the node key
// it was received from at the DERP layer. derpNodeSrc is zero when received
// over UDP.
func (c *Conn) handleDiscoMessage(msg []byte, src netaddr.IPPort, derpNodeSrc key.NodePublic) (isDiscoMsg bool) {
func (c *Conn) handleDiscoMessage(msg []byte, src netip.AddrPort, derpNodeSrc key.NodePublic) (isDiscoMsg bool) {
const headerLen = len(disco.Magic) + key.DiscoPublicRawLen
if len(msg) < headerLen || string(msg[:len(disco.Magic)]) != disco.Magic {
return false
@@ -2012,7 +2012,7 @@ func (c *Conn) unambiguousNodeKeyOfPingLocked(dm *disco.Ping, dk key.DiscoPublic
// di is the discoInfo of the source of the ping.
// derpNodeSrc is non-zero if the ping arrived via DERP.
func (c *Conn) handlePingLocked(dm *disco.Ping, src netaddr.IPPort, di *discoInfo, derpNodeSrc key.NodePublic) {
func (c *Conn) handlePingLocked(dm *disco.Ping, src netip.AddrPort, di *discoInfo, derpNodeSrc key.NodePublic) {
likelyHeartBeat := src == di.lastPingFrom && time.Since(di.lastPingTime) < 5*time.Second
di.lastPingFrom = src
di.lastPingTime = time.Now()
@@ -2089,7 +2089,7 @@ func (c *Conn) handlePingLocked(dm *disco.Ping, src netaddr.IPPort, di *discoInf
// flipping primary DERPs in the 0-30ms it takes to confirm our STUN endpoint.
// If they do, traffic will just go over DERP for a bit longer until the next
// discovery round.
func (c *Conn) enqueueCallMeMaybe(derpAddr netaddr.IPPort, de *endpoint) {
func (c *Conn) enqueueCallMeMaybe(derpAddr netip.AddrPort, de *endpoint) {
c.mu.Lock()
defer c.mu.Unlock()
@@ -2114,7 +2114,7 @@ func (c *Conn) enqueueCallMeMaybe(derpAddr netaddr.IPPort, de *endpoint) {
return
}
eps := make([]netaddr.IPPort, 0, len(c.lastEndpoints))
eps := make([]netip.AddrPort, 0, len(c.lastEndpoints))
for _, ep := range c.lastEndpoints {
eps = append(eps, ep.Addr)
}
@@ -2347,7 +2347,7 @@ func (c *Conn) SetNetworkMap(nm *netmap.NetworkMap) {
c: c,
publicKey: n.Key,
sentPing: map[stun.TxID]sentPing{},
endpointState: map[netaddr.IPPort]*endpointState{},
endpointState: map[netip.AddrPort]*endpointState{},
}
if !n.DiscoKey.IsZero() {
ep.discoKey = n.DiscoKey
@@ -2425,7 +2425,7 @@ func (c *Conn) closeAllDerpLocked(why string) {
// maybeCloseDERPsOnRebind, in response to a rebind, closes all
// DERP connections that don't have a local address in okayLocalIPs
// and pings all those that do.
func (c *Conn) maybeCloseDERPsOnRebind(okayLocalIPs []netaddr.IPPrefix) {
func (c *Conn) maybeCloseDERPsOnRebind(okayLocalIPs []netip.Prefix) {
c.mu.Lock()
defer c.mu.Unlock()
for regionID, ad := range c.activeDerp {
@@ -2910,7 +2910,7 @@ func (c *Conn) Rebind() {
return
}
var ifIPs []netaddr.IPPrefix
var ifIPs []netip.Prefix
if c.linkMon != nil {
st := c.linkMon.InterfaceState()
defIf := st.DefaultRouteInterface
@@ -2934,7 +2934,7 @@ func (c *Conn) resetEndpointStates() {
}
// packIPPort packs an IPPort into the form wanted by WireGuard.
func packIPPort(ua netaddr.IPPort) []byte {
func packIPPort(ua netip.AddrPort) []byte {
ip := ua.Addr().Unmap()
a := ip.As16()
ipb := a[:]
@@ -3000,12 +3000,12 @@ func (c *RebindingUDPConn) ReadFrom(b []byte) (int, net.Addr, error) {
// ReadFromNetaddr reads a packet from c into b.
// It returns the number of bytes copied and the return address.
// It is identical to c.ReadFrom, except that it returns a netaddr.IPPort instead of a net.Addr.
// It is identical to c.ReadFrom, except that it returns a netip.AddrPort instead of a net.Addr.
// ReadFromNetaddr is designed to work with specific underlying connection types.
// If c's underlying connection returns a non-*net.UPDAddr return address, ReadFromNetaddr will return an error.
// ReadFromNetaddr exists because it removes an allocation per read,
// when c's underlying connection is a net.UDPConn.
func (c *RebindingUDPConn) ReadFromNetaddr(b []byte) (n int, ipp netaddr.IPPort, err error) {
func (c *RebindingUDPConn) ReadFromNetaddr(b []byte) (n int, ipp netip.AddrPort, err error) {
for {
pconn := c.currentConn()
@@ -3019,12 +3019,12 @@ func (c *RebindingUDPConn) ReadFromNetaddr(b []byte) (n int, ipp netaddr.IPPort,
n, addr, err = pconn.ReadFrom(b)
pAddr, ok := addr.(*net.UDPAddr)
if addr != nil && !ok {
return 0, netaddr.IPPort{}, fmt.Errorf("RebindingUDPConn.ReadFromNetaddr: underlying connection returned address of type %T, want *netaddr.UDPAddr", addr)
return 0, netip.AddrPort{}, fmt.Errorf("RebindingUDPConn.ReadFromNetaddr: underlying connection returned address of type %T, want *netaddr.UDPAddr", addr)
}
if pAddr != nil {
ipp, ok = netaddr.FromStdAddr(pAddr.IP, pAddr.Port, pAddr.Zone)
if !ok {
return 0, netaddr.IPPort{}, errors.New("netaddr.FromStdAddr failed")
return 0, netip.AddrPort{}, errors.New("netaddr.FromStdAddr failed")
}
}
}
@@ -3167,7 +3167,7 @@ func simpleDur(d time.Duration) time.Duration {
return d.Round(time.Minute)
}
func sbPrintAddr(sb *strings.Builder, a netaddr.IPPort) {
func sbPrintAddr(sb *strings.Builder, a netip.AddrPort) {
is6 := a.Addr().Is6()
if is6 {
sb.WriteByte('[')
@@ -3205,9 +3205,9 @@ func (c *Conn) UpdateStatus(sb *ipnstate.StatusBuilder) {
c.mu.Lock()
defer c.mu.Unlock()
var tailscaleIPs []netaddr.IP
var tailscaleIPs []netip.Addr
if c.netMap != nil {
tailscaleIPs = make([]netaddr.IP, 0, len(c.netMap.Addresses))
tailscaleIPs = make([]netip.Addr, 0, len(c.netMap.Addresses))
for _, addr := range c.netMap.Addresses {
if !addr.IsSingleIP() {
continue
@@ -3250,7 +3250,7 @@ func (c *Conn) UpdateStatus(sb *ipnstate.StatusBuilder) {
})
}
func ippDebugString(ua netaddr.IPPort) string {
func ippDebugString(ua netip.AddrPort) string {
if ua.Addr() == derpMagicIPAddr {
return fmt.Sprintf("derp-%d", ua.Port())
}
@@ -3268,7 +3268,7 @@ type endpoint struct {
// These fields are initialized once and never modified.
c *Conn
publicKey key.NodePublic // peer public key (for WireGuard + DERP)
fakeWGAddr netaddr.IPPort // the UDP address we tell wireguard-go we're using
fakeWGAddr netip.AddrPort // the UDP address we tell wireguard-go we're using
wgEndpoint string // string from ParseEndpoint, holds a JSON-serialized wgcfg.Endpoints
// mu protects all following fields.
@@ -3280,14 +3280,14 @@ type endpoint struct {
heartBeatTimer *time.Timer // nil when idle
lastSend mono.Time // last time there was outgoing packets sent to this peer (from wireguard-go)
lastFullPing mono.Time // last time we pinged all endpoints
derpAddr netaddr.IPPort // fallback/bootstrap path, if non-zero (non-zero for well-behaved clients)
derpAddr netip.AddrPort // fallback/bootstrap path, if non-zero (non-zero for well-behaved clients)
bestAddr addrLatency // best non-DERP path; zero if none
bestAddrAt mono.Time // time best address re-confirmed
trustBestAddrUntil mono.Time // time when bestAddr expires
sentPing map[stun.TxID]sentPing
endpointState map[netaddr.IPPort]*endpointState
isCallMeMaybeEP map[netaddr.IPPort]bool
endpointState map[netip.AddrPort]*endpointState
isCallMeMaybeEP map[netip.AddrPort]bool
pendingCLIPings []pendingCLIPing // any outstanding "tailscale ping" commands running
}
@@ -3390,9 +3390,9 @@ func (st *endpointState) shouldDeleteLocked() bool {
}
}
func (de *endpoint) deleteEndpointLocked(ep netaddr.IPPort) {
func (de *endpoint) deleteEndpointLocked(ep netip.AddrPort) {
delete(de.endpointState, ep)
if de.bestAddr.IPPort == ep {
if de.bestAddr.AddrPort == ep {
de.bestAddr = addrLatency{}
}
}
@@ -3403,12 +3403,12 @@ const pongHistoryCount = 64
type pongReply struct {
latency time.Duration
pongAt mono.Time // when we received the pong
from netaddr.IPPort // the pong's src (usually same as endpoint map key)
pongSrc netaddr.IPPort // what they reported they heard
from netip.AddrPort // the pong's src (usually same as endpoint map key)
pongSrc netip.AddrPort // what they reported they heard
}
type sentPing struct {
to netaddr.IPPort
to netip.AddrPort
at mono.Time
timer *time.Timer // timeout timer
purpose discoPingPurpose
@@ -3422,7 +3422,7 @@ func (de *endpoint) initFakeUDPAddr() {
addr[0] = 0xfd
addr[1] = 0x00
binary.BigEndian.PutUint64(addr[2:], uint64(reflect.ValueOf(de).Pointer()))
de.fakeWGAddr = netaddr.IPPortFrom(netaddr.IPFrom16(addr), 12345)
de.fakeWGAddr = netip.AddrPortFrom(netaddr.IPFrom16(addr), 12345)
}
// noteRecvActivity records receive activity on de, and invokes
@@ -3467,8 +3467,8 @@ func (de *endpoint) canP2P() bool {
// addr may be non-zero.
//
// de.mu must be held.
func (de *endpoint) addrForSendLocked(now mono.Time) (udpAddr, derpAddr netaddr.IPPort) {
udpAddr = de.bestAddr.IPPort
func (de *endpoint) addrForSendLocked(now mono.Time) (udpAddr, derpAddr netip.AddrPort) {
udpAddr = de.bestAddr.AddrPort
if !udpAddr.IsValid() || now.After(de.trustBestAddrUntil) {
// We had a bestAddr but it expired so send both to it
// and DERP.
@@ -3639,7 +3639,7 @@ func (de *endpoint) removeSentPingLocked(txid stun.TxID, sp sentPing) {
//
// The caller should use de.discoKey as the discoKey argument.
// It is passed in so that sendDiscoPing doesn't need to lock de.mu.
func (de *endpoint) sendDiscoPing(ep netaddr.IPPort, discoKey key.DiscoPublic, txid stun.TxID, logLevel discoLogLevel) {
func (de *endpoint) sendDiscoPing(ep netip.AddrPort, discoKey key.DiscoPublic, txid stun.TxID, logLevel discoLogLevel) {
selfPubKey, _ := de.c.publicKeyAtomic.Load().(key.NodePublic)
sent, _ := de.c.sendDiscoMessage(ep, de.publicKey, discoKey, &disco.Ping{
TxID: [12]byte(txid),
@@ -3668,7 +3668,7 @@ const (
pingCLI
)
func (de *endpoint) startPingLocked(ep netaddr.IPPort, now mono.Time, purpose discoPingPurpose) {
func (de *endpoint) startPingLocked(ep netip.AddrPort, now mono.Time, purpose discoPingPurpose) {
if !de.canP2P() {
panic("tried to disco ping a peer that can't disco")
}
@@ -3749,7 +3749,7 @@ func (de *endpoint) updateFromNode(n *tailcfg.Node) {
de.resetLocked()
}
if n.DERP == "" {
de.derpAddr = netaddr.IPPort{}
de.derpAddr = netip.AddrPort{}
} else {
de.derpAddr, _ = netip.ParseAddrPort(n.DERP)
}
@@ -3788,7 +3788,7 @@ func (de *endpoint) updateFromNode(n *tailcfg.Node) {
//
// This is called once we've already verified that we got a valid
// discovery message from de via ep.
func (de *endpoint) addCandidateEndpoint(ep netaddr.IPPort) {
func (de *endpoint) addCandidateEndpoint(ep netip.AddrPort) {
de.mu.Lock()
defer de.mu.Unlock()
@@ -3833,7 +3833,7 @@ func (de *endpoint) noteConnectivityChange() {
// It should be called with the Conn.mu held.
//
// It reports whether m.TxID corresponds to a ping that this endpoint sent.
func (de *endpoint) handlePongConnLocked(m *disco.Pong, di *discoInfo, src netaddr.IPPort) (knownTxID bool) {
func (de *endpoint) handlePongConnLocked(m *disco.Pong, di *discoInfo, src netip.AddrPort) (knownTxID bool) {
de.mu.Lock()
defer de.mu.Unlock()
@@ -3890,7 +3890,7 @@ func (de *endpoint) handlePongConnLocked(m *disco.Pong, di *discoInfo, src netad
de.c.logf("magicsock: disco: node %v %v now using %v", de.publicKey.ShortString(), de.discoShort, sp.to)
de.bestAddr = thisPong
}
if de.bestAddr.IPPort == thisPong.IPPort {
if de.bestAddr.AddrPort == thisPong.AddrPort {
de.bestAddr.latency = latency
de.bestAddrAt = now
de.trustBestAddrUntil = now.Add(trustUDPAddrDuration)
@@ -3901,13 +3901,13 @@ func (de *endpoint) handlePongConnLocked(m *disco.Pong, di *discoInfo, src netad
// addrLatency is an IPPort with an associated latency.
type addrLatency struct {
netaddr.IPPort
netip.AddrPort
latency time.Duration
}
// betterAddr reports whether a is a better addr to use than b.
func betterAddr(a, b addrLatency) bool {
if a.IPPort == b.IPPort {
if a.AddrPort == b.AddrPort {
return false
}
if !b.IsValid() {
@@ -3965,7 +3965,7 @@ func (de *endpoint) handleCallMeMaybe(m *disco.CallMeMaybe) {
for ep := range de.isCallMeMaybeEP {
de.isCallMeMaybeEP[ep] = false // mark for deletion
}
var newEPs []netaddr.IPPort
var newEPs []netip.AddrPort
for _, ep := range m.MyNumber {
if ep.Addr().Is6() && ep.Addr().IsLinkLocalUnicast() {
// We send these out, but ignore them for now.
@@ -4074,9 +4074,9 @@ func (de *endpoint) numStopAndReset() int64 {
func derpStr(s string) string { return strings.ReplaceAll(s, "127.3.3.40:", "derp-") }
// ippEndpointCache is a mutex-free single-element cache, mapping from
// a single netaddr.IPPort to a single endpoint.
// a single netip.AddrPort to a single endpoint.
type ippEndpointCache struct {
ipp netaddr.IPPort
ipp netip.AddrPort
gen int64
de *endpoint
}
@@ -4107,7 +4107,7 @@ type discoInfo struct {
// Mutable fields follow, owned by Conn.mu:
// lastPingFrom is the src of a ping for discoKey.
lastPingFrom netaddr.IPPort
lastPingFrom netip.AddrPort
// lastPingTime is the last time of a ping for discoKey.
lastPingTime time.Time
+13 -13
View File
@@ -82,7 +82,7 @@ func (c *Conn) WaitReady(t testing.TB) {
}
}
func runDERPAndStun(t *testing.T, logf logger.Logf, l nettype.PacketListener, stunIP netaddr.IP) (derpMap *tailcfg.DERPMap, cleanup func()) {
func runDERPAndStun(t *testing.T, logf logger.Logf, l nettype.PacketListener, stunIP netip.Addr) (derpMap *tailcfg.DERPMap, cleanup func()) {
d := derp.NewServer(key.NewNode(), logf)
httpsrv := httptest.NewUnstartedServer(derphttp.Handler(d))
@@ -222,7 +222,7 @@ func (s *magicStack) Status() *ipnstate.Status {
// Something external needs to provide a NetworkMap and WireGuard
// configs to the magicStack in order for it to acquire an IP
// address. See meshStacks for one possible source of netmaps and IPs.
func (s *magicStack) IP() netaddr.IP {
func (s *magicStack) IP() netip.Addr {
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) {
st := s.Status()
if len(st.TailscaleIPs) > 0 {
@@ -251,13 +251,13 @@ func meshStacks(logf logger.Logf, mutateNetmap func(idx int, nm *netmap.NetworkM
nm := &netmap.NetworkMap{
PrivateKey: me.privateKey,
NodeKey: me.privateKey.Public(),
Addresses: []netaddr.IPPrefix{netaddr.IPPrefixFrom(netaddr.IPv4(1, 0, 0, byte(myIdx+1)), 32)},
Addresses: []netip.Prefix{netip.PrefixFrom(netaddr.IPv4(1, 0, 0, byte(myIdx+1)), 32)},
}
for i, peer := range ms {
if i == myIdx {
continue
}
addrs := []netaddr.IPPrefix{netaddr.IPPrefixFrom(netaddr.IPv4(1, 0, 0, byte(i+1)), 32)}
addrs := []netip.Prefix{netip.PrefixFrom(netaddr.IPv4(1, 0, 0, byte(i+1)), 32)}
peer := &tailcfg.Node{
ID: tailcfg.NodeID(i + 1),
Name: fmt.Sprintf("node%d", i+1),
@@ -833,13 +833,13 @@ func TestActiveDiscovery(t *testing.T) {
type devices struct {
m1 nettype.PacketListener
m1IP netaddr.IP
m1IP netip.Addr
m2 nettype.PacketListener
m2IP netaddr.IP
m2IP netip.Addr
stun nettype.PacketListener
stunIP netaddr.IP
stunIP netip.Addr
}
// newPinger starts continuously sending test packets from srcM to
@@ -1010,24 +1010,24 @@ func testTwoDevicePing(t *testing.T, d *devices) {
m1cfg := &wgcfg.Config{
Name: "peer1",
PrivateKey: m1.privateKey,
Addresses: []netaddr.IPPrefix{netip.MustParsePrefix("1.0.0.1/32")},
Addresses: []netip.Prefix{netip.MustParsePrefix("1.0.0.1/32")},
Peers: []wgcfg.Peer{
{
PublicKey: m2.privateKey.Public(),
DiscoKey: m2.conn.DiscoPublicKey(),
AllowedIPs: []netaddr.IPPrefix{netip.MustParsePrefix("1.0.0.2/32")},
AllowedIPs: []netip.Prefix{netip.MustParsePrefix("1.0.0.2/32")},
},
},
}
m2cfg := &wgcfg.Config{
Name: "peer2",
PrivateKey: m2.privateKey,
Addresses: []netaddr.IPPrefix{netip.MustParsePrefix("1.0.0.2/32")},
Addresses: []netip.Prefix{netip.MustParsePrefix("1.0.0.2/32")},
Peers: []wgcfg.Peer{
{
PublicKey: m1.privateKey.Public(),
DiscoKey: m1.conn.DiscoPublicKey(),
AllowedIPs: []netaddr.IPPrefix{netip.MustParsePrefix("1.0.0.1/32")},
AllowedIPs: []netip.Prefix{netip.MustParsePrefix("1.0.0.1/32")},
},
},
}
@@ -1157,7 +1157,7 @@ func TestDiscoMessage(t *testing.T) {
box := peer1Priv.Shared(c.discoPrivate.Public()).Seal([]byte(payload))
pkt = append(pkt, box...)
got := c.handleDiscoMessage(pkt, netaddr.IPPort{}, key.NodePublic{})
got := c.handleDiscoMessage(pkt, netip.AddrPort{}, key.NodePublic{})
if !got {
t.Error("failed to open it")
}
@@ -1538,7 +1538,7 @@ func TestEndpointSetsEqual(t *testing.T) {
s := func(ports ...uint16) (ret []tailcfg.Endpoint) {
for _, port := range ports {
ret = append(ret, tailcfg.Endpoint{
Addr: netaddr.IPPortFrom(netaddr.IP{}, port),
Addr: netip.AddrPortFrom(netip.Addr{}, port),
})
}
return
+5 -5
View File
@@ -10,12 +10,12 @@ package monitor
import (
"encoding/json"
"errors"
"net/netip"
"runtime"
"sync"
"time"
"tailscale.com/net/interfaces"
"tailscale.com/net/netaddr"
"tailscale.com/types/logger"
)
@@ -69,8 +69,8 @@ type Mon struct {
ruleDelCB map[*callbackHandle]RuleDeleteCallback
ifState *interfaces.State
gwValid bool // whether gw and gwSelfIP are valid
gw netaddr.IP // our gateway's IP
gwSelfIP netaddr.IP // our own IP address (that corresponds to gw)
gw netip.Addr // our gateway's IP
gwSelfIP netip.Addr // our own IP address (that corresponds to gw)
started bool
closed bool
goroutines sync.WaitGroup
@@ -127,7 +127,7 @@ func (m *Mon) interfaceStateUncached() (*interfaces.State, error) {
//
// It's the same as interfaces.LikelyHomeRouterIP, but it caches the
// result until the monitor detects a network change.
func (m *Mon) GatewayAndSelfIP() (gw, myIP netaddr.IP, ok bool) {
func (m *Mon) GatewayAndSelfIP() (gw, myIP netip.Addr, ok bool) {
m.mu.Lock()
defer m.mu.Unlock()
if m.gwValid {
@@ -289,7 +289,7 @@ func (m *Mon) notifyRuleDeleted(rdm ipRuleDeletedMessage) {
// isInterestingInterface reports whether the provided interface should be
// considered when checking for network state changes.
// The ips parameter should be the IPs of the provided interface.
func (m *Mon) isInterestingInterface(i interfaces.Interface, ips []netaddr.IPPrefix) bool {
func (m *Mon) isInterestingInterface(i interfaces.Interface, ips []netip.Prefix) bool {
return m.om.IsInterestingInterface(i.Name) && interfaces.UseInterestingInterfaces(i, ips)
}
+5 -4
View File
@@ -6,6 +6,7 @@ package monitor
import (
"fmt"
"net/netip"
"strings"
"sync"
@@ -170,20 +171,20 @@ func (m *darwinRouteMon) logAddrs(addrs []route.Addr) {
}
}
// ipOfAddr returns the route.Addr (possibly nil) as a netaddr.IP
// ipOfAddr returns the route.Addr (possibly nil) as a netip.Addr
// (possibly zero).
func ipOfAddr(a route.Addr) netaddr.IP {
func ipOfAddr(a route.Addr) netip.Addr {
switch a := a.(type) {
case *route.Inet4Addr:
return netaddr.IPv4(a.IP[0], a.IP[1], a.IP[2], a.IP[3])
case *route.Inet6Addr:
ip := netaddr.IPv6Raw(a.IP)
ip := netip.AddrFrom16(a.IP)
if a.ZoneID != 0 {
ip = ip.WithZone(fmt.Sprint(a.ZoneID)) // TODO: look up net.InterfaceByIndex? but it might be changing?
}
return ip
}
return netaddr.IP{}
return netip.Addr{}
}
func fmtAddr(a route.Addr) any {
+12 -11
View File
@@ -9,6 +9,7 @@ package monitor
import (
"net"
"net/netip"
"time"
"github.com/jsimonetti/rtnetlink"
@@ -43,7 +44,7 @@ type nlConn struct {
// used to suppress duplicate RTM_NEWADDR messages. It is populated
// by RTM_NEWADDR messages and de-populated by RTM_DELADDR. See
// issue #4282.
addrCache map[uint32]map[netaddr.IP]bool
addrCache map[uint32]map[netip.Addr]bool
}
func newOSMon(logf logger.Logf, m *Mon) (osMon, error) {
@@ -61,7 +62,7 @@ func newOSMon(logf logger.Logf, m *Mon) (osMon, error) {
logf("monitor_linux: AF_NETLINK RTMGRP failed, falling back to polling")
return newPollingMon(logf, m)
}
return &nlConn{logf: logf, conn: conn, addrCache: make(map[uint32]map[netaddr.IP]bool)}, nil
return &nlConn{logf: logf, conn: conn, addrCache: make(map[uint32]map[netip.Addr]bool)}, nil
}
func (c *nlConn) IsInterestingInterface(iface string) bool { return true }
@@ -120,7 +121,7 @@ func (c *nlConn) Receive() (message, error) {
// detect them. See nlConn.addrcache and issue #4282.
if msg.Header.Type == unix.RTM_NEWADDR {
if addrs == nil {
addrs = make(map[netaddr.IP]bool)
addrs = make(map[netip.Addr]bool)
c.addrCache[rmsg.Index] = addrs
}
@@ -235,24 +236,24 @@ func (c *nlConn) Receive() (message, error) {
}
}
func netaddrIP(std net.IP) netaddr.IP {
func netaddrIP(std net.IP) netip.Addr {
ip, _ := netaddr.FromStdIP(std)
return ip
}
func netaddrIPPrefix(std net.IP, bits uint8) netaddr.IPPrefix {
func netaddrIPPrefix(std net.IP, bits uint8) netip.Prefix {
ip, _ := netaddr.FromStdIP(std)
return netaddr.IPPrefixFrom(ip, bits)
return netip.PrefixFrom(ip, int(bits))
}
func condNetAddrPrefix(ipp netaddr.IPPrefix) string {
func condNetAddrPrefix(ipp netip.Prefix) string {
if !ipp.Addr().IsValid() {
return ""
}
return ipp.String()
}
func condNetAddrIP(ip netaddr.IP) string {
func condNetAddrIP(ip netip.Addr) string {
if !ip.IsValid() {
return ""
}
@@ -261,8 +262,8 @@ func condNetAddrIP(ip netaddr.IP) string {
// newRouteMessage is a message for a new route being added.
type newRouteMessage struct {
Src, Dst netaddr.IPPrefix
Gateway netaddr.IP
Src, Dst netip.Prefix
Gateway netip.Addr
Table uint8
}
@@ -275,7 +276,7 @@ func (m *newRouteMessage) ignore() bool {
// newAddrMessage is a message for a new address being added.
type newAddrMessage struct {
Delete bool
Addr netaddr.IP
Addr netip.Addr
IfIndex uint32 // interface index
}
+3 -3
View File
@@ -6,12 +6,12 @@ package monitor
import (
"net"
"net/netip"
"testing"
"github.com/jsimonetti/rtnetlink"
"github.com/mdlayher/netlink"
"golang.org/x/sys/unix"
"tailscale.com/net/netaddr"
)
func newAddrMsg(iface uint32, addr string, typ netlink.HeaderType) netlink.Message {
@@ -54,7 +54,7 @@ func TestIgnoreDuplicateNEWADDR(t *testing.T) {
newAddrMsg(1, "192.168.0.5", unix.RTM_NEWADDR),
newAddrMsg(1, "192.168.0.5", unix.RTM_NEWADDR),
},
addrCache: make(map[uint32]map[netaddr.IP]bool),
addrCache: make(map[uint32]map[netip.Addr]bool),
}
msg := mustReceive(&c)
@@ -75,7 +75,7 @@ func TestIgnoreDuplicateNEWADDR(t *testing.T) {
newAddrMsg(1, "192.168.0.5", unix.RTM_DELADDR),
newAddrMsg(1, "192.168.0.5", unix.RTM_NEWADDR),
},
addrCache: make(map[uint32]map[netaddr.IP]bool),
addrCache: make(map[uint32]map[netip.Addr]bool),
}
msg := mustReceive(&c)
+25 -24
View File
@@ -12,6 +12,7 @@ import (
"io"
"log"
"net"
"net/netip"
"os"
"os/exec"
"runtime"
@@ -116,14 +117,14 @@ type Impl struct {
// is a local (non-subnet) Tailscale IP address of this
// machine. It's always a non-nil func. It's changed on netmap
// updates.
atomicIsLocalIPFunc atomic.Value // of func(netaddr.IP) bool
atomicIsLocalIPFunc atomic.Value // of func(netip.Addr) bool
mu sync.Mutex
// connsOpenBySubnetIP keeps track of number of connections open
// for each subnet IP temporarily registered on netstack for active
// TCP connections, so they can be unregistered when connections are
// closed.
connsOpenBySubnetIP map[netaddr.IP]int
connsOpenBySubnetIP map[netip.Addr]int
}
// handleSSH is initialized in ssh.go (on Linux only) to register an SSH server
@@ -191,7 +192,7 @@ func Create(logf logger.Logf, tundev *tstun.Wrapper, e wgengine.Engine, mc *magi
e: e,
mc: mc,
dialer: dialer,
connsOpenBySubnetIP: make(map[netaddr.IP]int),
connsOpenBySubnetIP: make(map[netip.Addr]int),
dns: dns,
}
ns.ctx, ns.ctxCancel = context.WithCancel(context.Background())
@@ -246,7 +247,7 @@ func (ns *Impl) Start() error {
return nil
}
func (ns *Impl) addSubnetAddress(ip netaddr.IP) {
func (ns *Impl) addSubnetAddress(ip netip.Addr) {
ns.mu.Lock()
ns.connsOpenBySubnetIP[ip]++
needAdd := ns.connsOpenBySubnetIP[ip] == 1
@@ -271,7 +272,7 @@ func (ns *Impl) addSubnetAddress(ip netaddr.IP) {
}
}
func (ns *Impl) removeSubnetAddress(ip netaddr.IP) {
func (ns *Impl) removeSubnetAddress(ip netip.Addr) {
ns.mu.Lock()
defer ns.mu.Unlock()
ns.connsOpenBySubnetIP[ip]--
@@ -282,7 +283,7 @@ func (ns *Impl) removeSubnetAddress(ip netaddr.IP) {
}
}
func ipPrefixToAddressWithPrefix(ipp netaddr.IPPrefix) tcpip.AddressWithPrefix {
func ipPrefixToAddressWithPrefix(ipp netip.Prefix) tcpip.AddressWithPrefix {
return tcpip.AddressWithPrefix{
Address: tcpip.Address(ipp.Addr().AsSlice()),
PrefixLen: int(ipp.Bits()),
@@ -308,7 +309,7 @@ func (ns *Impl) updateIPs(nm *netmap.NetworkMap) {
}
newIPs := make(map[tcpip.AddressWithPrefix]bool)
isAddr := map[netaddr.IPPrefix]bool{}
isAddr := map[netip.Prefix]bool{}
if nm.SelfNode != nil {
for _, ipp := range nm.SelfNode.Addresses {
isAddr[ipp] = true
@@ -411,7 +412,7 @@ func (ns *Impl) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper) filter.Re
return filter.DropSilently
}
func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.TCPConn, error) {
func (ns *Impl) DialContextTCP(ctx context.Context, ipp netip.AddrPort) (*gonet.TCPConn, error) {
remoteAddress := tcpip.FullAddress{
NIC: nicID,
Addr: tcpip.Address(ipp.Addr().AsSlice()),
@@ -427,7 +428,7 @@ func (ns *Impl) DialContextTCP(ctx context.Context, ipp netaddr.IPPort) (*gonet.
return gonet.DialContextTCP(ctx, ns.ipstack, remoteAddress, ipType)
}
func (ns *Impl) DialContextUDP(ctx context.Context, ipp netaddr.IPPort) (*gonet.UDPConn, error) {
func (ns *Impl) DialContextUDP(ctx context.Context, ipp netip.AddrPort) (*gonet.UDPConn, error) {
remoteAddress := &tcpip.FullAddress{
NIC: nicID,
Addr: tcpip.Address(ipp.Addr().AsSlice()),
@@ -510,15 +511,15 @@ func (ns *Impl) inject() {
// isLocalIP reports whether ip is a Tailscale IP assigned to this
// node directly (but not a subnet-routed IP).
func (ns *Impl) isLocalIP(ip netaddr.IP) bool {
return ns.atomicIsLocalIPFunc.Load().(func(netaddr.IP) bool)(ip)
func (ns *Impl) isLocalIP(ip netip.Addr) bool {
return ns.atomicIsLocalIPFunc.Load().(func(netip.Addr) bool)(ip)
}
func (ns *Impl) processSSH() bool {
return ns.lb != nil && ns.lb.ShouldRunSSH()
}
func (ns *Impl) peerAPIPortAtomic(ip netaddr.IP) *uint32 {
func (ns *Impl) peerAPIPortAtomic(ip netip.Addr) *uint32 {
if ip.Is4() {
return &ns.peerapiPort4Atomic
} else {
@@ -588,7 +589,7 @@ var isSynology = runtime.GOOS == "linux" && distro.Get() == distro.Synology
//
// TODO(bradfitz): when we're running on Windows as the system user, use
// raw socket APIs instead of ping child processes.
func (ns *Impl) userPing(dstIP netaddr.IP, pingResPkt []byte) {
func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
if !userPingSem.TryAcquire() {
return
}
@@ -702,7 +703,7 @@ func (ns *Impl) injectInbound(p *packet.Parsed, t *tstun.Wrapper) filter.Respons
return filter.DropSilently
}
func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
func netaddrIPFromNetstackIP(s tcpip.Address) netip.Addr {
switch len(s) {
case 4:
return netaddr.IPv4(s[0], s[1], s[2], s[3])
@@ -711,7 +712,7 @@ func netaddrIPFromNetstackIP(s tcpip.Address) netaddr.IP {
copy(a[:], s)
return netaddr.IPFrom16(a)
}
return netaddr.IP{}
return netip.Addr{}
}
func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
@@ -776,7 +777,7 @@ func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
c := gonet.NewTCPConn(&wq, ep)
if reqDetails.LocalPort == 53 && (dialIP == magicDNSIP || dialIP == magicDNSIPv6) {
go ns.dns.HandleTCPConn(c, netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort))
go ns.dns.HandleTCPConn(c, netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort))
return
}
@@ -789,8 +790,8 @@ func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
}
if port, ok := ns.lb.GetPeerAPIPort(dialIP); ok {
if reqDetails.LocalPort == port && ns.isLocalIP(dialIP) {
src := netaddr.IPPortFrom(clientRemoteIP, reqDetails.RemotePort)
dst := netaddr.IPPortFrom(dialIP, port)
src := netip.AddrPortFrom(clientRemoteIP, reqDetails.RemotePort)
dst := netip.AddrPortFrom(dialIP, port)
ns.lb.ServePeerAPIConnection(src, dst, c)
return
}
@@ -808,11 +809,11 @@ func (ns *Impl) acceptTCP(r *tcp.ForwarderRequest) {
if isTailscaleIP {
dialIP = netaddr.IPv4(127, 0, 0, 1)
}
dialAddr := netaddr.IPPortFrom(dialIP, uint16(reqDetails.LocalPort))
dialAddr := netip.AddrPortFrom(dialIP, uint16(reqDetails.LocalPort))
ns.forwardTCP(c, clientRemoteIP, &wq, dialAddr)
}
func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netaddr.IP, wq *waiter.Queue, dialAddr netaddr.IPPort) {
func (ns *Impl) forwardTCP(client *gonet.TCPConn, clientRemoteIP netip.Addr, wq *waiter.Queue, dialAddr netip.AddrPort) {
defer client.Close()
dialAddrStr := dialAddr.String()
if debugNetstack {
@@ -900,7 +901,7 @@ func (ns *Impl) acceptUDP(r *udp.ForwarderRequest) {
go ns.forwardUDP(c, &wq, srcAddr, dstAddr)
}
func (ns *Impl) handleMagicDNSUDP(srcAddr netaddr.IPPort, c *gonet.UDPConn) {
func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
// In practice, implementations are advised not to exceed 512 bytes
// due to fragmenting. Just to be sure, we bump all the way to the MTU.
const maxUDPReqSize = mtu
@@ -941,7 +942,7 @@ func (ns *Impl) handleMagicDNSUDP(srcAddr netaddr.IPPort, c *gonet.UDPConn) {
// dstAddr may be either a local Tailscale IP, in which we case we proxy to
// 127.0.0.1, or any other IP (from an advertised subnet), in which case we
// proxy to it directly.
func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netaddr.IPPort) {
func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr, dstAddr netip.AddrPort) {
port, srcPort := dstAddr.Port(), clientAddr.Port()
if debugNetstack {
ns.logf("[v2] netstack: forwarding incoming UDP connection on port %v", port)
@@ -955,7 +956,7 @@ func (ns *Impl) forwardUDP(client *gonet.UDPConn, wq *waiter.Queue, clientAddr,
backendListenAddr = &net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: int(srcPort)}
} else {
if dstIP := dstAddr.Addr(); viaRange.Contains(dstIP) {
dstAddr = netaddr.IPPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
dstAddr = netip.AddrPortFrom(tsaddr.UnmapVia(dstIP), dstAddr.Port())
}
backendRemoteAddr = net.UDPAddrFromAddrPort(dstAddr)
if dstAddr.Addr().Is4() {
@@ -1058,6 +1059,6 @@ func stringifyTEI(tei stack.TransportEndpointID) string {
return fmt.Sprintf("%s -> %s", remoteHostPort, localHostPort)
}
func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netaddr.IPPort, ok bool) {
func ipPortOfNetstackAddr(a tcpip.Address, port uint16) (ipp netip.AddrPort, ok bool) {
return netaddr.FromStdAddr(net.IP(a), int(port), "") // TODO(bradfitz): can do without allocs
}
+2 -2
View File
@@ -5,11 +5,11 @@
package netstack
import (
"net/netip"
"runtime"
"testing"
"gvisor.dev/gvisor/pkg/refs"
"tailscale.com/net/netaddr"
"tailscale.com/net/packet"
"tailscale.com/net/tsdial"
"tailscale.com/net/tstun"
@@ -53,7 +53,7 @@ func TestInjectInboundLeak(t *testing.T) {
if err := ns.Start(); err != nil {
t.Fatalf("Start: %v", err)
}
ns.atomicIsLocalIPFunc.Store(func(netaddr.IP) bool { return true })
ns.atomicIsLocalIPFunc.Store(func(netip.Addr) bool { return true })
pkt := &packet.Parsed{}
const N = 10_000
+3 -3
View File
@@ -768,8 +768,8 @@ func getAllInterfaceRoutes(ifc *winipcfg.IPAdapterAddresses) ([]*winipcfg.RouteD
// filterRoutes removes routes that have been added by Windows and should not
// be managed by us.
func filterRoutes(routes []*winipcfg.RouteData, dontDelete []netaddr.IPPrefix) []*winipcfg.RouteData {
ddm := make(map[netaddr.IPPrefix]bool)
func filterRoutes(routes []*winipcfg.RouteData, dontDelete []netip.Prefix) []*winipcfg.RouteData {
ddm := make(map[netip.Prefix]bool)
for _, dd := range dontDelete {
// See issue 1448: we don't want to touch the routes added
// by Windows for our interface addresses.
@@ -802,7 +802,7 @@ func filterRoutes(routes []*winipcfg.RouteData, dontDelete []netaddr.IPPrefix) [
// This avoids a full ifc.FlushRoutes call.
// dontDelete is a list of interface address routes that the
// synchronization logic should never delete.
func syncRoutes(ifc *winipcfg.IPAdapterAddresses, want []*winipcfg.RouteData, dontDelete []netaddr.IPPrefix) error {
func syncRoutes(ifc *winipcfg.IPAdapterAddresses, want []*winipcfg.RouteData, dontDelete []netip.Prefix) error {
existingRoutes, err := getAllInterfaceRoutes(ifc)
if err != nil {
return err
+5 -5
View File
@@ -7,10 +7,10 @@
package router
import (
"net/netip"
"reflect"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/net/netaddr"
"tailscale.com/types/logger"
"tailscale.com/types/preftype"
"tailscale.com/wgengine/monitor"
@@ -55,21 +55,21 @@ type Config struct {
// LocalAddrs are the address(es) for this node. This is
// typically one IPv4/32 (the 100.x.y.z CGNAT) and one
// IPv6/128 (Tailscale ULA).
LocalAddrs []netaddr.IPPrefix
LocalAddrs []netip.Prefix
// Routes are the routes that point into the Tailscale
// interface. These are the /32 and /128 routes to peers, as
// well as any other subnets that peers are advertising and
// this node has chosen to use.
Routes []netaddr.IPPrefix
Routes []netip.Prefix
// LocalRoutes are the routes that should not be routed through Tailscale.
// There are no priorities set in how these routes are added, normal
// routing rules apply.
LocalRoutes []netaddr.IPPrefix
LocalRoutes []netip.Prefix
// Linux-only things below, ignored on other platforms.
SubnetRoutes []netaddr.IPPrefix // subnets being advertised to other Tailscale nodes
SubnetRoutes []netip.Prefix // subnets being advertised to other Tailscale nodes
SNATSubnetRoutes bool // SNAT traffic to local subnets
NetfilterMode preftype.NetfilterMode // how much to manage netfilter rules
}
+21 -21
View File
@@ -9,6 +9,7 @@ import (
"errors"
"fmt"
"io/ioutil"
"net/netip"
"os"
"os/exec"
"strconv"
@@ -23,7 +24,6 @@ import (
"golang.org/x/time/rate"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/envknob"
"tailscale.com/net/netaddr"
"tailscale.com/net/tsaddr"
"tailscale.com/syncs"
"tailscale.com/types/logger"
@@ -89,9 +89,9 @@ type linuxRouter struct {
tunname string
linkMon *monitor.Mon
unregLinkMon func()
addrs map[netaddr.IPPrefix]bool
routes map[netaddr.IPPrefix]bool
localRoutes map[netaddr.IPPrefix]bool
addrs map[netip.Prefix]bool
routes map[netip.Prefix]bool
localRoutes map[netip.Prefix]bool
snatSubnetRoutes bool
netfilterMode preftype.NetfilterMode
@@ -451,7 +451,7 @@ func (r *linuxRouter) setNetfilterMode(mode preftype.NetfilterMode) error {
// addAddress adds an IP/mask to the tunnel interface. Fails if the
// address is already assigned to the interface, or if the addition
// fails.
func (r *linuxRouter) addAddress(addr netaddr.IPPrefix) error {
func (r *linuxRouter) addAddress(addr netip.Prefix) error {
if !r.v6Available && addr.Addr().Is6() {
return nil
}
@@ -477,7 +477,7 @@ func (r *linuxRouter) addAddress(addr netaddr.IPPrefix) error {
// delAddress removes an IP/mask from the tunnel interface. Fails if
// the address is not assigned to the interface, or if the removal
// fails.
func (r *linuxRouter) delAddress(addr netaddr.IPPrefix) error {
func (r *linuxRouter) delAddress(addr netip.Prefix) error {
if !r.v6Available && addr.Addr().Is6() {
return nil
}
@@ -502,7 +502,7 @@ func (r *linuxRouter) delAddress(addr netaddr.IPPrefix) error {
// addLoopbackRule adds a firewall rule to permit loopback traffic to
// a local Tailscale IP.
func (r *linuxRouter) addLoopbackRule(addr netaddr.IP) error {
func (r *linuxRouter) addLoopbackRule(addr netip.Addr) error {
if r.netfilterMode == netfilterOff {
return nil
}
@@ -524,7 +524,7 @@ func (r *linuxRouter) addLoopbackRule(addr netaddr.IP) error {
// delLoopbackRule removes the firewall rule permitting loopback
// traffic to a Tailscale IP.
func (r *linuxRouter) delLoopbackRule(addr netaddr.IP) error {
func (r *linuxRouter) delLoopbackRule(addr netip.Addr) error {
if r.netfilterMode == netfilterOff {
return nil
}
@@ -547,7 +547,7 @@ func (r *linuxRouter) delLoopbackRule(addr netaddr.IP) error {
// addRoute adds a route for cidr, pointing to the tunnel
// interface. Fails if the route already exists, or if adding the
// route fails.
func (r *linuxRouter) addRoute(cidr netaddr.IPPrefix) error {
func (r *linuxRouter) addRoute(cidr netip.Prefix) error {
if !r.v6Available && cidr.Addr().Is6() {
return nil
}
@@ -569,7 +569,7 @@ func (r *linuxRouter) addRoute(cidr netaddr.IPPrefix) error {
// This has the effect that lookup in the routing table is terminated
// pretending that no route was found. Fails if the route already exists,
// or if adding the route fails.
func (r *linuxRouter) addThrowRoute(cidr netaddr.IPPrefix) error {
func (r *linuxRouter) addThrowRoute(cidr netip.Prefix) error {
if !r.ipRuleAvailable {
return nil
}
@@ -590,7 +590,7 @@ func (r *linuxRouter) addThrowRoute(cidr netaddr.IPPrefix) error {
return err
}
func (r *linuxRouter) addRouteDef(routeDef []string, cidr netaddr.IPPrefix) error {
func (r *linuxRouter) addRouteDef(routeDef []string, cidr netip.Prefix) error {
if !r.v6Available && cidr.Addr().Is6() {
return nil
}
@@ -624,7 +624,7 @@ var (
// delRoute removes the route for cidr pointing to the tunnel
// interface. Fails if the route doesn't exist, or if removing the
// route fails.
func (r *linuxRouter) delRoute(cidr netaddr.IPPrefix) error {
func (r *linuxRouter) delRoute(cidr netip.Prefix) error {
if !r.v6Available && cidr.Addr().Is6() {
return nil
}
@@ -649,7 +649,7 @@ func (r *linuxRouter) delRoute(cidr netaddr.IPPrefix) error {
// delThrowRoute removes the throw route for the cidr. Fails if the route
// doesn't exist, or if removing the route fails.
func (r *linuxRouter) delThrowRoute(cidr netaddr.IPPrefix) error {
func (r *linuxRouter) delThrowRoute(cidr netip.Prefix) error {
if !r.ipRuleAvailable {
return nil
}
@@ -671,7 +671,7 @@ func (r *linuxRouter) delThrowRoute(cidr netaddr.IPPrefix) error {
return err
}
func (r *linuxRouter) delRouteDef(routeDef []string, cidr netaddr.IPPrefix) error {
func (r *linuxRouter) delRouteDef(routeDef []string, cidr netip.Prefix) error {
if !r.v6Available && cidr.Addr().Is6() {
return nil
}
@@ -694,14 +694,14 @@ func (r *linuxRouter) delRouteDef(routeDef []string, cidr netaddr.IPPrefix) erro
return err
}
func dashFam(ip netaddr.IP) string {
func dashFam(ip netip.Addr) string {
if ip.Is6() {
return "-6"
}
return "-4"
}
func (r *linuxRouter) hasRoute(routeDef []string, cidr netaddr.IPPrefix) (bool, error) {
func (r *linuxRouter) hasRoute(routeDef []string, cidr netip.Prefix) (bool, error) {
args := append([]string{"ip", dashFam(cidr.Addr()), "route", "show"}, routeDef...)
if r.ipRuleAvailable {
args = append(args, "table", tailscaleRouteTable.ipCmdArg())
@@ -1378,8 +1378,8 @@ func (r *linuxRouter) delSNATRule() error {
// old and new match. Returns a map reflecting the actual new state
// (which may be somewhere in between old and new if some commands
// failed), and any error encountered while reconfiguring.
func cidrDiff(kind string, old map[netaddr.IPPrefix]bool, new []netaddr.IPPrefix, add, del func(netaddr.IPPrefix) error, logf logger.Logf) (map[netaddr.IPPrefix]bool, error) {
newMap := make(map[netaddr.IPPrefix]bool, len(new))
func cidrDiff(kind string, old map[netip.Prefix]bool, new []netip.Prefix, add, del func(netip.Prefix) error, logf logger.Logf) (map[netip.Prefix]bool, error) {
newMap := make(map[netip.Prefix]bool, len(new))
for _, cidr := range new {
newMap[cidr] = true
}
@@ -1387,7 +1387,7 @@ func cidrDiff(kind string, old map[netaddr.IPPrefix]bool, new []netaddr.IPPrefix
// ret starts out as a copy of old, and updates as we
// add/delete. That way we can always return it and have it be the
// true state of what we've done so far.
ret := make(map[netaddr.IPPrefix]bool, len(old))
ret := make(map[netip.Prefix]bool, len(old))
for cidr := range old {
ret[cidr] = true
}
@@ -1442,7 +1442,7 @@ func tsChain(chain string) string {
// normalizeCIDR returns cidr as an ip/mask string, with the host bits
// of the IP address zeroed out.
func normalizeCIDR(cidr netaddr.IPPrefix) string {
func normalizeCIDR(cidr netip.Prefix) string {
return cidr.Masked().String()
}
@@ -1548,7 +1548,7 @@ func checkIPRuleSupportsV6(logf logger.Logf) error {
return netlink.RuleAdd(rule)
}
func nlAddrOfPrefix(p netaddr.IPPrefix) *netlink.Addr {
func nlAddrOfPrefix(p netip.Prefix) *netlink.Addr {
return &netlink.Addr{
IPNet: netipx.PrefixIPNet(p),
}
+9 -9
View File
@@ -8,11 +8,11 @@ import (
"errors"
"fmt"
"log"
"net/netip"
"os/exec"
"go4.org/netipx"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/net/netaddr"
"tailscale.com/types/logger"
"tailscale.com/wgengine/monitor"
)
@@ -25,9 +25,9 @@ type openbsdRouter struct {
logf logger.Logf
linkMon *monitor.Mon
tunname string
local4 netaddr.IPPrefix
local6 netaddr.IPPrefix
routes map[netaddr.IPPrefix]struct{}
local4 netip.Prefix
local6 netip.Prefix
routes map[netip.Prefix]struct{}
}
func newUserspaceRouter(logf logger.Logf, tundev tun.Device, linkMon *monitor.Mon) (Router, error) {
@@ -59,7 +59,7 @@ func (r *openbsdRouter) Up() error {
return nil
}
func inet(p netaddr.IPPrefix) string {
func inet(p netip.Prefix) string {
if p.Addr().Is6() {
return "inet6"
}
@@ -77,8 +77,8 @@ func (r *openbsdRouter) Set(cfg *Config) error {
}
numIPv4 := 0
numIPv6 := 0
localAddr4 := netaddr.IPPrefix{}
localAddr6 := netaddr.IPPrefix{}
localAddr4 := netip.Prefix{}
localAddr6 := netip.Prefix{}
for _, addr := range cfg.LocalAddrs {
if addr.Addr().Is4() {
numIPv4++
@@ -145,7 +145,7 @@ func (r *openbsdRouter) Set(cfg *Config) error {
// in https://github.com/tailscale/tailscale/issues/1307 we made
// FreeBSD use a /48 for IPv6 addresses, which is nice because we
// don't need to additionally add routing entries. Do that here too.
localAddr6 = netaddr.IPPrefixFrom(localAddr6.Addr(), 48)
localAddr6 = netip.PrefixFrom(localAddr6.Addr(), 48)
}
if localAddr6 != r.local6 {
@@ -174,7 +174,7 @@ func (r *openbsdRouter) Set(cfg *Config) error {
}
}
newRoutes := make(map[netaddr.IPPrefix]struct{})
newRoutes := make(map[netip.Prefix]struct{})
for _, route := range cfg.Routes {
newRoutes[route] = struct{}{}
}
+3 -4
View File
@@ -9,12 +9,11 @@ import (
"reflect"
"testing"
"tailscale.com/net/netaddr"
"tailscale.com/types/preftype"
)
func mustCIDRs(ss ...string) []netaddr.IPPrefix {
var ret []netaddr.IPPrefix
func mustCIDRs(ss ...string) []netip.Prefix {
var ret []netip.Prefix
for _, s := range ss {
ret = append(ret, netip.MustParsePrefix(s))
}
@@ -36,7 +35,7 @@ func TestConfigEqual(t *testing.T) {
configFields, testedFields)
}
nets := func(strs ...string) (ns []netaddr.IPPrefix) {
nets := func(strs ...string) (ns []netip.Prefix) {
for _, s := range strs {
n, err := netip.ParsePrefix(s)
if err != nil {
+9 -9
View File
@@ -10,12 +10,12 @@ package router
import (
"fmt"
"log"
"net/netip"
"os/exec"
"runtime"
"go4.org/netipx"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/net/netaddr"
"tailscale.com/net/tsaddr"
"tailscale.com/types/logger"
"tailscale.com/version"
@@ -26,8 +26,8 @@ type userspaceBSDRouter struct {
logf logger.Logf
linkMon *monitor.Mon
tunname string
local []netaddr.IPPrefix
routes map[netaddr.IPPrefix]struct{}
local []netip.Prefix
routes map[netip.Prefix]struct{}
}
func newUserspaceBSDRouter(logf logger.Logf, tundev tun.Device, linkMon *monitor.Mon) (Router, error) {
@@ -43,7 +43,7 @@ func newUserspaceBSDRouter(logf logger.Logf, tundev tun.Device, linkMon *monitor
}, nil
}
func (r *userspaceBSDRouter) addrsToRemove(newLocalAddrs []netaddr.IPPrefix) (remove []netaddr.IPPrefix) {
func (r *userspaceBSDRouter) addrsToRemove(newLocalAddrs []netip.Prefix) (remove []netip.Prefix) {
for _, cur := range r.local {
found := false
for _, v := range newLocalAddrs {
@@ -59,7 +59,7 @@ func (r *userspaceBSDRouter) addrsToRemove(newLocalAddrs []netaddr.IPPrefix) (re
return
}
func (r *userspaceBSDRouter) addrsToAdd(newLocalAddrs []netaddr.IPPrefix) (add []netaddr.IPPrefix) {
func (r *userspaceBSDRouter) addrsToAdd(newLocalAddrs []netip.Prefix) (add []netip.Prefix) {
for _, cur := range newLocalAddrs {
found := false
for _, v := range r.local {
@@ -91,7 +91,7 @@ func (r *userspaceBSDRouter) Up() error {
return nil
}
func inet(p netaddr.IPPrefix) string {
func inet(p netip.Prefix) string {
if p.Addr().Is6() {
return "inet6"
}
@@ -126,7 +126,7 @@ func (r *userspaceBSDRouter) Set(cfg *Config) (reterr error) {
// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=218508
// Instead add our whole /48, which works because we use a /48 route.
// Full history: https://github.com/tailscale/tailscale/issues/1307
tmp := netaddr.IPPrefixFrom(addr.Addr(), 48)
tmp := netip.PrefixFrom(addr.Addr(), 48)
arg = []string{"ifconfig", r.tunname, inet(tmp), tmp.String()}
} else {
arg = []string{"ifconfig", r.tunname, inet(addr), addr.String(), addr.Addr().String()}
@@ -138,7 +138,7 @@ func (r *userspaceBSDRouter) Set(cfg *Config) (reterr error) {
}
}
newRoutes := make(map[netaddr.IPPrefix]struct{})
newRoutes := make(map[netip.Prefix]struct{})
for _, route := range cfg.Routes {
if runtime.GOOS != "darwin" && route == tsaddr.TailscaleULARange() {
// Because we added the interface address as a /48 above,
@@ -187,7 +187,7 @@ func (r *userspaceBSDRouter) Set(cfg *Config) (reterr error) {
// Store the interface and routes so we know what to change on an update.
if errq == nil {
r.local = append([]netaddr.IPPrefix{}, cfg.LocalAddrs...)
r.local = append([]netip.Prefix{}, cfg.LocalAddrs...)
}
r.routes = newRoutes
+7 -7
View File
@@ -10,6 +10,7 @@ import (
"encoding/json"
"fmt"
"io"
"net/netip"
"os"
"os/exec"
"strings"
@@ -22,7 +23,6 @@ import (
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
"tailscale.com/logtail/backoff"
"tailscale.com/net/dns"
"tailscale.com/net/netaddr"
"tailscale.com/types/logger"
"tailscale.com/wgengine/monitor"
)
@@ -93,7 +93,7 @@ func (r *winRouter) Set(cfg *Config) error {
return nil
}
func hasDefaultRoute(routes []netaddr.IPPrefix) bool {
func hasDefaultRoute(routes []netip.Prefix) bool {
for _, route := range routes {
if route.Bits() == 0 {
return true
@@ -132,8 +132,8 @@ type firewallTweaker struct {
wantLocal []string // next value we want, or "" to delete the firewall rule
lastLocal []string // last set value, if known
localRoutes []netaddr.IPPrefix
lastLocalRoutes []netaddr.IPPrefix
localRoutes []netip.Prefix
lastLocalRoutes []netip.Prefix
wantKillswitch bool
lastKillswitch bool
@@ -156,7 +156,7 @@ func (ft *firewallTweaker) clear() { ft.set(nil, nil, nil) }
// Empty slices remove firewall rules.
//
// set takes ownership of cidrs, but not routes.
func (ft *firewallTweaker) set(cidrs []string, routes, localRoutes []netaddr.IPPrefix) {
func (ft *firewallTweaker) set(cidrs []string, routes, localRoutes []netip.Prefix) {
ft.mu.Lock()
defer ft.mu.Unlock()
@@ -236,7 +236,7 @@ func (ft *firewallTweaker) doAsyncSet() {
// process to dial out as it pleases.
//
// Must only be invoked from doAsyncSet.
func (ft *firewallTweaker) doSet(local []string, killswitch bool, clear bool, procRule bool, allowedRoutes []netaddr.IPPrefix) error {
func (ft *firewallTweaker) doSet(local []string, killswitch bool, clear bool, procRule bool, allowedRoutes []netip.Prefix) error {
if clear {
ft.logf("clearing Tailscale-In firewall rules...")
// We ignore the error here, because netsh returns an error for
@@ -343,7 +343,7 @@ func (ft *firewallTweaker) doSet(local []string, killswitch bool, clear bool, pr
return ft.fwProcEncoder.Encode(allowedRoutes)
}
func routesEqual(a, b []netaddr.IPPrefix) bool {
func routesEqual(a, b []netip.Prefix) bool {
if len(a) != len(b) {
return false
}
+31 -32
View File
@@ -31,7 +31,6 @@ import (
"tailscale.com/net/dns/resolver"
"tailscale.com/net/flowtrack"
"tailscale.com/net/interfaces"
"tailscale.com/net/netaddr"
"tailscale.com/net/packet"
"tailscale.com/net/tsaddr"
"tailscale.com/net/tsdial"
@@ -108,11 +107,11 @@ type userspaceEngine struct {
// isLocalAddr reports the whether an IP is assigned to the local
// tunnel interface. It's used to reflect local packets
// incorrectly sent to us.
isLocalAddr atomic.Value // of func(netaddr.IP)bool
isLocalAddr atomic.Value // of func(netip.Addr)bool
// isDNSIPOverTailscale reports the whether a DNS resolver's IP
// is being routed over Tailscale.
isDNSIPOverTailscale atomic.Value // of func(netaddr.IP)bool
isDNSIPOverTailscale atomic.Value // of func(netip.Addr)bool
wgLock sync.Mutex // serializes all wgdev operations; see lock order comment below
lastCfgFull wgcfg.Config
@@ -124,8 +123,8 @@ type userspaceEngine struct {
lastIsSubnetRouter bool // was the node a primary subnet router in the last run.
recvActivityAt map[key.NodePublic]mono.Time
trimmedNodes map[key.NodePublic]bool // set of node keys of peers currently excluded from wireguard config
sentActivityAt map[netaddr.IP]*mono.Time // value is accessed atomically
destIPActivityFuncs map[netaddr.IP]func()
sentActivityAt map[netip.Addr]*mono.Time // value is accessed atomically
destIPActivityFuncs map[netip.Addr]func()
statusBufioReader *bufio.Reader // reusable for UAPI
lastStatusPollTime mono.Time // last time we polled the engine status
@@ -137,7 +136,7 @@ type userspaceEngine struct {
endpoints []tailcfg.Endpoint
pendOpen map[flowtrack.Tuple]*pendingOpenFlow // see pendopen.go
networkMapCallbacks map[*someHandle]NetworkMapCallback
tsIPByIPPort map[netaddr.IPPort]netaddr.IP // allows registration of IP:ports as belonging to a certain Tailscale IP for whois lookups
tsIPByIPPort map[netip.AddrPort]netip.Addr // allows registration of IP:ports as belonging to a certain Tailscale IP for whois lookups
// pongCallback is the map of response handlers waiting for disco or TSMP
// pong callbacks. The map key is a random slice of bytes.
@@ -498,7 +497,7 @@ func (e *userspaceEngine) handleLocalPackets(p *packet.Parsed, t *tstun.Wrapper)
}
if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
isLocalAddr, ok := e.isLocalAddr.Load().(func(netaddr.IP) bool)
isLocalAddr, ok := e.isLocalAddr.Load().(func(netip.Addr) bool)
if !ok {
e.logf("[unexpected] e.isLocalAddr was nil, can't check for loopback packet")
} else if isLocalAddr(p.Dst.Addr()) {
@@ -629,7 +628,7 @@ func (e *userspaceEngine) noteRecvActivity(nk key.NodePublic) {
// has had a packet sent to or received from it since t.
//
// e.wgLock must be held.
func (e *userspaceEngine) isActiveSinceLocked(nk key.NodePublic, ip netaddr.IP, t mono.Time) bool {
func (e *userspaceEngine) isActiveSinceLocked(nk key.NodePublic, ip netip.Addr, t mono.Time) bool {
if e.recvActivityAt[nk].After(t) {
return true
}
@@ -673,7 +672,7 @@ func (e *userspaceEngine) maybeReconfigWireguardLocked(discoChanged map[key.Node
// to install tracking hooks for to watch their send/receive
// activity.
trackNodes := make([]key.NodePublic, 0, len(full.Peers))
trackIPs := make([]netaddr.IP, 0, len(full.Peers))
trackIPs := make([]netip.Addr, 0, len(full.Peers))
trimmedNodes := map[key.NodePublic]bool{} // TODO: don't re-alloc this map each time
@@ -747,7 +746,7 @@ func (e *userspaceEngine) maybeReconfigWireguardLocked(discoChanged map[key.Node
// as given to wireguard-go.
//
// e.wgLock must be held.
func (e *userspaceEngine) updateActivityMapsLocked(trackNodes []key.NodePublic, trackIPs []netaddr.IP) {
func (e *userspaceEngine) updateActivityMapsLocked(trackNodes []key.NodePublic, trackIPs []netip.Addr) {
// Generate the new map of which nodekeys we want to track
// receive times for.
mr := map[key.NodePublic]mono.Time{} // TODO: only recreate this if set of keys changed
@@ -762,9 +761,9 @@ func (e *userspaceEngine) updateActivityMapsLocked(trackNodes []key.NodePublic,
e.recvActivityAt = mr
oldTime := e.sentActivityAt
e.sentActivityAt = make(map[netaddr.IP]*mono.Time, len(oldTime))
e.sentActivityAt = make(map[netip.Addr]*mono.Time, len(oldTime))
oldFunc := e.destIPActivityFuncs
e.destIPActivityFuncs = make(map[netaddr.IP]func(), len(oldFunc))
e.destIPActivityFuncs = make(map[netip.Addr]func(), len(oldFunc))
updateFn := func(timePtr *mono.Time) func() {
return func() {
@@ -810,7 +809,7 @@ func (e *userspaceEngine) updateActivityMapsLocked(trackNodes []key.NodePublic,
// hasOverlap checks if there is a IPPrefix which is common amongst the two
// provided slices.
func hasOverlap(aips, rips []netaddr.IPPrefix) bool {
func hasOverlap(aips, rips []netip.Prefix) bool {
for _, aip := range aips {
for _, rip := range rips {
if aip == rip {
@@ -1290,7 +1289,7 @@ func (e *userspaceEngine) UpdateStatus(sb *ipnstate.StatusBuilder) {
e.magicConn.UpdateStatus(sb)
}
func (e *userspaceEngine) Ping(ip netaddr.IP, pingType tailcfg.PingType, cb func(*ipnstate.PingResult)) {
func (e *userspaceEngine) Ping(ip netip.Addr, pingType tailcfg.PingType, cb func(*ipnstate.PingResult)) {
res := &ipnstate.PingResult{IP: ip.String()}
pip, ok := e.PeerForIP(ip)
if !ok {
@@ -1318,11 +1317,11 @@ func (e *userspaceEngine) Ping(ip netaddr.IP, pingType tailcfg.PingType, cb func
}
}
func (e *userspaceEngine) mySelfIPMatchingFamily(dst netaddr.IP) (src netaddr.IP, err error) {
func (e *userspaceEngine) mySelfIPMatchingFamily(dst netip.Addr) (src netip.Addr, err error) {
e.mu.Lock()
defer e.mu.Unlock()
if e.netMap == nil {
return netaddr.IP{}, errors.New("no netmap")
return netip.Addr{}, errors.New("no netmap")
}
for _, a := range e.netMap.Addresses {
if a.IsSingleIP() && a.Addr().BitLen() == dst.BitLen() {
@@ -1330,12 +1329,12 @@ func (e *userspaceEngine) mySelfIPMatchingFamily(dst netaddr.IP) (src netaddr.IP
}
}
if len(e.netMap.Addresses) == 0 {
return netaddr.IP{}, errors.New("no self address in netmap")
return netip.Addr{}, errors.New("no self address in netmap")
}
return netaddr.IP{}, errors.New("no self address in netmap matching address family")
return netip.Addr{}, errors.New("no self address in netmap matching address family")
}
func (e *userspaceEngine) sendICMPEchoRequest(destIP netaddr.IP, peer *tailcfg.Node, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
func (e *userspaceEngine) sendICMPEchoRequest(destIP netip.Addr, peer *tailcfg.Node, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
srcIP, err := e.mySelfIPMatchingFamily(destIP)
if err != nil {
res.Err = err.Error()
@@ -1384,7 +1383,7 @@ func (e *userspaceEngine) sendICMPEchoRequest(destIP netaddr.IP, peer *tailcfg.N
e.tundev.InjectOutbound(icmpPing)
}
func (e *userspaceEngine) sendTSMPPing(ip netaddr.IP, peer *tailcfg.Node, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
func (e *userspaceEngine) sendTSMPPing(ip netip.Addr, peer *tailcfg.Node, res *ipnstate.PingResult, cb func(*ipnstate.PingResult)) {
srcIP, err := e.mySelfIPMatchingFamily(ip)
if err != nil {
res.Err = err.Error()
@@ -1454,16 +1453,16 @@ func (e *userspaceEngine) setICMPEchoResponseCallback(idSeq uint32, cb func()) {
}
}
func (e *userspaceEngine) RegisterIPPortIdentity(ipport netaddr.IPPort, tsIP netaddr.IP) {
func (e *userspaceEngine) RegisterIPPortIdentity(ipport netip.AddrPort, tsIP netip.Addr) {
e.mu.Lock()
defer e.mu.Unlock()
if e.tsIPByIPPort == nil {
e.tsIPByIPPort = make(map[netaddr.IPPort]netaddr.IP)
e.tsIPByIPPort = make(map[netip.AddrPort]netip.Addr)
}
e.tsIPByIPPort[ipport] = tsIP
}
func (e *userspaceEngine) UnregisterIPPortIdentity(ipport netaddr.IPPort) {
func (e *userspaceEngine) UnregisterIPPortIdentity(ipport netip.AddrPort) {
e.mu.Lock()
defer e.mu.Unlock()
if e.tsIPByIPPort == nil {
@@ -1480,7 +1479,7 @@ var whoIsSleeps = [...]time.Duration{
100 * time.Millisecond,
}
func (e *userspaceEngine) WhoIsIPPort(ipport netaddr.IPPort) (tsIP netaddr.IP, ok bool) {
func (e *userspaceEngine) WhoIsIPPort(ipport netip.AddrPort) (tsIP netip.Addr, ok bool) {
// We currently have a registration race,
// https://github.com/tailscale/tailscale/issues/1616,
// so loop a few times for now waiting for the registration
@@ -1507,7 +1506,7 @@ func (e *userspaceEngine) WhoIsIPPort(ipport netaddr.IPPort) (tsIP netaddr.IP, o
//
// peerForIP acquires both e.mu and e.wgLock, but neither at the same
// time.
func (e *userspaceEngine) PeerForIP(ip netaddr.IP) (ret PeerForIP, ok bool) {
func (e *userspaceEngine) PeerForIP(ip netip.Addr) (ret PeerForIP, ok bool) {
e.mu.Lock()
nm := e.netMap
e.mu.Unlock()
@@ -1534,7 +1533,7 @@ func (e *userspaceEngine) PeerForIP(ip netaddr.IP) (ret PeerForIP, ok bool) {
defer e.wgLock.Unlock()
// TODO(bradfitz): this is O(n peers). Add ART to netaddr?
var best netaddr.IPPrefix
var best netip.Prefix
var bestKey key.NodePublic
for _, p := range e.lastCfgFull.Peers {
for _, cidr := range p.AllowedIPs {
@@ -1572,7 +1571,7 @@ func (p closeOnErrorPool) closeAllIfError(errp *error) {
}
// ipInPrefixes reports whether ip is in any of pp.
func ipInPrefixes(ip netaddr.IP, pp []netaddr.IPPrefix) bool {
func ipInPrefixes(ip netip.Addr, pp []netip.Prefix) bool {
for _, p := range pp {
if p.Contains(ip) {
return true
@@ -1584,8 +1583,8 @@ func ipInPrefixes(ip netaddr.IP, pp []netaddr.IPPrefix) bool {
// dnsIPsOverTailscale returns the IPPrefixes of DNS resolver IPs that are
// routed over Tailscale. The returned value does not contain duplicates is
// not necessarily sorted.
func dnsIPsOverTailscale(dnsCfg *dns.Config, routerCfg *router.Config) (ret []netaddr.IPPrefix) {
m := map[netaddr.IP]bool{}
func dnsIPsOverTailscale(dnsCfg *dns.Config, routerCfg *router.Config) (ret []netip.Prefix) {
m := map[netip.Addr]bool{}
add := func(resolvers []*dnstype.Resolver) {
for _, r := range resolvers {
@@ -1608,7 +1607,7 @@ func dnsIPsOverTailscale(dnsCfg *dns.Config, routerCfg *router.Config) (ret []ne
add(resolvers)
}
ret = make([]netaddr.IPPrefix, 0, len(m))
ret = make([]netip.Prefix, 0, len(m))
for ip := range m {
ret = append(ret, netip.PrefixFrom(ip, ip.BitLen()))
}
@@ -1622,8 +1621,8 @@ type fwdDNSLinkSelector struct {
tunName string
}
func (ls fwdDNSLinkSelector) PickLink(ip netaddr.IP) (linkName string) {
if ls.ue.isDNSIPOverTailscale.Load().(func(netaddr.IP) bool)(ip) {
func (ls fwdDNSLinkSelector) PickLink(ip netip.Addr) (linkName string) {
if ls.ue.isDNSIPOverTailscale.Load().(func(netip.Addr) bool)(ip) {
return ls.tunName
}
return ""
+8 -8
View File
@@ -113,8 +113,8 @@ func TestUserspaceEngineReconfig(t *testing.T) {
Peers: []wgcfg.Peer{
{
PublicKey: nk,
AllowedIPs: []netaddr.IPPrefix{
netaddr.IPPrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
AllowedIPs: []netip.Prefix{
netip.PrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
},
},
},
@@ -173,8 +173,8 @@ func TestUserspaceEnginePortReconfig(t *testing.T) {
Peers: []wgcfg.Peer{
{
PublicKey: nodeKey,
AllowedIPs: []netaddr.IPPrefix{
netaddr.IPPrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
AllowedIPs: []netip.Prefix{
netip.PrefixFrom(netaddr.IPv4(100, 100, 99, 1), 32),
},
},
},
@@ -231,7 +231,7 @@ func BenchmarkGenLocalAddrFunc(b *testing.B) {
b.Run("map1", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
m := map[netaddr.IP]bool{
m := map[netip.Addr]bool{
la1: true,
}
for i := 0; i < b.N; i++ {
@@ -242,7 +242,7 @@ func BenchmarkGenLocalAddrFunc(b *testing.B) {
b.Run("map2", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
m := map[netaddr.IP]bool{
m := map[netip.Addr]bool{
la1: true,
la2: true,
}
@@ -254,7 +254,7 @@ func BenchmarkGenLocalAddrFunc(b *testing.B) {
b.Run("or1", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
f := func(t netaddr.IP) bool {
f := func(t netip.Addr) bool {
return t == la1
}
for i := 0; i < b.N; i++ {
@@ -265,7 +265,7 @@ func BenchmarkGenLocalAddrFunc(b *testing.B) {
b.Run("or2", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
f := func(t netaddr.IP) bool {
f := func(t netip.Addr) bool {
return t == la1 || t == la2
}
for i := 0; i < b.N; i++ {
+6 -6
View File
@@ -9,6 +9,7 @@ package wgengine
import (
"log"
"net/netip"
"runtime/pprof"
"strings"
"time"
@@ -17,7 +18,6 @@ import (
"tailscale.com/ipn/ipnstate"
"tailscale.com/net/dns"
"tailscale.com/net/dns/resolver"
"tailscale.com/net/netaddr"
"tailscale.com/net/tstun"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
@@ -120,16 +120,16 @@ func (e *watchdogEngine) DiscoPublicKey() (k key.DiscoPublic) {
e.watchdog("DiscoPublicKey", func() { k = e.wrap.DiscoPublicKey() })
return k
}
func (e *watchdogEngine) Ping(ip netaddr.IP, pingType tailcfg.PingType, cb func(*ipnstate.PingResult)) {
func (e *watchdogEngine) Ping(ip netip.Addr, pingType tailcfg.PingType, cb func(*ipnstate.PingResult)) {
e.watchdog("Ping", func() { e.wrap.Ping(ip, pingType, cb) })
}
func (e *watchdogEngine) RegisterIPPortIdentity(ipp netaddr.IPPort, tsIP netaddr.IP) {
func (e *watchdogEngine) RegisterIPPortIdentity(ipp netip.AddrPort, tsIP netip.Addr) {
e.watchdog("RegisterIPPortIdentity", func() { e.wrap.RegisterIPPortIdentity(ipp, tsIP) })
}
func (e *watchdogEngine) UnregisterIPPortIdentity(ipp netaddr.IPPort) {
func (e *watchdogEngine) UnregisterIPPortIdentity(ipp netip.AddrPort) {
e.watchdog("UnregisterIPPortIdentity", func() { e.wrap.UnregisterIPPortIdentity(ipp) })
}
func (e *watchdogEngine) WhoIsIPPort(ipp netaddr.IPPort) (tsIP netaddr.IP, ok bool) {
func (e *watchdogEngine) WhoIsIPPort(ipp netip.AddrPort) (tsIP netip.Addr, ok bool) {
e.watchdog("UnregisterIPPortIdentity", func() { tsIP, ok = e.wrap.WhoIsIPPort(ipp) })
return tsIP, ok
}
@@ -148,7 +148,7 @@ func (e *watchdogEngine) GetResolver() (r *resolver.Resolver, ok bool) {
}
return nil, false
}
func (e *watchdogEngine) PeerForIP(ip netaddr.IP) (ret PeerForIP, ok bool) {
func (e *watchdogEngine) PeerForIP(ip netip.Addr) (ret PeerForIP, ok bool) {
e.watchdog("PeerForIP", func() { ret, ok = e.wrap.PeerForIP(ip) })
return ret, ok
}
+5 -4
View File
@@ -6,7 +6,8 @@
package wgcfg
import (
"tailscale.com/net/netaddr"
"net/netip"
"tailscale.com/types/key"
)
@@ -17,16 +18,16 @@ import (
type Config struct {
Name string
PrivateKey key.NodePrivate
Addresses []netaddr.IPPrefix
Addresses []netip.Prefix
MTU uint16
DNS []netaddr.IP
DNS []netip.Addr
Peers []Peer
}
type Peer struct {
PublicKey key.NodePublic
DiscoKey key.DiscoPublic // present only so we can handle restarts within wgengine, not passed to WireGuard
AllowedIPs []netaddr.IPPrefix
AllowedIPs []netip.Prefix
PersistentKeepalive uint16
// wireguard-go's endpoint for this peer. It should always equal Peer.PublicKey.
// We represent it explicitly so that we can detect if they diverge and recover.
+3 -4
View File
@@ -19,7 +19,6 @@ import (
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun"
"tailscale.com/net/netaddr"
"tailscale.com/types/key"
)
@@ -42,7 +41,7 @@ func TestDeviceConfig(t *testing.T) {
PrivateKey: pk1,
Peers: []Peer{{
PublicKey: k2,
AllowedIPs: []netaddr.IPPrefix{ip2},
AllowedIPs: []netip.Prefix{ip2},
}},
}
@@ -50,7 +49,7 @@ func TestDeviceConfig(t *testing.T) {
PrivateKey: pk2,
Peers: []Peer{{
PublicKey: k1,
AllowedIPs: []netaddr.IPPrefix{ip1},
AllowedIPs: []netip.Prefix{ip1},
PersistentKeepalive: 5,
}},
}
@@ -143,7 +142,7 @@ func TestDeviceConfig(t *testing.T) {
t.Run("device1 add new peer", func(t *testing.T) {
cfg1.Peers = append(cfg1.Peers, Peer{
PublicKey: k3,
AllowedIPs: []netaddr.IPPrefix{ip3},
AllowedIPs: []netip.Prefix{ip3},
})
sort.Slice(cfg1.Peers, func(i, j int) bool {
return cfg1.Peers[i].PublicKey.Less(cfg1.Peers[j].PublicKey)
+2 -2
View File
@@ -8,9 +8,9 @@ package nmcfg
import (
"bytes"
"fmt"
"net/netip"
"strings"
"tailscale.com/net/netaddr"
"tailscale.com/net/tsaddr"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
@@ -34,7 +34,7 @@ func nodeDebugName(n *tailcfg.Node) string {
// cidrIsSubnet reports whether cidr is a non-default-route subnet
// exported by node that is not one of its own self addresses.
func cidrIsSubnet(node *tailcfg.Node, cidr netaddr.IPPrefix) bool {
func cidrIsSubnet(node *tailcfg.Node, cidr netip.Prefix) bool {
if cidr.Bits() == 0 {
return false
}
+2 -2
View File
@@ -9,11 +9,11 @@ import (
"fmt"
"io"
"net"
"net/netip"
"strconv"
"strings"
"go4.org/mem"
"tailscale.com/net/netaddr"
"tailscale.com/types/key"
)
@@ -163,7 +163,7 @@ func (cfg *Config) handlePeerLine(peer *Peer, k, value mem.RO, valueBytes []byte
}
peer.PersistentKeepalive = uint16(n)
case k.EqualString("allowed_ip"):
ipp := netaddr.IPPrefix{}
ipp := netip.Prefix{}
err := ipp.UnmarshalText(valueBytes)
if err != nil {
return err
+1 -2
View File
@@ -13,7 +13,6 @@ import (
"runtime"
"testing"
"tailscale.com/net/netaddr"
"tailscale.com/types/key"
)
@@ -72,7 +71,7 @@ func BenchmarkFromUAPI(b *testing.B) {
peer := Peer{
PublicKey: k1,
AllowedIPs: []netaddr.IPPrefix{ip1},
AllowedIPs: []netip.Prefix{ip1},
}
cfg1 := &Config{
PrivateKey: pk1,
+3 -3
View File
@@ -7,9 +7,9 @@ package wgcfg
import (
"fmt"
"io"
"net/netip"
"strconv"
"tailscale.com/net/netaddr"
"tailscale.com/types/key"
"tailscale.com/types/logger"
)
@@ -101,7 +101,7 @@ func (cfg *Config) ToUAPI(logf logger.Logf, w io.Writer, prev *Config) error {
return stickyErr
}
func cidrsEqual(x, y []netaddr.IPPrefix) bool {
func cidrsEqual(x, y []netip.Prefix) bool {
// TODO: re-implement using netaddr.IPSet.Equal.
if len(x) != len(y) {
return false
@@ -119,7 +119,7 @@ func cidrsEqual(x, y []netaddr.IPPrefix) bool {
}
// Otherwise, see if they're the same, but out of order.
m := make(map[netaddr.IPPrefix]bool)
m := make(map[netip.Prefix]bool)
for _, v := range x {
m[v] = true
}
+7 -7
View File
@@ -6,11 +6,11 @@ package wgengine
import (
"errors"
"net/netip"
"time"
"tailscale.com/ipn/ipnstate"
"tailscale.com/net/dns"
"tailscale.com/net/netaddr"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
"tailscale.com/types/netmap"
@@ -62,7 +62,7 @@ type PeerForIP struct {
// Route is the route that matched the IP provided
// to Engine.PeerForIP.
Route netaddr.IPPrefix
Route netip.Prefix
}
// Engine is the Tailscale WireGuard engine interface.
@@ -80,7 +80,7 @@ type Engine interface {
// PeerForIP returns the node to which the provided IP routes,
// if any. If none is found, (nil, nil) is returned.
PeerForIP(netaddr.IP) (_ PeerForIP, ok bool)
PeerForIP(netip.Addr) (_ PeerForIP, ok bool)
// GetFilter returns the current packet filter, if any.
GetFilter() *filter.Filter
@@ -156,20 +156,20 @@ type Engine interface {
// Ping is a request to start a ping with the peer handling the given IP and
// then call cb with its ping latency & method.
Ping(ip netaddr.IP, pingType tailcfg.PingType, cb func(*ipnstate.PingResult))
Ping(ip netip.Addr, pingType tailcfg.PingType, cb func(*ipnstate.PingResult))
// RegisterIPPortIdentity registers a given node (identified by its
// Tailscale IP) as temporarily having the given IP:port for whois lookups.
// The IP:port is generally a localhost IP and an ephemeral port, used
// while proxying connections to localhost when tailscaled is running
// in netstack mode.
RegisterIPPortIdentity(netaddr.IPPort, netaddr.IP)
RegisterIPPortIdentity(netip.AddrPort, netip.Addr)
// UnregisterIPPortIdentity removes a temporary IP:port registration
// made previously by RegisterIPPortIdentity.
UnregisterIPPortIdentity(netaddr.IPPort)
UnregisterIPPortIdentity(netip.AddrPort)
// WhoIsIPPort looks up an IP:port in the temporary registrations,
// and returns a matching Tailscale IP, if it exists.
WhoIsIPPort(netaddr.IPPort) (netaddr.IP, bool)
WhoIsIPPort(netip.AddrPort) (netip.Addr, bool)
}