RELAYLINK

UDP forwarding design

Document ID: DES-006
Status: Draft
Version: v1.4.0
Updated: 2026-11-29
Research Date: 2026-10-05
Related: Requirements, ADR-0024, Peer Direct & Relay Fallback

1. Transport and Compatibility

Standard cloud-ingress forwarding and default peer relay (relayOnly) carry unicast UDP over Server-paired TCP data tunnels. Since v0.1.0-rc.18, authorized peer unicast UDP configured with preferDirect can also run over reliable P2P streams—bidirectional QUIC 1.3 streams on the shared UDP socket when encrypted, or mutually authenticated ICE-TCP streams when encryption is explicitly disabled—automatically falling back to the same encryption mode over the Server relay when direct connectivity fails. Both relay and direct reliable streams retain the exact 4-byte big-endian length framing, 65507-byte maximum payload, 32-datagram per-source bounded queue, and udpIdleTimeoutSeconds idle reclamation contract. See Peer Direct & Relay Fallback for direct negotiation, probe budgets, and fallback rules.

Relay paths preserve the NTP1 magic, separated control and data ports, independent tunnel binding, and per-client authentication. Wire protocol v4 introduces UDP support (extended by v5 for HTTP and P2P control signaling). Newer Servers accept v3, v4, and v5, locking the control session version on the first Register frame and responding with matching frame headers:

  • v3 compatibility: Initial and incremental snapshots for v3 exclude UDP channels and UDP outbound mappings, strip added UDP fields during serialization, compute config digests using the legacy field order, and preserve standard TCP proxy plus TCP peer access between legacy and newer Agents.
  • UDP version gate: UDP is permitted only when all participating endpoints are v4 or later; v1/v2, unknown versions, and mid-session version switches are rejected.
  • Data binding consistency: Data bindings must match the control session version; a mismatched version does not consume the one-time binding token. See ADR-0025.
  • Schema compatibility: JSON schemaVersion is unchanged; legacy channel files omitting incremental fields continue defaulting to TCP. Plain TCP copies raw bytes after binding; UDP uses datagram framing inside the bound TCP connection (or the established direct stream). Each source session exclusively owns a single tunnel or direct stream without cross-session multiplexing.

Datagram Framing

Each UDP application record consists of a 4-byte big-endian signed non-negative length followed by the payload, supporting payloads from 0 to 65507 bytes:

  • Length 0 represents a valid empty datagram; TCP/stream EOF signals tunnel termination.
  • Out-of-range lengths or truncated payloads immediately terminate the session without delivering partial datagrams.
  • Application records inside the bound stream do not include an inner NTP1 Data header.
  • In peer relay mode, records are written to FramedDuplexStream (plaintext) or SslStream layered over it (encrypted) after the access proof succeeds. The outer Data frame limit of 32 KiB remains unchanged; large datagrams span multiple Data and TLS records and are reassembled before sending a single UDP packet. TCP half-close records do not apply to UDP.

Snapshot Sync and Protocol Switching

ChannelSnapshot distributes transportProtocol and udpIdleTimeoutSeconds; OutboundMappingSnapshot derives the same fields from the target channel rather than duplicating them in mapping JSON. Standard Open resolves the protocol under the active config version; PeerOpen and PeerOpenGranted carry the protocol field, and both Agents validate it against their confirmed snapshots and reject mismatches. Whenever a target channel's protocol or idle timeout changes, the Server pushes updated snapshots to dependent caller Agents to rebuild their local ingress listeners. Establishment is rejected during transient snapshot skew so TCP bytes are never misinterpreted as UDP.

2. Sessions and Lifecycle

DatagramListener binds one exclusive UdpClient per ingress and maintains a bounded session table keyed by source IPEndPoint:

  1. First-packet registration: On receiving the first packet from a source, the listener creates and registers a DatagramSession, enqueues the payload into the bounded queue, and starts the handler. Synchronous exceptions or handler task failures cancel and dispose only that source session while logging to the host; other sources continue uninterrupted.
  2. Pre-queue checks: Each session owns an independent queue, cancellation token source (CTS), and target UDP socket. Standard security-group and Agent-online checks run before queue allocation, and every subsequent incoming datagram re-evaluates source rules.
  3. Target preparation: Server and Agent enforce existing capacity, pending-connection, and audit gates. The target UDP socket resolves the first IPv4/IPv6 address via async DNS and calls Connect, ensuring only replies from that target IP and port are forwarded. UDP Connect confirms local DNS resolution and socket readiness—it does not prove that the target service is online or reachable, and status outputs must be read accordingly. Target connect timeouts cover DNS resolution plus socket setup.

DatagramRelay runs two concurrent tasks: one reading from the UDP ingress queue into the stream, and one reading complete application records from the stream and sending UDP datagrams. The idle timer starts when relaying begins and refreshes upon every successful datagram forward in either direction (including 0-byte datagrams). When either direction exits, the other is cancelled and awaited: idle timeouts terminate cleanly, while control disconnects, revocations, and service shutdowns exit via external cancellation. UDP has no half-close semantics. Stopping the listener cancels all active ingress sessions; a background loop cleans up completed queues and CTS instances every second; local port persistence (<clientId>.ports.json) records only the mapped port, never payloads or session state.

3. Resource Limits and Observability

Parameter / Mechanism Constraint and Behavior
Per-source queue depth Fixed 32 datagrams; newest datagrams are dropped when full (no unbounded queuing)
Max datagram payload 65507 bytes (up to ~2 MiB queued payload per session plus active in-flight datagrams and socket buffers)
Drop metrics and logs Server increments udpDroppedTotal per drop (exposed in channel and dashboard metrics without per-packet log spam); Agent local ingress drops with the same policy and logs at most one aggregated warning every 30 seconds
Concurrency and quotas Ingress session count is bounded by channel/client MaxConnections; tunnel setup tasks are bounded by global and pending limits; drops from full queues, offline Agents, capacity limits, or ACL rejections are never retried
Socket send buffer RelayLink sets UDP socket send buffers to at least 128 KiB to avoid macOS default buffer limits on max-size datagrams (bounded by OS caps without altering global OS tuning)
Write timeout Defaults to 30 seconds; standard Server relay uses blockedWriteTimeoutSeconds
  • Accounting: Standard channels count raw UDP payload bytes (excluding the 4-byte length header). Peer relay counts outer Data payload bytes (including framing, access proofs, and TLS overhead when encrypted), while preferDirect counts caller-reported deduplicated direct bytes. Empty datagrams count as 0 payload bytes.
  • Audit and privacy: Active connection lists and quotas treat each source session as one connection. Audit records reuse proxy/peer start/end events and connectionId values without storing UDP payloads. Standard UDP proxy tunnels provide no transport encryption (matching standard TCP); rely on application-layer security or authorized peer TLS / QUIC when confidentiality is required.

4. Operations and Explicit Limitations

  • Firewall rules: Business ingress firewalls must permit UDP on configured ingress ports; Server control (:7443) and data (:7444) ports remain TCP-only (plus optional UDP ports for STUN/QUIC when preferDirect is enabled per Peer Direct & Relay Fallback). Linux Docker Compose uses host networking and requires no per-channel port mapping; custom bridge deployments must explicitly publish /udp. TCP and UDP can share the same numeric port because existing TCP control, data, and management listeners do not bind UDP ports.
  • Explicit non-goals: Caller source IPs are not preserved to the target (the target sees the target Agent's socket address). Broadcast, multicast, discovery packet rewriting, native QUIC DATAGRAM routing, packet retries, and lossless connection migration are not supported. Because UDP source addresses can be spoofed, keep security groups, firewalls, and application-level authentication enabled.
  • Head-of-line blocking: Both TCP relay tunnels and preferDirect reliable QUIC/ICE-TCP streams experience head-of-line blocking within a source session when packets are lost and retransmitted.

The implementation uses cancellation-aware .NET 10 UdpClient.ReceiveAsync and SendAsync. API capabilities are separate from engineering parameters: the 32-datagram queue, 60-second default idle timeout, and independent reliable tunnels are RelayLink design choices.

Current test coverage and remaining target-environment gaps are documented in Verification Status.

Repository source