| 1 |
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly> |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
// Package udp implements DTLS specific UDP networking primitives. |
| 5 |
// NOTE: this package is an adaption of pion/transport/udp that allows for |
| 6 |
// routing datagrams based on identifiers other than the remote address. The |
| 7 |
// primary use case for this functionality is routing based on DTLS connection |
| 8 |
// IDs. In order to allow for consumers of this package to treat connections as |
| 9 |
// generic net.PackageConn, routing and identitier establishment is based on |
| 10 |
// custom introspecion of datagrams, rather than direct intervention by |
| 11 |
// consumers. If possible, the updates made in this repository will be reflected |
| 12 |
// back upstream. If not, it is likely that this will be moved to a public |
| 13 |
// package in this repository. |
| 14 |
// |
| 15 |
// This package was migrated from pion/transport/udp at |
| 16 |
// https://github.com/pion/transport/commit/6890c795c807a617c054149eee40a69d7fdfbfdb |
| 17 |
package udp |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"net" |
| 23 |
"sync" |
| 24 |
"sync/atomic" |
| 25 |
"time" |
| 26 |
|
| 27 |
idtlsnet "github.com/pion/dtls/v3/internal/net" |
| 28 |
dtlsnet "github.com/pion/dtls/v3/pkg/net" |
| 29 |
"github.com/pion/transport/v4/deadline" |
| 30 |
) |
| 31 |
|
| 32 |
const ( |
| 33 |
receiveMTU = 8192 |
| 34 |
defaultListenBacklog = 128 // same as Linux default |
| 35 |
) |
| 36 |
|
| 37 |
// Typed errors. |
| 38 |
var ( |
| 39 |
ErrClosedListener = errors.New("udp: listener closed") |
| 40 |
ErrListenQueueExceeded = errors.New("udp: listen queue exceeded") |
| 41 |
) |
| 42 |
|
| 43 |
// listener augments a connection-oriented Listener over a UDP PacketConn. |
| 44 |
type listener struct { |
| 45 |
pConn *net.UDPConn |
| 46 |
|
| 47 |
accepting atomic.Value // bool |
| 48 |
acceptCh chan *PacketConn |
| 49 |
doneCh chan struct{} |
| 50 |
doneOnce sync.Once |
| 51 |
acceptFilter func([]byte) bool |
| 52 |
datagramRouter func([]byte) (string, bool) |
| 53 |
connIdentifier func([]byte) (string, bool) |
| 54 |
|
| 55 |
connLock sync.Mutex |
| 56 |
conns map[string]*PacketConn |
| 57 |
connWG sync.WaitGroup |
| 58 |
|
| 59 |
readWG sync.WaitGroup |
| 60 |
errClose atomic.Value // error |
| 61 |
|
| 62 |
readDoneCh chan struct{} |
| 63 |
errRead atomic.Value // error |
| 64 |
} |
| 65 |
|
| 66 |
// Accept waits for and returns the next connection to the listener. |
| 67 |
func (l *listener) Accept() (net.PacketConn, net.Addr, error) { |
| 68 |
select { |
| 69 |
case c := <-l.acceptCh: |
| 70 |
l.connWG.Add(1) |
| 71 |
|
| 72 |
return c, c.raddr, nil |
| 73 |
|
| 74 |
case <-l.readDoneCh: |
| 75 |
err, _ := l.errRead.Load().(error) |
| 76 |
|
| 77 |
return nil, nil, err |
| 78 |
|
| 79 |
case <-l.doneCh: |
| 80 |
return nil, nil, ErrClosedListener |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
// Close closes the listener. |
| 85 |
// Any blocked Accept operations will be unblocked and return errors. |
| 86 |
func (l *listener) Close() error { |
| 87 |
var err error |
| 88 |
l.doneOnce.Do(func() { |
| 89 |
l.accepting.Store(false) |
| 90 |
close(l.doneCh) |
| 91 |
|
| 92 |
l.connLock.Lock() |
| 93 |
// Close unaccepted connections |
| 94 |
lclose: |
| 95 |
for { |
| 96 |
select { |
| 97 |
case c := <-l.acceptCh: |
| 98 |
close(c.doneCh) |
| 99 |
// If we have an alternate identifier, remove it from the connection |
| 100 |
// map. |
| 101 |
if id := c.id.Load(); id != nil { |
| 102 |
delete(l.conns, id.(string)) //nolint:forcetypeassert |
| 103 |
} |
| 104 |
// If we haven't already removed the remote address, remove it |
| 105 |
// from the connection map. |
| 106 |
if c.rmraddr.Load() == nil { |
| 107 |
delete(l.conns, c.raddr.String()) |
| 108 |
c.rmraddr.Store(true) |
| 109 |
} |
| 110 |
default: |
| 111 |
break lclose |
| 112 |
} |
| 113 |
} |
| 114 |
nConns := len(l.conns) |
| 115 |
l.connLock.Unlock() |
| 116 |
|
| 117 |
l.connWG.Done() |
| 118 |
|
| 119 |
if nConns == 0 { |
| 120 |
// Wait if this is the final connection. |
| 121 |
l.readWG.Wait() |
| 122 |
if errClose, ok := l.errClose.Load().(error); ok { |
| 123 |
err = errClose |
| 124 |
} |
| 125 |
} else { |
| 126 |
err = nil |
| 127 |
} |
| 128 |
}) |
| 129 |
|
| 130 |
return err |
| 131 |
} |
| 132 |
|
| 133 |
// Addr returns the listener's network address. |
| 134 |
func (l *listener) Addr() net.Addr { |
| 135 |
return l.pConn.LocalAddr() |
| 136 |
} |
| 137 |
|
| 138 |
// ListenConfig stores options for listening to an address. |
| 139 |
type ListenConfig struct { |
| 140 |
// Backlog defines the maximum length of the queue of pending |
| 141 |
// connections. It is equivalent of the backlog argument of |
| 142 |
// POSIX listen function. |
| 143 |
// If a connection request arrives when the queue is full, |
| 144 |
// the request will be silently discarded, unlike TCP. |
| 145 |
// Set zero to use default value 128 which is same as Linux default. |
| 146 |
Backlog int |
| 147 |
|
| 148 |
// AcceptFilter determines whether the new conn should be made for |
| 149 |
// the incoming packet. If not set, any packet creates new conn. |
| 150 |
AcceptFilter func([]byte) bool |
| 151 |
|
| 152 |
// DatagramRouter routes an incoming datagram to a connection by extracting |
| 153 |
// an identifier from the its paylod |
| 154 |
DatagramRouter func([]byte) (string, bool) |
| 155 |
|
| 156 |
// ConnectionIdentifier extracts an identifier from an outgoing packet. If |
| 157 |
// the identifier is not already associated with the connection, it will be |
| 158 |
// added. |
| 159 |
ConnectionIdentifier func([]byte) (string, bool) |
| 160 |
} |
| 161 |
|
| 162 |
// Listen creates a new listener based on the ListenConfig. |
| 163 |
func (lc *ListenConfig) Listen(network string, laddr *net.UDPAddr) (dtlsnet.PacketListener, error) { |
| 164 |
if lc.Backlog == 0 { |
| 165 |
lc.Backlog = defaultListenBacklog |
| 166 |
} |
| 167 |
|
| 168 |
conn, err := net.ListenUDP(network, laddr) |
| 169 |
if err != nil { |
| 170 |
return nil, err |
| 171 |
} |
| 172 |
|
| 173 |
packetListener := &listener{ |
| 174 |
pConn: conn, |
| 175 |
acceptCh: make(chan *PacketConn, lc.Backlog), |
| 176 |
conns: make(map[string]*PacketConn), |
| 177 |
doneCh: make(chan struct{}), |
| 178 |
acceptFilter: lc.AcceptFilter, |
| 179 |
datagramRouter: lc.DatagramRouter, |
| 180 |
connIdentifier: lc.ConnectionIdentifier, |
| 181 |
readDoneCh: make(chan struct{}), |
| 182 |
} |
| 183 |
|
| 184 |
packetListener.accepting.Store(true) |
| 185 |
packetListener.connWG.Add(1) |
| 186 |
packetListener.readWG.Add(2) // wait readLoop and Close execution routine |
| 187 |
|
| 188 |
go packetListener.readLoop() |
| 189 |
go func() { |
| 190 |
packetListener.connWG.Wait() |
| 191 |
if err := packetListener.pConn.Close(); err != nil { |
| 192 |
packetListener.errClose.Store(err) |
| 193 |
} |
| 194 |
packetListener.readWG.Done() |
| 195 |
}() |
| 196 |
|
| 197 |
return packetListener, nil |
| 198 |
} |
| 199 |
|
| 200 |
// Listen creates a new listener using default ListenConfig. |
| 201 |
func Listen(network string, laddr *net.UDPAddr) (dtlsnet.PacketListener, error) { |
| 202 |
return (&ListenConfig{}).Listen(network, laddr) |
| 203 |
} |
| 204 |
|
| 205 |
// readLoop dispatches packets to the proper connection, creating a new one if |
| 206 |
// necessary, until all connections are closed. |
| 207 |
func (l *listener) readLoop() { |
| 208 |
defer l.readWG.Done() |
| 209 |
defer close(l.readDoneCh) |
| 210 |
|
| 211 |
buf := make([]byte, receiveMTU) |
| 212 |
|
| 213 |
for { |
| 214 |
n, raddr, err := l.pConn.ReadFrom(buf) |
| 215 |
if err != nil { |
| 216 |
l.errRead.Store(err) |
| 217 |
|
| 218 |
return |
| 219 |
} |
| 220 |
conn, ok, err := l.getConn(raddr, buf[:n]) |
| 221 |
if err != nil { |
| 222 |
continue |
| 223 |
} |
| 224 |
if ok { |
| 225 |
_, _ = conn.buffer.WriteTo(buf[:n], raddr) |
| 226 |
} |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
// getConn gets an existing connection or creates a new one. |
| 231 |
func (l *listener) getConn(raddr net.Addr, buf []byte) (*PacketConn, bool, error) { //nolint:cyclop |
| 232 |
l.connLock.Lock() |
| 233 |
defer l.connLock.Unlock() |
| 234 |
// If we have a custom resolver, use it. |
| 235 |
if l.datagramRouter != nil { |
| 236 |
if id, ok := l.datagramRouter(buf); ok { |
| 237 |
if conn, ok := l.conns[id]; ok { |
| 238 |
return conn, true, nil |
| 239 |
} |
| 240 |
} |
| 241 |
} |
| 242 |
|
| 243 |
// If we don't have a custom resolver, or we were unable to find an |
| 244 |
// associated connection, fall back to remote address. |
| 245 |
conn, ok := l.conns[raddr.String()] |
| 246 |
if !ok { |
| 247 |
if isAccepting, ok := l.accepting.Load().(bool); !isAccepting || !ok { |
| 248 |
return nil, false, ErrClosedListener |
| 249 |
} |
| 250 |
if l.acceptFilter != nil { |
| 251 |
if !l.acceptFilter(buf) { |
| 252 |
return nil, false, nil |
| 253 |
} |
| 254 |
} |
| 255 |
conn = l.newPacketConn(raddr) |
| 256 |
select { |
| 257 |
case l.acceptCh <- conn: |
| 258 |
l.conns[raddr.String()] = conn |
| 259 |
default: |
| 260 |
return nil, false, ErrListenQueueExceeded |
| 261 |
} |
| 262 |
} |
| 263 |
|
| 264 |
return conn, true, nil |
| 265 |
} |
| 266 |
|
| 267 |
// PacketConn is a net.PacketConn implementation that is able to dictate its |
| 268 |
// routing ID via an alternate identifier from its remote address. Internal |
| 269 |
// buffering is performed for reads, and writes are passed through to the |
| 270 |
// underlying net.PacketConn. |
| 271 |
type PacketConn struct { |
| 272 |
listener *listener |
| 273 |
|
| 274 |
raddr net.Addr |
| 275 |
rmraddr atomic.Value // bool |
| 276 |
id atomic.Value // string |
| 277 |
|
| 278 |
buffer *idtlsnet.PacketBuffer |
| 279 |
|
| 280 |
doneCh chan struct{} |
| 281 |
doneOnce sync.Once |
| 282 |
|
| 283 |
writeDeadline *deadline.Deadline |
| 284 |
} |
| 285 |
|
| 286 |
// newPacketConn constructs a new PacketConn. |
| 287 |
func (l *listener) newPacketConn(raddr net.Addr) *PacketConn { |
| 288 |
return &PacketConn{ |
| 289 |
listener: l, |
| 290 |
raddr: raddr, |
| 291 |
buffer: idtlsnet.NewPacketBuffer(), |
| 292 |
doneCh: make(chan struct{}), |
| 293 |
writeDeadline: deadline.New(), |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
// ReadFrom reads a single packet payload and its associated remote address from |
| 298 |
// the underlying buffer. |
| 299 |
func (c *PacketConn) ReadFrom(buff []byte) (int, net.Addr, error) { |
| 300 |
return c.buffer.ReadFrom(buff) |
| 301 |
} |
| 302 |
|
| 303 |
// WriteTo writes len(payload) bytes from payload to the specified address. |
| 304 |
func (c *PacketConn) WriteTo(payload []byte, addr net.Addr) (n int, err error) { |
| 305 |
// If we have a connection identifier, check to see if the outgoing packet |
| 306 |
// sets it. |
| 307 |
if c.listener.connIdentifier != nil { |
| 308 |
id := c.id.Load() |
| 309 |
// Only update establish identifier if we haven't already done so. |
| 310 |
if id == nil { |
| 311 |
candidate, ok := c.listener.connIdentifier(payload) |
| 312 |
// If we have an identifier, add entry to connection map. |
| 313 |
if ok { |
| 314 |
c.listener.connLock.Lock() |
| 315 |
c.listener.conns[candidate] = c |
| 316 |
c.listener.connLock.Unlock() |
| 317 |
c.id.Store(candidate) |
| 318 |
} |
| 319 |
} |
| 320 |
// If we are writing to a remote address that differs from the initial, |
| 321 |
// we have an alternate identifier established, and we haven't already |
| 322 |
// freed the remote address, free the remote address to be used by |
| 323 |
// another connection. |
| 324 |
// Note: this strategy results in holding onto a remote address after it |
| 325 |
// is potentially no longer in use by the client. However, releasing |
| 326 |
// earlier means that we could miss some packets that should have been |
| 327 |
// routed to this connection. Ideally, we would drop the connection |
| 328 |
// entry for the remote address as soon as the client starts sending |
| 329 |
// using an alternate identifier, but in practice this proves |
| 330 |
// challenging because any client could spoof a connection identifier, |
| 331 |
// resulting in the remote address entry being dropped prior to the |
| 332 |
// "real" client transitioning to sending using the alternate |
| 333 |
// identifier. |
| 334 |
if id != nil && c.rmraddr.Load() == nil && addr.String() != c.raddr.String() { |
| 335 |
c.listener.connLock.Lock() |
| 336 |
delete(c.listener.conns, c.raddr.String()) |
| 337 |
c.rmraddr.Store(true) |
| 338 |
c.listener.connLock.Unlock() |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
select { |
| 343 |
case <-c.writeDeadline.Done(): |
| 344 |
return 0, context.DeadlineExceeded |
| 345 |
default: |
| 346 |
} |
| 347 |
|
| 348 |
return c.listener.pConn.WriteTo(payload, addr) |
| 349 |
} |
| 350 |
|
| 351 |
// Close closes the conn and releases any Read calls. |
| 352 |
func (c *PacketConn) Close() error { |
| 353 |
var err error |
| 354 |
c.doneOnce.Do(func() { |
| 355 |
c.listener.connWG.Done() |
| 356 |
close(c.doneCh) |
| 357 |
c.listener.connLock.Lock() |
| 358 |
// If we have an alternate identifier, remove it from the connection |
| 359 |
// map. |
| 360 |
if id := c.id.Load(); id != nil { |
| 361 |
delete(c.listener.conns, id.(string)) //nolint:forcetypeassert |
| 362 |
} |
| 363 |
// If we haven't already removed the remote address, remove it from the |
| 364 |
// connection map. |
| 365 |
if c.rmraddr.Load() == nil { |
| 366 |
delete(c.listener.conns, c.raddr.String()) |
| 367 |
c.rmraddr.Store(true) |
| 368 |
} |
| 369 |
nConns := len(c.listener.conns) |
| 370 |
c.listener.connLock.Unlock() |
| 371 |
|
| 372 |
if isAccepting, ok := c.listener.accepting.Load().(bool); nConns == 0 && !isAccepting && ok { |
| 373 |
// Wait if this is the final connection |
| 374 |
c.listener.readWG.Wait() |
| 375 |
if errClose, ok := c.listener.errClose.Load().(error); ok { |
| 376 |
err = errClose |
| 377 |
} |
| 378 |
} else { |
| 379 |
err = nil |
| 380 |
} |
| 381 |
|
| 382 |
if errBuf := c.buffer.Close(); errBuf != nil && err == nil { |
| 383 |
err = errBuf |
| 384 |
} |
| 385 |
}) |
| 386 |
|
| 387 |
return err |
| 388 |
} |
| 389 |
|
| 390 |
// LocalAddr implements net.PacketConn.LocalAddr. |
| 391 |
func (c *PacketConn) LocalAddr() net.Addr { |
| 392 |
return c.listener.pConn.LocalAddr() |
| 393 |
} |
| 394 |
|
| 395 |
// SetDeadline implements net.PacketConn.SetDeadline. |
| 396 |
func (c *PacketConn) SetDeadline(t time.Time) error { |
| 397 |
c.writeDeadline.Set(t) |
| 398 |
|
| 399 |
return c.SetReadDeadline(t) |
| 400 |
} |
| 401 |
|
| 402 |
// SetReadDeadline implements net.PacketConn.SetReadDeadline. |
| 403 |
func (c *PacketConn) SetReadDeadline(t time.Time) error { |
| 404 |
return c.buffer.SetReadDeadline(t) |
| 405 |
} |
| 406 |
|
| 407 |
// SetWriteDeadline implements net.PacketConn.SetWriteDeadline. |
| 408 |
func (c *PacketConn) SetWriteDeadline(t time.Time) error { |
| 409 |
c.writeDeadline.Set(t) |
| 410 |
// Write deadline of underlying connection should not be changed |
| 411 |
// since the connection can be shared. |
| 412 |
return nil |
| 413 |
} |