Skip to content

NAT hole punching with relay server fallback (+ overlay connection info) - #657

Open
Mayo0x0 wants to merge 7 commits into
Detanup01:devfrom
Mayo0x0:Mayo0x0-Relay-PR
Open

Mayo0x0 wants to merge 7 commits into
Detanup01:devfrom
Mayo0x0:Mayo0x0-Relay-PR

Conversation

@Mayo0x0

@Mayo0x0 Mayo0x0 commented Dec 1, 2026 •

Copy link
Copy Markdown

Summary

Note for testing: this PR needs #658. Without the friend context menu fix from #658, dev crashes (release and debug builds) when the overlay is opened while another player is in the friends list, which is exactly the situation when testing the relay with 2 players.

Adds NAT hole punching with a relay server fallback, so players can play over the internet without port forwarding or a VPN (same idea as Steam: direct connection when possible, relay otherwise). LAN play is unchanged and keeps priority.

Relay server – tools/relay (new project tool_relay)

  • Small UDP server (gbe_relay_x64 / gbe_relay_x32, Windows + Linux), one UDP port (default 27999).
  • --port, --password (optional), --verbose, plus limits: --max-clients, --max-clients-per-ip, --max-group-size, --client-rate, --total-rate, --register-rate.
  • Built to serve many groups: groups and ids are indexed (O(1) relaying), registration needs an address-bound cookie (no spoofed sources, no amplification), an id can only move to a new address with its secret per-instance token.
  • Groups clients by AppID + optional room, tells each client its public address and the public/local addresses of the other players, forwards traffic when no direct path works.

Relay client in the emulator

  • Registers at the relay, then per peer: LAN (existing TCP) → P2P (UDP hole punching to public + local address) → Relay.
  • Traffic starts through the relay immediately and switches to the direct path once punching succeeds; falls back to the relay if the direct path dies.
  • Reliable messages use KCP (MIT, v1.7, libs/kcp) in stream mode with the same length-prefixed framing as the LAN TCP path; small unreliable packets are plain UDP datagrams.
  • One transport per peer for reliable messages: switching from KCP to LAN TCP only happens once all KCP data was acknowledged, so messages can't arrive out of order.
  • Shares the emulator's UDP socket; relay packets start with GBR (can't be a valid protobuf), so it's compatible with clients without relay config.
  • Relay/peer IPs are allowed through the LAN-only hooks of the experimental builds.
  • GBE_RELAY_FORCE_RELAY=1 disables hole punching (diagnostics).

Config – configs.main.ini

[main::connectivity]
relay_server=relay.example.com:27999
relay_room=myroom
relay_password=secret

Empty relay_server (default) = feature off, no behavior change. Documented in configs.main.EXAMPLE.ini and tools/relay/README.md.

Overlay (experimental)

  • Friends list shows [LAN] / [P2P] / [Relay] per friend (colored, with tooltip).
  • "Toggle User Info" shows the relay state (server, room, public address, peer/P2P count, or connecting / rejected / not resolved).
  • Values are read in the steam callback thread (global_mutex held) and only rendered from a cached copy.

Build / packaging

  • tool_relay added to all CI build matrices and build_win_premake.bat; package scripts copy the README next to it (tools/relay/README.relay.md).
  • KCP added to CREDITS.md.

Review follow-up

  • Review fixes: d73992b. Scalable/public relay (limits, cookie handshake, auth token, indexes): 774b973. Details in the comments below.

Related

Testing

  • Full CI release run on my fork succeeded (all 168 jobs, incl. tool_relay on Win/Linux/ARM): https://github.com/Mayo0x0/gbe_fork/releases/tag/release-2026_12_01-relay
  • Teardown, 2 PCs: same LAN ([LAN]), and one PC on a mobile hotspot behind carrier CGNAT (hole punching impossible → [Relay], game played fine).
  • Local test harness (two instances + relay): hole punching, forced relay, 300 KB reliable packet, unreliable packets, relay → LAN switch with 400 sequenced messages and 0 ordering errors, wrong password rejected, separate rooms isolated.
  • Not tested: Linux runtime (builds only), more than 2 players, hole punching between two different home connections.

Limitations

  • No encryption, IPv4 only.
  • Clients connect full mesh inside a group: many players = many rooms, not one huge group (--max-group-size).
  • Only traffic through the Steam networking interfaces uses the relay; games that connect to an IP directly still need it reachable.

🤖 Generated with Claude Code

@universal963

Copy link
Copy Markdown
Collaborator

Since you've used Claude to code, I think it is ok to use ChatGPT to review it.
Here are results from ChatGPT:

Code Review — PR #657

Review verdict: Request Changes

The proposed NAT traversal and relay functionality is a valuable addition to the project. However, the current implementation has several issues involving connection lifecycle management, reliable message delivery, memory consumption, error handling, and network security.

I would recommend addressing the following issues before merging this PR into the dev branch, particularly before considering public deployment of the relay server.

1. Stale relay connection state and incorrect timeout handling

Severity: High

Location: dll/network.cpp:875–913

In Networking::run_relay(), conn->last_received is refreshed whenever peer.received_data is true.

However, received_data indicates that the peer has received data at some point in the past, rather than indicating that new data has actually been received during the current update.

Additionally, when Relay_Client::update() removes an expired peer, the corresponding Connection::relay_ok flag is not explicitly reset.

Potential consequences include:

  • Disconnected peers remaining logically connected.
  • Delayed or missing disconnection callbacks.
  • Stale connection objects remaining active.
  • Incorrect connection timeout behavior when the relay server remains reachable but communication with the remote peer has failed.

Suggested fix:

Maintain a per-peer timestamp such as last_valid_rx, and update it only upon receiving valid traffic from that peer.

The relay_ok flag should also be recalculated based on the current peer state rather than retaining its previous value indefinitely.

A historical boolean flag should not be used as a connection liveness indicator.

2. Unbounded KCP send queue growth

Severity: High

Location: dll/relay_client.cpp:140–153

Related functions:

  • send_kcp_frame()
  • send()
  • can_send()
  • update_peer()

The current implementation allows messages to continue being queued as long as the KCP instance exists and either the relay registration or direct connection is considered available.

However, successful registration with the relay server does not necessarily mean that the destination peer is reachable.

Although the KCP send and receive windows are configured to 256 segments, these window sizes do not impose an upper limit on the application-side send queue.

Consequently, repeated calls to ikcp_send() can continue allocating memory while the remote peer is unreachable or unable to acknowledge packets.

Furthermore, the implementation does not check the KCP state field, which indicates a dead link after the retransmission threshold has been reached.

Potential consequences include:

  • Unbounded memory consumption.
  • Excessive message accumulation.
  • Significant latency after network recovery.
  • Address space exhaustion, particularly in 32-bit game processes.

This is not a conventional memory leak, but rather uncontrolled memory growth caused by missing resource limits.

Suggested fix:

  • Use ikcp_waitsnd() to monitor pending segments.
  • Introduce per-peer and global send queue limits.
  • Detect and handle KCP dead-link states.
  • Propagate send failures to the upper networking layer.
  • Reject complete reliable messages when the queue limit is reached instead of silently dropping portions of a message.

3. Invalid packets can modify the direct connection endpoint

Severity: High

Location: dll/relay_client.cpp:256–297

Function: Relay_Client::handle_peer_packet()

In the KCP packet handling branch, mark_direct() is called before ikcp_input() validates and processes the received packet.

As a result, the following connection state may be modified before the packet has been successfully validated:

  • direct_ok
  • direct_ep
  • last_direct_rx

The unreliable packet handling branch has a similar issue and also lacks session ID validation.

Invalid, stale, or unexpected packets may therefore cause an established direct communication endpoint to be incorrectly replaced.

Suggested fix:

Separate endpoint validation from ordinary packet processing.

A direct endpoint should only be established or updated after successful bidirectional connectivity verification and session validation.

Moving mark_direct() after a successful ikcp_input() call would partially mitigate the issue, but would not address the underlying lack of peer authentication.

4. Missing SteamID consistency validation in relay messages

Severity: High

Location: dll/network.cpp:902–912

Relay_Client::Message contains a transport-associated peer_id, while the deserialized Protobuf Common_Message contains its own source_id().

The current implementation checks whether the Protobuf message can be parsed and whether source_id() is nonzero, but does not verify that the source SteamID actually belongs to the associated peer.

The message is subsequently passed directly to do_callbacks_message().

This allows the transport-layer peer identity and the application-layer sender identity to become inconsistent.

Suggested fix:

Before dispatching a received message, verify that:

  • The message originates from an established peer.
  • source_id() belongs to the registered SteamID set of that peer.
  • The destination ID complies with the local recipient and broadcast rules.
  • The peer belongs to the expected AppID and active session.

However, since the relay server itself currently lacks strong peer authentication, these checks would only address internal identity consistency rather than provide complete identity authentication.

5. Insufficient safeguards for public relay server deployment

Severity: High

Location: tools/relay/relay_server.cpp:87–176

5.1. Incomplete room and application isolation

handle_register() removes existing clients with the same primary_id but a different source endpoint.

However, this cleanup does not appear to consider AppID or Room, nor does it verify that the newly registered client legitimately owns the previous session identity.

Consequently, identical SteamIDs used across different games or rooms may interfere with each other.

Client identity should be scoped to the corresponding application, room, and authenticated session.

5.2. Poor scalability of peer discovery and forwarding

Several operations require linear scans over the registered client collection.

The approximate complexity is:

Operation Complexity
Duplicate identity lookup O(N)
Generating a peer list O(N)
Updating peer lists for all clients in a group O(N²) in the worst case
Looking up a forwarding destination O(N)

These operations may become increasingly expensive as the number of registered clients grows.

Consider introducing appropriate indexes based on AppID, Room, and Peer ID.

5.3. Missing resource limits and authentication

The current relay server lacks several safeguards normally expected from a publicly accessible UDP service:

  • Maximum client count.
  • Maximum room population.
  • Registration rate limiting.
  • Traffic rate limiting.
  • Endpoint reachability verification.
  • Session authentication.
  • Confidential transport for room passwords.

Room passwords are currently transmitted through an unencrypted UDP protocol.

These limitations may be acceptable for a small private server operated by trusted users, but they should be addressed before recommending public deployment.

6. Reliable message ordering is not strictly guaranteed across transport switches

Severity: Medium–High

Location: dll/network.cpp:1282–1325

The implementation switches from KCP to LAN TCP when TCP becomes available and relay->is_idle() returns true.

However, is_idle() is based on whether ikcp_waitsnd() returns zero.

A transport-layer acknowledgment does not necessarily mean that the remote application has already processed the acknowledged message.

Although the current ordering of relay and TCP message processing in Run() reduces the likelihood of out-of-order delivery under normal conditions, it does not provide a strict end-to-end ordering guarantee across different transports.

This is particularly relevant during:

  • KCP session resets.
  • TCP disconnections and fallback to KCP.
  • Transport switching with pending application-level messages.
  • Network interruptions and recovery.

Suggested fix:

Consider one of the following approaches:

  1. Keep the selected reliable transport fixed for the lifetime of a logical connection, and establish a new connection when changing transports.
  2. Introduce transport-independent message sequence numbers and an explicit transport-switch synchronization mechanism.

For the initial implementation, the first approach would be considerably simpler and easier to validate.

7. Unilateral KCP resets may desynchronize peers

Severity: Medium–High

Location: dll/relay_client.cpp:156–184

When an invalid frame length is encountered, read_kcp() directly calls create_kcp(peer) to recreate the local KCP instance.

However, the KCP conversation ID is derived from the session IDs of both peers. Recreating the local KCP instance does not change these session IDs.

As a result, the local and remote KCP instances may retain the same conversation ID while maintaining incompatible protocol states.

The local instance resets its sequence numbers and clears its queues, whereas the remote instance may continue using the previous sequence numbers and retransmitting old packets.

This may prevent the connection from recovering correctly and may also discard previously queued reliable messages.

Suggested fix:

Introduce an explicit session reset or reconnection mechanism that ensures both peers discard the previous KCP state and establish a new conversation.

A KCP session should not be silently recreated on only one side without coordinating the reset with the remote peer.

8. KCP allocation failures and send errors are not handled

Severity: Medium–High

Locations:

8.1. Unchecked ikcp_create() return value

ikcp_create() may return NULL if allocation of the KCP control structure or its internal buffer fails.

The current implementation does not check the returned pointer before calling subsequent KCP functions such as ikcp_setoutput().

This may result in a null pointer dereference under memory pressure.

The return value of ikcp_setmtu() should also be checked.

8.2. Ignored ikcp_send() return value

send_kcp_frame() returns void and ignores the return value of ikcp_send().

More importantly, a single application-level frame is divided into multiple ikcp_send() calls.

If one of these calls fails after previous portions have already been queued, the resulting byte stream may contain an incomplete frame.

Since the implementation uses length-prefixed stream framing, a partial write may corrupt the framing of subsequent messages rather than merely cause a single message to be lost.

Suggested fix:

  • Make send_kcp_frame() return an explicit success or failure result.
  • Validate message sizes and queue capacity before enqueueing.
  • Check all relevant KCP return values.
  • Invalidate or explicitly reset the session if a partial enqueue cannot be recovered.
  • Do not report successful delivery or enqueueing to the upper networking layer when the underlying operation has failed.

9. Relay IP allowlist grows indefinitely and has excessive scope

Severity: Medium–High

Location: dll/base.cpp:318–331

The newly introduced static std::set<uint32_t> stores IP addresses that are permitted to bypass LAN-only networking restrictions.

Although access to the set is protected by a mutex, its lifecycle management is incomplete.

Specifically:

  • Entries are inserted but never removed.
  • IP addresses remain permitted after the corresponding peer disconnects.
  • Previously permitted addresses may remain active across AppID or session changes.
  • Permissions are applied at IP address granularity rather than endpoint or socket granularity.

This creates both uncontrolled resource growth and unnecessarily persistent network permissions.

Suggested fix:

Use a session-scoped endpoint allowlist with explicit expiration and removal.

Where possible, restrict the exception to the specific UDP socket or networking component that requires relay functionality, rather than modifying global networking permissions.

10. Excessive per-peer receive buffer limits

Severity: Medium

Location: dll/relay_client.cpp:20

The current maximum frame size is 64 MiB.

read_kcp() continuously appends incoming data to stream_in until a complete frame becomes available.

Since each peer maintains its own receive buffer, aggregate memory consumption may become substantial:

Number of peers Potential buffered payload
1 64 MiB
4 256 MiB
8 512 MiB
16 1 GiB
32 2 GiB

These estimates exclude vector capacity overhead, KCP internal queues, Protobuf parsing, and additional message copies.

Furthermore, std::vector::erase() does not guarantee that previously allocated capacity will be released.

This is particularly concerning for 32-bit game processes with limited virtual address space.

Suggested fix:

  • Establish a reasonable maximum frame size based on the requirements of the supported Steam Networking APIs.
  • Introduce a global receive memory budget.
  • Add a timeout for incomplete frames.
  • Ensure consistent message size limits between the sender and receiver.
  • Consider releasing excessively large retained buffer capacity when appropriate.

11. Blocking DNS resolution and missing endpoint refresh

Severity: Medium

Locations:

The relay hostname is resolved using synchronous getaddrinfo().

The initial resolution occurs during Steam client initialization. Failed resolutions may subsequently be retried during network updates.

Since network->Run() may execute while holding global_mutex, a slow DNS lookup can potentially block unrelated Steam API operations.

Potential consequences include:

  • Increased initialization time.
  • Steam API calls blocking while waiting for global_mutex.
  • Game stalls.
  • Delayed network callback processing.

Additionally, hostname resolution appears to be retried only when no valid endpoint has previously been obtained.

If the relay server changes its public IP address, clients may continue attempting to communicate with the obsolete endpoint.

Suggested fix:

Perform DNS resolution outside the global networking lock, preferably using a dedicated asynchronous resolution mechanism.

Re-resolve the hostname after repeated registration or connectivity failures, and consider trying alternative IPv4 addresses returned by DNS.

12. Review of the unrelated bug fixes

The five independent bug fixes included in this PR appear generally reasonable:

Fix Assessment
Overlay mutex lock-order inversion Correct direction, but requires additional concurrency review
Null pointer dereference when receiving a GAME_INVITE from an unknown friend Reasonable
Infinite recursion in TriggerHapticPulse(uint32) Reasonable; index bounds should also be verified
Null pointer dereference in the legacy SendUserConnectAndAuthenticate() implementation Reasonable; return-value semantics should be verified
Incorrect ImGui popup flags Reasonable and relatively low risk

I would recommend submitting these fixes in separate PRs, since they are largely independent of the relay and NAT traversal functionality.

Additional concern regarding the overlay deadlock fix

Location: overlay_experimental/steam_overlay.cpp:1543–1569

Using std::try_to_lock avoids blocking the rendering thread while it holds overlay_mutex, thereby eliminating the identified circular wait involving global_mutex.

However, settings->get_image() appears to be called after global_mutex has been released.

It should be verified whether the underlying image container has independent synchronization and whether the returned image remains valid if another thread modifies the container.

Otherwise, a potential data race or object lifetime issue may remain.

This is a concern requiring further verification, rather than a confirmed regression.

13. Memory management assessment

I did not identify an obvious conventional memory leak in the normal destruction paths of the reviewed relay-related objects.

The relevant resources appear to be released through:

  • Destruction of Relay_Client.
  • std::unique_ptr ownership of peer objects.
  • ikcp_release().
  • freeaddrinfo().
  • Socket cleanup.
  • Destruction of per-peer receive buffers.

However, the absence of a conventional memory leak does not imply that the implementation is free of memory-related issues.

The following concerns remain more significant:

  • Unbounded KCP send queue growth.
  • Excessive receive buffer limits.
  • Permanent growth of the IP allowlist.
  • Unchecked allocation failures.
  • Stream corruption following partial enqueue failures.
  • Delayed cleanup of stale connections.

These issues are particularly relevant to long-running sessions, unstable networks, and 32-bit game processes.

14. Recommended additional testing

Before merging, I would recommend covering the following scenarios:

  • Abrupt termination of a remote game process.
  • Relay server shutdown and restart during an active session.
  • Network interface changes and NAT endpoint changes.
  • Sustained packet loss, high latency, and complete network interruption.
  • Multiplayer sessions involving 4, 8, and 16 players.
  • Repeated transitions between LAN TCP and KCP.
  • Identical SteamIDs registered under different AppIDs and rooms.
  • Invalid frame lengths and incomplete message streams.
  • Regression testing of existing LAN networking with relay functionality disabled.
  • Long-running x86 Debug and Release builds.
  • KCP allocation failures and send queue exhaustion.
  • Linux runtime testing.

Reliable message ordering, duplication, loss, connection recovery, callback behavior, and aggregate memory consumption should be explicitly verified.

Final recommendation

I would recommend splitting this PR into several independently reviewable changes:

  1. The five unrelated bug fixes.
  2. KCP integration and the relay protocol implementation.
  3. NAT hole punching, connection lifecycle management, and transport switching.
  4. Relay server tooling, overlay integration, CI, and packaging.

The primary concerns with this PR are not related to C++ syntax or coding style, but rather to the correctness and robustness of the networking protocol.

The implementation may work well in normal two-player sessions with relatively stable network conditions. However, its behavior under disconnections, reconnections, multiple concurrent peers, memory pressure, and untrusted network traffic requires further attention.

I would strongly recommend addressing issues 1–8 before merging the relay functionality into the main development branch.

Review limitations: This review is based on static inspection of the PR, the corresponding source files, and the bundled KCP implementation. I was unable to retrieve the complete unified diff, so this is not an exhaustive line-by-line review of all 32 changed files. I have not independently compiled or executed the implementation. The runtime consequences described above are therefore based on source-level analysis rather than independently reproduced failures.

Mayo0x0 and others added 6 commits December 1, 2026 13:01
Adds a small relay server (tools/relay, built as tool_relay) and a relay
client in the emulator so players can connect over the internet without
port forwarding:

- the emulator registers at the relay (steam ids, appid, optional room and
  password) and learns its public address and the other players of the
  same game/room
- traffic starts through the relay immediately while both sides UDP hole
  punch (public + local address); once that works it switches to the
  direct path, and falls back to the relay if the direct path dies
- reliable messages use KCP (libs/kcp, MIT, v1.7) in stream mode with the
  same length-prefixed framing as the LAN TCP path; small unreliable
  packets are sent as plain UDP datagrams
- everything shares the emulator's UDP socket, relay packets start with
  'GBR' so LAN packets stay compatible; LAN connections keep priority
- relay/peer addresses are allowed through the LAN-only network hooks
- config: [main::connectivity] relay_server / relay_room / relay_password
- GBE_RELAY_FORCE_RELAY=1 disables hole punching for diagnostics

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…type in overlay

- Networking now keeps one transport per peer for reliable messages
  (LAN TCP or relay/KCP). Switching from KCP to TCP only happens once all
  KCP data was acknowledged, so a message sent over TCP can't overtake an
  earlier one still in flight over KCP. Falls back to KCP if TCP dies.
- Networking::getConnectionType() reports LAN / Direct (hole punched) /
  Relay per user.
- the overlay friends list shows a colored [LAN] / [P2P] / [Relay] tag with
  a tooltip; the value is read in the steam callback thread (global_mutex
  held) and only rendered from the cached copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The user info line in the overlay now shows the relay server, whether
the client is registered (room, public address, peer and P2P counts)
or why not (connecting, rejected, server not resolved).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- build tool_relay in all CI build matrices (win, win vs22, linux, arm)
- package_win.bat / package_linux.sh copy the relay README next to it
- configs.main.EXAMPLE.ini: relay_server example and overlay hint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- peer liveness: Peer_Info::alive is based on recent valid traffic
  (KCP keepalives every 5s) instead of "ever received". relay_ok is
  cleared when a peer is dropped or goes silent, and the user timeout
  counts from the last real packet: a killed peer is now detected after
  the normal 20s user timeout (was ~50s).
- KCP send queue is bounded (4096 segments per peer); a reliable send
  that doesn't fit fails as a whole, like a full Steam send buffer.
- frames are limited to 16 MiB (was 64 MiB) on both sides, the receive
  buffer gives back memory after a big message.
- the direct endpoint is only set by PUNCH/PUNCH_ACK carrying the peer's
  session; other direct packets only refresh it when they come from the
  known endpoint, unreliable direct packets from other endpoints are
  dropped.
- relay messages are only dispatched if their source id belongs to the
  peer they came from.
- a broken KCP stream (bad frame length, partial enqueue) resets the
  session id instead of recreating KCP on one side only, so both sides
  restart in sync via the relay.
- ikcp_create/ikcp_setmtu/ikcp_send results are checked.
- relay DNS resolution runs in the background (Run() holds
  global_mutex), and is repeated when the relay stops answering, so an
  address change of the relay host is picked up.
- relay server: an id re-registering from a new endpoint only replaces
  entries of the same appid and room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mayo0x0 added a commit to Mayo0x0/gbe_fork that referenced this pull request Dec 1, 2026
- peer liveness: Peer_Info::alive is based on recent valid traffic
  (KCP keepalives every 5s) instead of "ever received". relay_ok is
  cleared when a peer is dropped or goes silent, and the user timeout
  counts from the last real packet: a killed peer is now detected after
  the normal 20s user timeout (was ~50s).
- KCP send queue is bounded (4096 segments per peer); a reliable send
  that doesn't fit fails as a whole, like a full Steam send buffer.
- frames are limited to 16 MiB (was 64 MiB) on both sides, the receive
  buffer gives back memory after a big message.
- the direct endpoint is only set by PUNCH/PUNCH_ACK carrying the peer's
  session; other direct packets only refresh it when they come from the
  known endpoint, unreliable direct packets from other endpoints are
  dropped.
- relay messages are only dispatched if their source id belongs to the
  peer they came from.
- a broken KCP stream (bad frame length, partial enqueue) resets the
  session id instead of recreating KCP on one side only, so both sides
  restart in sync via the relay.
- ikcp_create/ikcp_setmtu/ikcp_send results are checked.
- relay DNS resolution runs in the background (Run() holds
  global_mutex), and is repeated when the relay stops answering, so an
  address change of the relay host is picked up.
- relay server: an id re-registering from a new endpoint only replaces
  entries of the same appid and room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Mayo0x0 Mayo0x0 changed the title NAT hole punching with relay server fallback (+ overlay connection info, 5 bug fixes) NAT hole punching with relay server fallback (+ overlay connection info) Dec 1, 2026
@Mayo0x0

Mayo0x0 commented Dec 1, 2026

Copy link
Copy Markdown
Author

Thanks for the review! I went through every point against the code. Changes are in d73992b, and the bug fixes are now a separate PR: #658.

Fixed

  • 1. Stale relay state: liveness now comes from recent valid traffic (KCP keepalives every 5s, so an idle peer still counts). relay_ok is cleared when a peer is dropped or goes silent, and last_received is set to the time of the last real packet, not "now". A killed peer is now detected after the normal 20s USER_TIMEOUT (measured, was ~50s before).
  • 2. Unbounded send queue: at most 4096 KCP segments (~5 MB) waiting per peer. A reliable send that doesn't fit is rejected as a whole and SendP2PPacket returns false, like a full Steam send buffer. Partial frames can't happen.
  • 3. Direct endpoint: only a PUNCH/PUNCH_ACK carrying the peer's session sets the direct endpoint. Direct KCP packets only refresh it when they come from the already known endpoint (and KCP checks the conversation id derived from both sessions). Unreliable direct packets from any other endpoint are dropped.
  • 4. SteamID consistency: relay messages are only dispatched when source_id() belongs to the connection of the peer they came from.
  • 5.1 Isolation: an id re-registering from a new endpoint only replaces entries with the same appid and room.
  • 7. One-sided KCP reset: a broken stream (bad frame length, partial enqueue) now resets the session id. The relay pushes the new session to the others, so both sides recreate KCP with a new conversation id, using the existing restart path.
  • 8. Return values: ikcp_create, ikcp_setmtu and ikcp_send results are checked, and send_kcp_frame() returns success.
  • 10. Frame size: limit is now 16 MiB on both sides (was 64 MiB), and the receive buffer gives its memory back after a big message.
  • 11. DNS: resolution runs in the background (std::async), and Run() only picks up the result. It resolves again when the relay hasn't answered for 30s, so an address change of the relay host is picked up.
  • 12. Bug fixes: split out into Fix overlay deadlock and four crash/assert bugs #658.

Not changed, and why

  • 6. Ordering across transport switches: on the receiving side, ikcp_input() → read_kcp() queues the messages, and run_relay() sends the ACK (ikcp_update) and dispatches those messages right after each other in the same call, under global_mutex. So by the time the sender sees waitsnd == 0, the receiver has already dispatched everything. A TCP message sent after that can't overtake it. The test sends 400 sequenced messages across a relay→LAN switch with 0 ordering errors.
  • 5.2 Scalability: O(N) per register is fine for what this is meant for, a private relay for a group of friends.
  • 5.3 Rate limits / auth / encryption: already listed under limitations in the README. It's meant for a small, private, trusted group, not as a public service.
  • 9. Allowlist: it only holds the relay IP and the IPs of peers the relay reported (a handful). Its purpose is exactly to let the emulator's own traffic to those hosts pass the LAN-only hooks. Removing entries would race with in-flight packets for no real gain.

Tested again after the changes

Two instances + relay locally: hole punching, forced relay, LAN + relay (KCP→TCP switch), 300 KB reliable packet, unreliable packets, 400 sequenced messages with 0 order errors, wrong password, and killing one instance mid-session (detected after 20s). Windows x64 builds, the full CI matrix ran on my fork earlier.

Server:
- index groups (appid + room) and steam ids in hash maps: relaying a
  packet and building a peer list no longer scan all clients
- cookie handshake (CHALLENGE, SipHash of the source address, rotating
  every 30s): a client must receive at its address before it is
  registered, so spoofed sources can't register or get peer lists sent
  to a victim; the challenge is smaller than the request
- per-instance secret auth token: an id can only move to a new address
  with the same token, nobody else can take it over or kick it
- limits: clients in total / per IP / per group, relay bandwidth per
  client (token bucket) and in total, registrations per IP
- non-blocking socket drained in batches, stats line every 60s
- clear rejection of emulators without the new fields

Client:
- answers CHALLENGE, sends cookie and auth token with REGISTER
- the overlay shows the relay's reject reason (room full, relay full,
  id in use, ...)

Measured locally (release build, 3000 clients, groups of 32, 60k relayed
packets/s): 36% of one core, no loss. The previous version needed 81%
and lost 22% of the packets under the same load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Mayo0x0

Mayo0x0 commented Dec 1, 2026

Copy link
Copy Markdown
Author

A follow-up on 5.2 and 5.3. In my first reply I waved them off because I had only my own use case in mind: one small relay for a group of friends. After thinking about it more, I think the relay is much more useful when one instance can serve many players and groups, for example as a community relay anyone can use. With that goal the review is right: linear scans and missing limits are real problems, not details. So I reworked the relay server in 774b973.

5.2 Scalability

  • Groups (appid + room) and all steam ids are indexed in hash maps. Relaying a packet is an O(1) lookup, and a peer list only touches the client's own group, no matter how many clients are connected in total.
  • The socket is non-blocking and drained in batches, and a stats line is logged every 60s (clients, groups, relayed pkt/s and KB/s, drops).

5.3 Limits and authentication (encryption is intentionally still out of scope)

  • Address verification: registration needs a cookie from a CHALLENGE (SipHash of the source address with a random server key, rotating every 30s). A spoofed source can't register, and it can't make the relay send peer lists to a victim either. The challenge is smaller than the request, so there's no amplification.
  • Session authentication: every emulator instance sends a random secret token that is never forwarded to other clients. An id can only move to a new address (NAT rebinding) with the same token, so nobody can take over or kick another player's id.
  • Limits, all configurable: clients in total (--max-clients, 10000), per public IP (--max-clients-per-ip, 64, high enough for carrier NAT), per game + room (--max-group-size, 64), relay bandwidth per client (token bucket, --client-rate, 2 MB/s) and in total (--total-rate), registrations per IP (--register-rate).
  • The client shows the relay's reject reason in the overlay ("room is full", "this id is already in use", ...). An emulator without these changes gets a clear "emulator too old for this relay, please update". A new emulator still works with an old relay.

What it can't change: clients connect full mesh inside a group, so "many players" means many groups (rooms/lobbies), not one huge group. --max-group-size keeps that sane, and the README now says to use rooms.

Measurements (local, release build, load generator on the same machine):

Load New relay Previous relay
3000 clients, groups of 8, 30k relayed pkt/s 17% of one core, 0% loss 55%, 0% loss
3000 clients, groups of 32, 60k relayed pkt/s 36% of one core, 0% loss, 5 MB RAM 81%, 22% loss

Protection checks (all passed): old client rejected with a clear reason, cookie handshake, forged cookie only gets a new challenge, id takeover without the token denied, id move with the token allowed, room limit, per-IP limit, per-client rate limit (measured against the expected token bucket), no relaying across rooms. The two-instance game scenarios (hole punching, forced relay, LAN + relay, 400 sequenced messages) still pass with the new handshake.

Not covered yet: the new server is only built and tested on Windows so far, and the CI run of this PR will be the first Linux build of it.

@LuKeSt0rm

LuKeSt0rm commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Teardown: I'd like to note that you should definitely test this with 3 or more players.
Because the current dev branch clearly shows issues with connecting and dead sessions especially with Teardown. (seems to be a good test candidate for this issue)
You can read more about it here #650 (i'm working on fixing it)

How to test/reproduce
One player hosts and two join, then the host exits. Another joiner hosts and the other joins, former host last.

@Mayo0x0

Mayo0x0 commented Dec 2, 2026

Copy link
Copy Markdown
Author

Thanks for the heads-up and the repro steps!

This PR doesn't touch the lobby/session logic, only the transport underneath (hole punching with relay fallback). The relay state is kept per game instance, not per lobby, and it's only active when a relay server is configured. A pure LAN setup like the one in #650 doesn't use it at all. A restarted peer is detected by its new session id and the connection is rebuilt on both sides.

I'll still run your scenario with 3 players, once with the relay disabled as a baseline and once with it enabled, and report back. Once your fix for #650 lands on dev, I'll rebase and test again.

@Mayo0x0

Mayo0x0 commented Dec 2, 2026

Copy link
Copy Markdown
Author

Follow-up on the 3-player test: I ran your scenario with 3 Teardown instances on one PC, once with the relay disabled as a baseline and once with it enabled.

The former host failed to rejoin in both runs, so it isn't caused by this PR. The logs pointed to the lobby and session handling on dev (rejoin loop after the owner leaves, messages delivered before the session was accepted, stale messages kept after a peer ended the session). I fixed those on a separate branch and described them in #650:
#650 (comment)

With those fixes applied on top of this PR, the scenario works in both modes: host leaves, another player hosts, the others and the former host join without restarting. With the relay enabled, all three instances registered and connected directly to each other.

Not tested on separate PCs or across NATs yet; I'll report back once I have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants