mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
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 <bradfitz@tailscale.com>
245 lines
6.5 KiB
Go
245 lines
6.5 KiB
Go
// 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 }
|