Repository navigation
Conversation
|
Since you've used Claude to code, I think it is ok to use ChatGPT to review it. Code Review — PR #657Review 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 1. Stale relay connection state and incorrect timeout handlingSeverity: High Location: dll/network.cpp:875–913 In However, Additionally, when Potential consequences include:
Suggested fix: Maintain a per-peer timestamp such as The A historical boolean flag should not be used as a connection liveness indicator. 2. Unbounded KCP send queue growthSeverity: High Location: dll/relay_client.cpp:140–153 Related functions:
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 Furthermore, the implementation does not check the KCP Potential consequences include:
This is not a conventional memory leak, but rather uncontrolled memory growth caused by missing resource limits. Suggested fix:
3. Invalid packets can modify the direct connection endpointSeverity: High Location: dll/relay_client.cpp:256–297 Function: In the KCP packet handling branch, As a result, the following connection state may be modified before the packet has been successfully validated:
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 4. Missing SteamID consistency validation in relay messagesSeverity: High Location: dll/network.cpp:902–912
The current implementation checks whether the Protobuf message can be parsed and whether The message is subsequently passed directly to 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:
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 deploymentSeverity: High Location: tools/relay/relay_server.cpp:87–176 5.1. Incomplete room and application isolation
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 forwardingSeveral operations require linear scans over the registered client collection. The approximate complexity is:
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 authenticationThe current relay server lacks several safeguards normally expected from a publicly accessible UDP service:
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 switchesSeverity: Medium–High Location: dll/network.cpp:1282–1325 The implementation switches from KCP to LAN TCP when TCP becomes available and However, 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 This is particularly relevant during:
Suggested fix: Consider one of the following approaches:
For the initial implementation, the first approach would be considerably simpler and easier to validate. 7. Unilateral KCP resets may desynchronize peersSeverity: Medium–High Location: dll/relay_client.cpp:156–184 When an invalid frame length is encountered, 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 handledSeverity: Medium–High Locations: 8.1. Unchecked
|
| 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_ptrownership 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:
- The five unrelated bug fixes.
- KCP integration and the relay protocol implementation.
- NAT hole punching, connection lifecycle management, and transport switching.
- 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.
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>
73be12c to
d73992b
Compare
- 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>
|
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
Not changed, and why
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>
|
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
5.3 Limits and authentication (encryption is intentionally still out of scope)
What it can't change: clients connect full mesh inside a group, so "many players" means many groups (rooms/lobbies), not one huge group. Measurements (local, release build, load generator on the same machine):
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. |
|
Teardown: I'd like to note that you should definitely test this with 3 or more players. How to test/reproduce |
|
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. |
|
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: 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. |
Summary
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 projecttool_relay)gbe_relay_x64/gbe_relay_x32, Windows + Linux), one UDP port (default27999).--port,--password(optional),--verbose, plus limits:--max-clients,--max-clients-per-ip,--max-group-size,--client-rate,--total-rate,--register-rate.Relay client in the emulator
libs/kcp) in stream mode with the same length-prefixed framing as the LAN TCP path; small unreliable packets are plain UDP datagrams.GBR(can't be a valid protobuf), so it's compatible with clients without relay config.GBE_RELAY_FORCE_RELAY=1disables hole punching (diagnostics).Config –
configs.main.iniEmpty
relay_server(default) = feature off, no behavior change. Documented inconfigs.main.EXAMPLE.iniandtools/relay/README.md.Overlay (experimental)
[LAN]/[P2P]/[Relay]per friend (colored, with tooltip).global_mutexheld) and only rendered from a cached copy.Build / packaging
tool_relayadded to all CI build matrices andbuild_win_premake.bat; package scripts copy the README next to it (tools/relay/README.relay.md).CREDITS.md.Review follow-up
Related
Testing
tool_relayon Win/Linux/ARM): https://github.com/Mayo0x0/gbe_fork/releases/tag/release-2026_12_01-relay[LAN]), and one PC on a mobile hotspot behind carrier CGNAT (hole punching impossible →[Relay], game played fine).Limitations
--max-group-size).🤖 Generated with Claude Code