Documentation
¶
Overview ¶
Package udpflow turns UDP datagrams into connections that can be accepted from or dialed through a shared packet socket.
Index ¶
- Constants
- Variables
- func ListenUDPReusePort(ctx context.Context, lc *net.ListenConfig, network, address string, n int) ([]*net.UDPConn, error)
- type PacketListener
- func (l *PacketListener) Accept() (net.Conn, error)
- func (l *PacketListener) Addr() net.Addr
- func (l *PacketListener) Close() error
- func (l *PacketListener) DestinationAware() bool
- func (l *PacketListener) Dial(peer net.Addr) (net.Conn, error)
- func (l *PacketListener) RejectPeer(peer net.Addr)
- func (l *PacketListener) SetIdleTimeout(d time.Duration)
- func (l *PacketListener) WriteTo(p []byte, addr net.Addr) (int, error)
- type PacketListenerOption
- func WithPacketAcceptBacklog(n int) PacketListenerOption
- func WithPacketAcceptFilter(filter func(peer net.Addr, first []byte) bool) PacketListenerOption
- func WithPacketClock(c timeshim.Clock) PacketListenerOption
- func WithPacketConns(more ...net.PacketConn) PacketListenerOption
- func WithPacketIdleTimeout(d time.Duration) PacketListenerOption
- func WithPacketMaxConns(n int) PacketListenerOption
- func WithPacketMaxDatagram(n int) PacketListenerOption
- func WithPacketQueue(n int) PacketListenerOption
- func WithPacketReadBatch(n int) PacketListenerOption
- func WithPacketRejectCache(size int, ttl time.Duration) PacketListenerOption
Examples ¶
Constants ¶
const ( // DefaultPacketQueue is how many datagrams a connection holds until // they are read; see WithPacketQueue. DefaultPacketQueue = 128 // DefaultPacketAcceptBacklog is how many new connections wait for // Accept; see WithPacketAcceptBacklog. DefaultPacketAcceptBacklog = 128 // DefaultPacketMaxDatagram is the largest datagram delivered in full; // see WithPacketMaxDatagram. DefaultPacketMaxDatagram = bufpool.MaxDatagram )
Defaults of NewPacketListener.
Variables ¶
var ErrPacketConnLimit = errors.New("udpflow: packet listener connection limit reached")
ErrPacketConnLimit is returned by PacketListener.Dial while the listener holds the connections that WithPacketMaxConns allows.
var ErrPacketPeerConnected = errors.New("udpflow: packet listener peer already connected")
ErrPacketPeerConnected is returned by PacketListener.Dial for a peer that has a connection already.
var ErrReusePortUnsupported = errors.New("udpflow: SO_REUSEPORT load balancing is not supported on this system")
ErrReusePortUnsupported is returned by ListenUDPReusePort for more than one socket where the system does not spread datagrams over sockets that share a port.
Functions ¶
func ListenUDPReusePort ¶
func ListenUDPReusePort(ctx context.Context, lc *net.ListenConfig, network, address string, n int) ([]*net.UDPConn, error)
ListenUDPReusePort opens n UDP sockets on address with SO_REUSEPORT, among which the kernel spreads the datagrams by their source, for a PacketListener that reads them with WithPacketConns. A port of 0 is chosen by the first socket and shared by the rest. lc, nil meaning a zero net.ListenConfig, may set other socket options with its Control. A non-positive n opens one socket without the option. More than one is supported on Linux and Android; elsewhere it returns ErrReusePortUnsupported. A network other than "udp", "udp4", or "udp6" returns net.UnknownNetworkError.
Types ¶
type PacketListener ¶
type PacketListener struct {
// contains filtered or unexported fields
}
PacketListener accepts datagram flows from a packet connection such as a UDP socket. A datagram for a new flow starts a connection that Accept returns. Later datagrams for that flow are read from it, and writes on it send datagrams to the peer. It is the server side of connection-oriented protocols over UDP.
Each Read of a connection returns one datagram, truncated to the buffer like a UDP socket. Datagrams that arrive while a connection's queue is full, or while too many connections wait for Accept, are dropped. After a connection is closed, the next datagram for its flow starts a new one. A connection lasts until it is closed, so a server facing untrusted or spoofed peers should set WithPacketIdleTimeout or read deadlines, and WithPacketMaxConns.
A flow is keyed by remote address. When every socket is a wildcard *net.UDPConn with packet information enabled (Linux, Android, macOS, iOS and Windows), the key includes the local unicast destination and, for link-local destinations, its interface index. An accepted unicast flow reports that destination in LocalAddr and uses it as its reply source. If the source is temporarily unavailable, that datagram is retried with an OS-selected source. A flow whose source is confirmed as a broadcast or multicast address after a write error switches to OS-selected sources and reports the socket's address. All broadcast and multicast traffic from a remote address shares one flow, separate from its unicast flows, with an OS-selected reply source. Datagrams missing packet information are dropped in this mode. If any socket cannot enable packet information, every socket uses remote-only flow keys and OS-selected reply sources. DestinationAware reports which mode the listener uses. WriteTo always uses the OS-selected source.
Create it with NewPacketListener. The zero value has no packet connection: its Accept waits until Close, its Addr is nil, and its Dial and WriteTo fail.
Example ¶
Serve one goroutine per UDP peer, like a TCP server.
package main
import (
"log"
"net"
"time"
"github.com/djylb/netx/udpflow"
)
func main() {
pc, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
l := udpflow.NewPacketListener(pc, udpflow.WithPacketIdleTimeout(time.Minute))
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = c.Close() }()
buf := make([]byte, 1500)
for {
n, err := c.Read(buf) // one datagram from this peer
if err != nil {
return
}
_, _ = c.Write(buf[:n]) // echo it back
}
}()
}
}
Output:
func NewPacketListener ¶
func NewPacketListener(pc net.PacketConn, opts ...PacketListenerOption) *PacketListener
NewPacketListener starts reading pc and returns a listener for its peers. The listener owns pc and closes it on Close. A read error meaning that pc is closed or exhausted (net.ErrClosed, io.EOF) closes the listener; other read errors are retried, with a growing delay while they persist, and an expired read deadline on pc is cleared.
func (*PacketListener) Accept ¶
func (l *PacketListener) Accept() (net.Conn, error)
Accept waits for the next flow. It returns net.ErrClosed once the listener is closed. The idle timeout of a connection starts when it is accepted.
func (*PacketListener) Addr ¶
func (l *PacketListener) Addr() net.Addr
Addr returns the packet connection's local address.
func (*PacketListener) Close ¶
func (l *PacketListener) Close() error
Close closes the packet connection and every connection of the listener, and waits for the listener's goroutines to stop unless the accept filter, which may call Close, is running.
func (*PacketListener) DestinationAware ¶
func (l *PacketListener) DestinationAware() bool
DestinationAware reports whether the listener separates unicast flows by their destination. This mode is selected at construction when every socket can report packet destinations. Otherwise all sockets share remote-only flow keys. The result is fixed for the listener's lifetime.
func (*PacketListener) Dial ¶
Dial returns a connection to peer over the listener's packet connection, as if peer had sent a datagram, but without Accept: datagrams from peer are read from it, and its writes are sent to peer. It reaches a known peer from the socket that also accepts others, as hole punching does. It returns ErrPacketPeerConnected if peer has any connection, including one waiting for Accept or one carrying broadcast or multicast traffic. It returns ErrPacketConnLimit at the limit of WithPacketMaxConns, and net.ErrClosed once the listener is closed. The idle timeout of the connection starts at Dial. Flow deadlines also bound waiting to send. A socket that rejects a requested deadline reports its error on an active or subsequent write. Closing a flow interrupts an active send only when its socket supports deadlines. Closing the listener closes the shared socket. With packet information enabled, peer must be a *net.UDPAddr with a valid IP address. Writes use the OS-selected source until the first datagram from peer with a unicast destination at the listener's port fixes the local destination and any link-local scope. This binding uses the packet's claimed source address. A sender that can spoof peer's source may bind the connection first. Later datagrams for other local destinations or scopes start separate flows, as for Accept.
func (*PacketListener) RejectPeer ¶
func (l *PacketListener) RejectPeer(peer net.Addr)
RejectPeer drops the datagrams of new flows from peer, before the accept filter runs, for the time to live of WithPacketRejectCache; without that option it does nothing. It leaves the peer's existing connections alone. Call it only for a peer whose source address is proven, never for one that a datagram merely claims, as a spoofed source would lock the real peer out; the accept filter may call it for a peer it rejects.
func (*PacketListener) SetIdleTimeout ¶
func (l *PacketListener) SetIdleTimeout(d time.Duration)
SetIdleTimeout changes the WithPacketIdleTimeout of a running listener, for the connections it holds too: each is checked against d within a quarter of d, so one idle for d by then is closed; a non-positive d keeps idle connections from now on.
type PacketListenerOption ¶
type PacketListenerOption func(*packetListenerOptions)
PacketListenerOption configures NewPacketListener.
func WithPacketAcceptBacklog ¶
func WithPacketAcceptBacklog(n int) PacketListenerOption
WithPacketAcceptBacklog sets how many new connections wait for Accept, DefaultPacketAcceptBacklog by default. A non-positive n is treated as one.
func WithPacketAcceptFilter ¶
func WithPacketAcceptFilter(filter func(peer net.Addr, first []byte) bool) PacketListenerOption
WithPacketAcceptFilter drops a datagram of a new flow for which filter returns false instead of starting a connection for it. filter gets the peer and the datagram, which is valid only during the call, so that it can check a token or cookie in it before anything is allocated for the peer, and reply with WriteTo without state, as a retry does; peers that only spoof their source then take no place in the accept backlog or under WithPacketMaxConns. It runs on the read loop, so it must be fast. It may close the listener or its connections. Multiple sockets can call it concurrently.
func WithPacketClock ¶
func WithPacketClock(c timeshim.Clock) PacketListenerOption
WithPacketClock sets the clock for idle timeouts and peer rejection expiry. The system clock is used by default.
func WithPacketConns ¶
func WithPacketConns(more ...net.PacketConn) PacketListenerOption
WithPacketConns adds more packet connections to the listener, which reads each with a read loop of its own into the same connections, so that peers are read on several cores: sockets bound to the same address with SO_REUSEPORT, as ListenUDPReusePort makes them, among which the kernel spreads peers by their address, so that the datagrams of one peer keep their order. An accepted connection writes from the packet connection that its flow first came through, and Dial and WriteTo from pc. The listener owns them as it owns pc.
func WithPacketIdleTimeout ¶
func WithPacketIdleTimeout(d time.Duration) PacketListenerOption
WithPacketIdleTimeout closes a connection that has neither received nor sent a datagram for d since Accept returned it. Its pending and later Reads return io.EOF. Connections waiting for Accept are kept with their datagrams. A non-positive d, the default, keeps idle connections.
func WithPacketMaxConns ¶
func WithPacketMaxConns(n int) PacketListenerOption
WithPacketMaxConns sets how many connections the listener holds at once, accepted or waiting for Accept, those of Dial included; a non-positive n, the default, sets no limit. While it holds n, a datagram for a new flow is dropped, before the accept filter runs or anything is allocated for the peer, and Dial returns ErrPacketConnLimit. Each connection holds its queued datagrams, so the limit bounds the listener's memory with WithPacketQueue. Peers that spoof their source can take every place, and keep it while they send, until an idle timeout or the application closes their connections: pair the limit with WithPacketIdleTimeout, and with an accept filter that checks a token, which spoofed sources cannot echo, to keep the places for real peers.
func WithPacketMaxDatagram ¶
func WithPacketMaxDatagram(n int) PacketListenerOption
WithPacketMaxDatagram sets the largest datagram that is delivered in full, DefaultPacketMaxDatagram bytes by default. A non-positive n is treated as one. Longer datagrams are truncated. Outside batch reads the read buffer is at least 65535 bytes, since Windows drops a datagram that does not fit without reporting its sender or data.
func WithPacketQueue ¶
func WithPacketQueue(n int) PacketListenerOption
WithPacketQueue sets how many datagrams a connection holds until they are read, DefaultPacketQueue by default. A datagram larger than 2 KiB takes the room of several in proportion to its size, so a connection holds at most n × 2 KiB of queued datagrams, or a single larger one. A connection's queue grows with the datagrams waiting in it, a pointer-sized slot each, up to n, and gives the room of a burst back once it is read, so the bound costs nothing until datagrams pile up. A non-positive n is treated as one.
func WithPacketReadBatch ¶
func WithPacketReadBatch(n int) PacketListenerOption
WithPacketReadBatch reads up to n datagrams with one system call, where the platform has one for it (recvmmsg on Linux and Android) and the packet connection is a *net.UDPConn; elsewhere a datagram is read at a time. Each read loop then holds n buffers of the WithPacketMaxDatagram size, so lower that to what the protocol sends. A non-positive or single n, the default, reads a datagram at a time.
func WithPacketRejectCache ¶
func WithPacketRejectCache(size int, ttl time.Duration) PacketListenerOption
WithPacketRejectCache remembers up to size peers given to RejectPeer, for ttl each, and drops the datagrams of a new connection from them before the accept filter runs, so that a peer that keeps sending costs a lookup. The cache grows with the peers it holds; at size, the older half of them is forgotten. A non-positive size or ttl, the default, keeps none, and RejectPeer then does nothing.
The filter's own rejections are not remembered: a datagram's source can be spoofed, and remembering it would let anyone lock a real peer out. Call RejectPeer only for a source that the datagram proves, as one that echoes a token the listener sent it does.