mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-03 23:22:23 -08:00
net/memnet: add UDP support
Add Network.ListenPacket, making Network a nettype.PacketListener with in-memory UDP sockets. Packets go by exact destination address and port. Sending never blocks; packets to an address without a socket, or to a full receive queue, are dropped. An unspecified or empty listen IP binds the family's loopback address, and port zero picks the next ephemeral port in rotation, so a just-closed socket's port isn't handed right back out, as with an OS. Reads block only on channels and timers, including for read deadlines, so the sockets work in testing/synctest bubbles. That's for running magicsock (via its TestOnlyPacketListener) and STUN (via stuntest.ServeWithPacketListener) on an in-memory network with fake time. Updates #22831 Change-Id: Id7043412ca036b075927c6352c663d73f2b8657f Signed-off-by: Brad Fitzpatrick <[email protected]>
This commit is contained in:
1 parent
24feea8da5
commit
c277dd1791
3 files changed
+409
-4
No files matched your search
@@ -22,12 +22,15 @@ var _ netx.Network = (*Network)(nil)
|
||||
// Network implements [Network] using an in-memory network, usually
|
||||
// used for testing.
|
||||
//
|
||||
// As of 2025-04-08, it only supports TCP.
|
||||
// It supports TCP (Listen and Dial) and UDP (ListenPacket).
|
||||
//
|
||||
// Its zero value is a valid [netx.Network] implementation.
|
||||
type Network struct {
|
||||
mu syncs.Mutex
|
||||
lns map[string]*Listener // address -> listener
|
||||
mu syncs.Mutex
|
||||
lns map[string]*Listener // address -> listener
|
||||
pconns map[netip.AddrPort]*packetConn // UDP sockets by local address
|
||||
|
||||
nextUDPPort int // next ephemeral UDP port to try, minus firstEphemeralPort
|
||||
}
|
||||
|
||||
func (m *Network) Listen(network, address string) (net.Listener, error) {
|
||||
@@ -48,7 +51,7 @@ func (m *Network) Listen(network, address string) (net.Listener, error) {
|
||||
port := ap.Port()
|
||||
for {
|
||||
if port == 0 {
|
||||
port = 33000
|
||||
port = firstEphemeralPort
|
||||
}
|
||||
key := net.JoinHostPort(ap.Addr().String(), fmt.Sprint(port))
|
||||
_, ok := m.lns[key]
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package memnet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"tailscale.com/types/nettype"
|
||||
)
|
||||
|
||||
var _ nettype.PacketListener = (*Network)(nil)
|
||||
|
||||
// udpQueueLen is how many packets a PacketConn from [Network.ListenPacket]
|
||||
// queues for reading before it drops new ones, like a full socket
|
||||
// receive buffer.
|
||||
const udpQueueLen = 1024
|
||||
|
||||
// firstEphemeralPort is the first port [Network.Listen] and
|
||||
// [Network.ListenPacket] try when asked for port 0.
|
||||
const firstEphemeralPort = 33000
|
||||
|
||||
// ListenPacket implements [nettype.PacketListener], returning an in-memory
|
||||
// UDP socket that exchanges packets with other sockets from the same
|
||||
// Network.
|
||||
//
|
||||
// The network must be "udp", "udp4" or "udp6". The address's port may be
|
||||
// zero to pick an unused one, which isn't one freed recently. An empty or unspecified IP binds to the
|
||||
// loopback address of the family: 127.0.0.1 for "udp" and "udp4", and
|
||||
// ::1 for "udp6". Packets are routed by exact destination address and
|
||||
// port; there is no wildcard binding.
|
||||
//
|
||||
// Like UDP, sending never blocks. A packet to an address with no socket,
|
||||
// or to a socket whose receive queue is full, is silently dropped.
|
||||
//
|
||||
// Reads block on channels and timers only, so the sockets work inside
|
||||
// [testing/synctest] bubbles.
|
||||
func (m *Network) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||
var loopback netip.Addr
|
||||
switch network {
|
||||
case "udp", "udp4":
|
||||
loopback = netip.AddrFrom4([4]byte{127, 0, 0, 1})
|
||||
case "udp6":
|
||||
loopback = netip.IPv6Loopback()
|
||||
default:
|
||||
return nil, fmt.Errorf("memNetwork: ListenPacket called with unsupported network %q", network)
|
||||
}
|
||||
host, portStr, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("memNetwork: ListenPacket called with invalid address %q: %w", address, err)
|
||||
}
|
||||
ip := loopback
|
||||
if host != "" {
|
||||
ip, err = netip.ParseAddr(host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("memNetwork: ListenPacket called with invalid address %q: %w", address, err)
|
||||
}
|
||||
// Packets are routed by unmapped address; see WriteToUDPAddrPort.
|
||||
ip = ip.Unmap()
|
||||
if ip.IsUnspecified() {
|
||||
ip = loopback
|
||||
}
|
||||
}
|
||||
ap, err := netip.ParseAddrPort(net.JoinHostPort(ip.String(), portStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("memNetwork: ListenPacket called with invalid address %q: %w", address, err)
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.pconns == nil {
|
||||
m.pconns = make(map[netip.AddrPort]*packetConn)
|
||||
}
|
||||
if ap.Port() == 0 {
|
||||
// Like an OS, hand out ephemeral ports in rotation rather than
|
||||
// reusing a just-freed one, so a packet for a closed socket
|
||||
// doesn't reach the next socket to bind.
|
||||
const numEphemeral = 0x10000 - firstEphemeralPort
|
||||
for i := 0; ; i++ {
|
||||
if i == numEphemeral {
|
||||
return nil, fmt.Errorf("memNetwork: no free UDP port on %v", ip)
|
||||
}
|
||||
port := uint16(firstEphemeralPort + m.nextUDPPort)
|
||||
m.nextUDPPort = (m.nextUDPPort + 1) % numEphemeral
|
||||
try := netip.AddrPortFrom(ip, port)
|
||||
if _, ok := m.pconns[try]; !ok {
|
||||
ap = try
|
||||
break
|
||||
}
|
||||
}
|
||||
} else if _, ok := m.pconns[ap]; ok {
|
||||
return nil, fmt.Errorf("memNetwork: ListenPacket called with duplicate address %q", address)
|
||||
}
|
||||
pc := &packetConn{
|
||||
net: m,
|
||||
local: ap,
|
||||
in: make(chan packet, udpQueueLen),
|
||||
closed: make(chan struct{}),
|
||||
dlChanged: make(chan struct{}),
|
||||
}
|
||||
m.pconns[ap] = pc
|
||||
return pc, nil
|
||||
}
|
||||
|
||||
// deliver queues a copy of b from src for the socket bound to dst, if any.
|
||||
func (m *Network) deliver(b []byte, src, dst netip.AddrPort) {
|
||||
m.mu.Lock()
|
||||
pc := m.pconns[dst]
|
||||
m.mu.Unlock()
|
||||
if pc == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case pc.in <- packet{src: src, b: bytes.Clone(b)}:
|
||||
default:
|
||||
// Queue full; drop it.
|
||||
}
|
||||
}
|
||||
|
||||
type packet struct {
|
||||
src netip.AddrPort
|
||||
b []byte
|
||||
}
|
||||
|
||||
// packetConn is the [net.PacketConn] returned by [Network.ListenPacket].
|
||||
// It also implements [nettype.PacketConn].
|
||||
type packetConn struct {
|
||||
net *Network
|
||||
local netip.AddrPort
|
||||
in chan packet
|
||||
|
||||
closeOnce sync.Once
|
||||
closed chan struct{} // closed by Close
|
||||
|
||||
mu sync.Mutex
|
||||
readDeadline time.Time
|
||||
dlChanged chan struct{} // closed and replaced when readDeadline changes
|
||||
}
|
||||
|
||||
var _ nettype.PacketConn = (*packetConn)(nil)
|
||||
|
||||
func (c *packetConn) LocalAddr() net.Addr { return net.UDPAddrFromAddrPort(c.local) }
|
||||
|
||||
func (c *packetConn) Close() error {
|
||||
c.closeOnce.Do(func() {
|
||||
c.net.mu.Lock()
|
||||
if c.net.pconns[c.local] == c {
|
||||
delete(c.net.pconns, c.local)
|
||||
}
|
||||
c.net.mu.Unlock()
|
||||
close(c.closed)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *packetConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||
n, src, err := c.ReadFromUDPAddrPort(b)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
return n, net.UDPAddrFromAddrPort(src), nil
|
||||
}
|
||||
|
||||
func (c *packetConn) ReadFromUDPAddrPort(b []byte) (int, netip.AddrPort, error) {
|
||||
for {
|
||||
c.mu.Lock()
|
||||
deadline, changed := c.readDeadline, c.dlChanged
|
||||
c.mu.Unlock()
|
||||
|
||||
select {
|
||||
case <-c.closed:
|
||||
return 0, netip.AddrPort{}, net.ErrClosed
|
||||
default:
|
||||
}
|
||||
|
||||
var timeout <-chan time.Time
|
||||
stopTimer := func() {}
|
||||
if !deadline.IsZero() {
|
||||
d := time.Until(deadline)
|
||||
if d <= 0 {
|
||||
return 0, netip.AddrPort{}, os.ErrDeadlineExceeded
|
||||
}
|
||||
timer := time.NewTimer(d)
|
||||
timeout, stopTimer = timer.C, func() { timer.Stop() }
|
||||
}
|
||||
select {
|
||||
case p := <-c.in:
|
||||
stopTimer()
|
||||
return copy(b, p.b), p.src, nil
|
||||
case <-c.closed:
|
||||
stopTimer()
|
||||
return 0, netip.AddrPort{}, net.ErrClosed
|
||||
case <-timeout:
|
||||
return 0, netip.AddrPort{}, os.ErrDeadlineExceeded
|
||||
case <-changed:
|
||||
// The deadline changed; recheck it.
|
||||
stopTimer()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *packetConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||
ua, ok := addr.(*net.UDPAddr)
|
||||
if !ok {
|
||||
return 0, &net.OpError{Op: "write", Net: "udp", Addr: addr, Err: net.InvalidAddrError("not a *net.UDPAddr")}
|
||||
}
|
||||
return c.WriteToUDPAddrPort(b, ua.AddrPort())
|
||||
}
|
||||
|
||||
func (c *packetConn) WriteToUDPAddrPort(b []byte, dst netip.AddrPort) (int, error) {
|
||||
select {
|
||||
case <-c.closed:
|
||||
return 0, net.ErrClosed
|
||||
default:
|
||||
}
|
||||
// Unmap so a v4-mapped v6 destination reaches a v4 socket, as a
|
||||
// dual-stack OS socket would send it.
|
||||
dst = netip.AddrPortFrom(dst.Addr().Unmap(), dst.Port())
|
||||
c.net.deliver(b, c.local, dst)
|
||||
return len(b), nil
|
||||
}
|
||||
|
||||
func (c *packetConn) SetDeadline(t time.Time) error {
|
||||
return c.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (c *packetConn) SetReadDeadline(t time.Time) error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.readDeadline = t
|
||||
close(c.dlChanged)
|
||||
c.dlChanged = make(chan struct{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetWriteDeadline is a no-op, as writes never block.
|
||||
func (c *packetConn) SetWriteDeadline(t time.Time) error { return nil }
|
||||
@@ -0,0 +1,158 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package memnet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestListenPacket(t *testing.T) {
|
||||
var nw Network
|
||||
ctx := context.Background()
|
||||
a, err := nw.ListenPacket(ctx, "udp4", ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a.Close()
|
||||
b, err := nw.ListenPacket(ctx, "udp4", "127.0.0.1:5000")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer b.Close()
|
||||
|
||||
if got, want := a.LocalAddr().String(), "127.0.0.1:33000"; got != want {
|
||||
t.Errorf("a.LocalAddr = %v; want %v", got, want)
|
||||
}
|
||||
if _, err := nw.ListenPacket(ctx, "udp4", "127.0.0.1:5000"); err == nil {
|
||||
t.Errorf("ListenPacket on in-use address succeeded")
|
||||
}
|
||||
|
||||
if _, err := a.WriteTo([]byte("hello"), b.LocalAddr()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A packet to nowhere is dropped without error.
|
||||
if _, err := a.WriteTo([]byte("lost"), net.UDPAddrFromAddrPort(netip.MustParseAddrPort("127.0.0.1:1"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf := make([]byte, 100)
|
||||
n, src, err := b.ReadFrom(buf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(buf[:n]) != "hello" || src.String() != a.LocalAddr().String() {
|
||||
t.Errorf("ReadFrom = %q from %v; want %q from %v", buf[:n], src, "hello", a.LocalAddr())
|
||||
}
|
||||
|
||||
// A v4-mapped destination reaches the v4 socket.
|
||||
mapped := netip.AddrPortFrom(netip.MustParseAddr("::ffff:127.0.0.1"), 5000)
|
||||
if _, err := a.(*packetConn).WriteToUDPAddrPort([]byte("mapped"), mapped); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, _, err := b.ReadFrom(buf); err != nil || string(buf[:n]) != "mapped" {
|
||||
t.Errorf("ReadFrom = %q, %v; want %q", buf[:n], err, "mapped")
|
||||
}
|
||||
|
||||
// A v4-mapped listen address binds the v4 address.
|
||||
m, err := nw.ListenPacket(ctx, "udp6", "[::ffff:127.0.0.1]:5001")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.Close()
|
||||
if got, want := m.LocalAddr().String(), "127.0.0.1:5001"; got != want {
|
||||
t.Errorf("m.LocalAddr = %v; want %v", got, want)
|
||||
}
|
||||
if _, err := a.WriteTo([]byte("to-mapped"), net.UDPAddrFromAddrPort(netip.MustParseAddrPort("127.0.0.1:5001"))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.SetReadDeadline(time.Now().Add(time.Second)) // in case it was dropped
|
||||
if n, _, err := m.ReadFrom(buf); err != nil || string(buf[:n]) != "to-mapped" {
|
||||
t.Errorf("ReadFrom = %q, %v; want %q", buf[:n], err, "to-mapped")
|
||||
}
|
||||
|
||||
b6, err := nw.ListenPacket(ctx, "udp6", ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer b6.Close()
|
||||
if got, want := b6.LocalAddr().String(), "[::1]:33001"; got != want { // next in rotation
|
||||
t.Errorf("b6.LocalAddr = %v; want %v", got, want)
|
||||
}
|
||||
|
||||
if err := b.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := b.ReadFrom(buf); !errors.Is(err, net.ErrClosed) {
|
||||
t.Errorf("ReadFrom after Close = %v; want net.ErrClosed", err)
|
||||
}
|
||||
if b2, err := nw.ListenPacket(ctx, "udp4", "127.0.0.1:5000"); err != nil {
|
||||
t.Errorf("ListenPacket on same address after close failed: %v", err)
|
||||
} else {
|
||||
b2.Close()
|
||||
}
|
||||
|
||||
// A freed ephemeral port isn't reused right away.
|
||||
freed := a.LocalAddr().String()
|
||||
a.Close()
|
||||
a2, err := nw.ListenPacket(ctx, "udp4", ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer a2.Close()
|
||||
if got := a2.LocalAddr().String(); got == freed {
|
||||
t.Errorf("ephemeral port %v reused right after close", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPacketConnDeadline(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
var nw Network
|
||||
pc, err := nw.ListenPacket(t.Context(), "udp4", ":0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pc.Close()
|
||||
buf := make([]byte, 10)
|
||||
|
||||
t0 := time.Now()
|
||||
pc.SetReadDeadline(t0.Add(time.Second))
|
||||
if _, _, err := pc.ReadFrom(buf); !errors.Is(err, os.ErrDeadlineExceeded) {
|
||||
t.Fatalf("ReadFrom = %v; want os.ErrDeadlineExceeded", err)
|
||||
}
|
||||
if d := time.Since(t0); d != time.Second {
|
||||
t.Errorf("ReadFrom returned after %v; want 1s", d)
|
||||
}
|
||||
|
||||
// Moving the deadline into the past wakes a blocked reader.
|
||||
pc.SetReadDeadline(time.Time{})
|
||||
errc := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, err := pc.ReadFrom(buf)
|
||||
errc <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
pc.SetReadDeadline(time.Now())
|
||||
if err := <-errc; !errors.Is(err, os.ErrDeadlineExceeded) {
|
||||
t.Fatalf("ReadFrom = %v; want os.ErrDeadlineExceeded", err)
|
||||
}
|
||||
|
||||
// Close wakes a blocked reader.
|
||||
pc.SetReadDeadline(time.Time{})
|
||||
go func() {
|
||||
_, _, err := pc.ReadFrom(buf)
|
||||
errc <- err
|
||||
}()
|
||||
synctest.Wait()
|
||||
pc.Close()
|
||||
if err := <-errc; !errors.Is(err, net.ErrClosed) {
|
||||
t.Fatalf("ReadFrom = %v; want net.ErrClosed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user