Skip to content

Networking and security

Requirements

  • Up to four players per game against an authoritative server: the server decides, clients display and send inputs.
  • UDP for everything in game (imposed); TCP only with a strong justification.
  • A binary protocol, documented so that someone can write a new client from the RFC.
  • A multithreaded server that never blocks on a client and survives any client crash or malformed packet.
  • Playable with 150 ms latency, 2 % loss or duplication, and a 5 KB/s bandwidth cap.

Transport

Transport Behaviour Fit
UDP (chosen for gameplay) Datagrams, no ordering, no retransmission, no head-of-line blocking A lost position is replaced by the next snapshot 50 ms later; waiting for it would freeze every newer update
TCP Ordered reliable stream A single lost segment stalls all later data until retransmitted: fatal for real-time positions
TCP for the login only (chosen) One short exchange before the game Login needs reliability and is not time-critical. TCP gives it for free and lets the server issue a session token before any UDP traffic is accepted; it carries no in-game data.
QUIC Reliable and unreliable streams over UDP Excellent, but heavy libraries and a lot of protocol we would not use

Networking library

Option Assessment
Standalone Asio (chosen) Header-only, cross-platform (epoll, kqueue, IOCP), asynchronous UDP and TCP, timers; allowed by the subject; we still design the whole protocol (in place: net::UdpSocket, net::TcpConnection and net::TcpListener, Asio kept private to the module)
BSD sockets / Winsock directly Two code paths to maintain and wrap; error-prone non-blocking I/O
ENet, yojimbo, GameNetworkingSockets Provide reliability, fragmentation and sessions: the very parts the project asks us to design, and harder to document as our own protocol

Protocol design

  • Binary and explicit (serializer in place: net::BinaryWriter and net::BinaryReader; RFC sections 1 and 2 in place, the message sections planned): fixed-size little-endian fields written field by field, never by copying structs, so padding and compiler layout never reach the wire and Windows, Linux and macOS clients agree. Every read is checked against the remaining bytes and fails instead of reading past the end; the first failure sticks, so a truncated packet is never half-parsed.
  • Header on every datagram (in place: net::PacketHeader, RFC section 2): magic number, protocol version, message type, sequence number, acknowledgement and ack bitfield, session id. A wrong magic or version is dropped immediately.
  • Inputs, not positions, from clients: a compact bitmask per tick. The server cannot be told "I am here", only "I pressed up", which removes a whole class of cheating.
  • Snapshots from the server at 20 Hz; clients interpolate remote entities between the two latest snapshots to hide the low rate and jitter.
  • Reliable events over UDP (in place: net::ReliableChannel, RFC section 5): spawns, deaths and disconnections must arrive. Every datagram acknowledges the peer's with the last sequence received plus a 32-bit bitfield of the previous ones; the sender resends the events of unacknowledged datagrams after a timeout, and the receiver drops the copies by event id. This is the approach popularised by Glenn Fiedler's articles: no extra connection, and acknowledgements ride on traffic that is sent anyway.
  • Sequence numbers on 16 bits with wrap-around comparison (RFC 1982 serial number arithmetic, in place: net::sequence_greater_than()), so the counter can wrap during long games without reordering bugs.
  • Datagrams of at most 1200 bytes, below common path MTUs, to avoid IP fragmentation (a lost fragment loses the whole datagram).

Threading

  • Network thread + game thread (in place: net::NetworkThread, core::SpscQueue): Asio runs on its own thread; the simulation runs at a fixed 60 Hz on another. They exchange messages through single-producer single-consumer lock-free queues, so the simulation never waits on a socket and a slow client cannot stall the tick.
  • Alternatives: one thread per client (does not scale, needs locks around the world state); everything on one thread with non-blocking sockets (simple but couples the tick rate to network activity).

Data transmission

A snapshot first sent every entity whole, 22 bytes each with f32 positions and velocities: about 1 KB, 20 times a second, to each player. Four techniques reduce it; each was measured on the same game, so their gains and costs can be compared.

Method. A seeded 30-second game of R-Type (4 players firing, the first stage's waves), 600 snapshots of 46.1 entities on average, each encoded every way; payload bytes for one client, headers excluded. Times per snapshot with Clang 20 at -O2 on a Ryzen 5 7640U, the encoders of the game (rtype/snapshot.hpp, rtype/delta_snapshot.hpp) and of the engine (net/compression.hpp). The live game was also measured by the network benchmark (4 bots, lan profile, every datagram with its header, events included).

Payload Bytes per snapshot Bytes per second With LZ4 Encode Decode
Byte-aligned, f32 fields (the first layout) 1081.9 21,638 12,662 (-41.5 %) 1.3 µs
Packed bit by bit and quantized 465.5 9,310 8,881 (-4.6 %) 3.1 µs 2.0 µs
Delta against the snapshot before 257.9 5,158 5,158 (-0.0 %) 5.8 µs 5.5 µs
Delta against the snapshot two before 264.6 5,292 5,292 (-0.0 %) 5.8 µs 5.5 µs

The byte-aligned layout needs 852 datagrams for the 600 snapshots (51 records each at most), the others one per snapshot (about 120 records). LZ4 compresses a payload in 0.56 µs and decompresses it in 0.06 µs.

Technique Gain Cost Status
Bit packing (RFC 1.4, net::BitWriter): each field on the bits it needs, ids as an index gap (varint) and an 8-bit generation, kind on 3 bits, frame on 4 25 of the 99 bits saved per record: id, kind and frame from 48 bits to about 23 Encoding 2.4 times slower than byte-aligned writes (3.1 µs against 1.3 µs per snapshot), still negligible at 20 Hz; a bit reader to fuzz (tools/fuzz.sh bits); unreadable in a hex dump without the RFC tables in place
Quantization (RFC 4.3): positions to 1/8 px on 15 bits, velocities to 1 px/s on 12 bits The other 74 bits saved per record. With packing, 176 bits become 77: 1081.9 to 465.5 bytes per snapshot (-57 %); in the live game, 13,889 to 7,068 bytes per second per bot (-49 %) Precision: 1/16 px and 0.5 px/s at most, below half a pixel once drawn; positions clamped to -2048 to 2047.875 and velocities to ±2048, so a world larger than that needs more bits in place
Delta compression (RFC 4.8): each client gets only what changed since the latest snapshot it acknowledged 465.5 to 257.9 bytes per snapshot (-45 %) with a baseline one snapshot old, 264.6 (-43 %) two old: the age of the baseline, so the latency, barely matters The server encodes for each client (5.8 µs per snapshot and client) and keeps its last 32 snapshots; the client keeps 32 too and rebuilds (5.5 µs); a client that misses its baseline drops deltas until the server falls back on an older one; the RFC section and the decoder are the most intricate code of the protocol in place (project-rtype#60, #62)
General-purpose compression, LZ4 on whole payloads (RFC 2.6) -41.5 % on the byte-aligned layout, whose f32 fields repeat; only -4.6 % once packed, nothing on deltas. Live game: 7,068 to 6,860 bytes per second per bot (-2.9 %), within the spread between two runs A dependency (LZ4, 1.10.0, built into net), 0.56 µs per payload, a header flag, a decompressor in front of every parser, so more to fuzz; a peer that does not compress is unaffected in place (#432), off by default in the game (project-rtype#63)

Conclusions.

  • Packing and quantization come first: they halve every snapshot for almost no CPU and a precision loss no player can see.
  • Delta compression is the next big step, and the costliest in code and memory; it pays as long as most entities move little between two snapshots, which holds in a shoot'em up where enemies follow scripted paths.
  • A general-purpose compressor only helps a redundant encoding. Once the data is packed and sent as deltas, there is nothing left for LZ4 to find, so the game keeps it off; it stays available to a game whose payloads are byte-aligned or textual.

Security

Threat Countermeasure
Malformed or truncated packets crashing the parser Every read is bounds-checked against the remaining bytes and returns an error instead of reading past the buffer; lengths are validated before allocation; unknown types are dropped
Oversized packets exhausting memory Fixed maximum datagram size; no allocation proportional to an untrusted length beyond that limit; a TCP peer announcing a message over 4096 bytes is disconnected before anything is allocated (in place: net::TcpConnection)
Spoofed or foreign UDP traffic UDP is accepted only from the endpoint bound to a session token obtained through the TCP login; other datagrams are dropped
Flooding a server Per-IP packet rate limit; excess is dropped and logged, so the tick rate is unaffected
Cheating clients Server authority: clients send inputs only; movement, firing cooldowns, collisions and scores are computed on the server
One faulty client taking the server down Per-client error isolation: an exception while handling one client is caught and that client is disconnected
Vulnerable or tampered dependencies Dependencies pinned by version, commit or SHA-256 (CPM); GitHub Actions pinned by commit SHA

Detection and long-term monitoring

  • Fuzzing the packet parser and the bit reader with libFuzzer (in place: tests/fuzz/packet_fuzz.cpp and tests/fuzz/bits_fuzz.cpp, a minute each on every pull request, 10 minutes with tools/fuzz.sh) and dedicated malformed-packet unit tests (in place: tests/net/malformed_packet_test.cpp).
  • AddressSanitizer and UndefinedBehaviorSanitizer on every pull request (in place), catching memory errors before they ship.
  • Static analysis with clang-tidy (bugprone, cert, cppcoreguidelines...) on every pull request (in place).
  • Server logs (planned): rejected packets, rate-limit hits and disconnections are logged with the source endpoint, so abuse is visible after the fact.
  • Degraded-network tests with netem (Linux) or clumsy (Windows) (in place: tools/netem.sh, Test on a degraded network): loss, duplication, 150 ms latency and 5 KB/s cap, as the subject requires.

Security of the lobby, chat and admin console (Part 2)

Part 2 opens three new doors: the lobby (rooms over TCP), the chat between players, and the admin console of the server. Each keeps the rules above: the server checks everything it receives, and a bad request is refused or ends its session, never the server.

Threat Countermeasure
Room spam: a client creating rooms until none is left 64 rooms at most, NoRoomLeft beyond; a room created empty is freed when its last session leaves (in place: SessionTable, RFC 3.6)
Bad names and rules of rooms The name follows the rules of player names (1 to 16 bytes of UTF-8, no control character), each rule its range; the first bad value gets its reason, the connection going on (in place: RFC 3.6)
Impersonation in the lobby A name is unique on the server (NameTaken), and the server, not the client, puts the sender's name and number in each relayed message (in place for rooms; in progress for the chat: Aegis2D-Dev/project-rtype#93)
Chat flood 5 messages at once, then 1 per second per session; beyond, refused with TooFast and not relayed, so a flooder only floods itself (in progress: ChatRate, RFC 3.8)
Long or binary chat texts 200 bytes at most, UTF-8 without control characters, refused with their reason; TCP messages over 4096 bytes close the connection before anything is read (RFC 3.8, 1.3)
Log or terminal injection through texts Names are checked before they reach a log; chat texts are never logged, and refused messages only at debug level, so a flood does not become a flood of log lines
Messages reaching the wrong players A chat message goes to the sender's room only, or to the lobby; game traffic never leaves its room (in place: rooms, RFC 3.6)
Abusive players kick and ban from the admin console, a ban kept on disk and checked at the login (planned: #311)
Admin console reached from the network The console reads the standard input of the server process only: using it needs access to the machine that runs the server, and no admin command travels over the network, so there is no password to guess (planned: #310, on the engine's command system)
Wrong admin commands Each command is parsed by the engine's command system, and a wrong one says why without doing anything (planned: #310)
Scores and bans files tampered with or corrupted Validated on read, reported and never fatal, written atomically (see Storage)

Why no remote administration: an admin console over the network would need authentication, encryption (TLS) and protection against password guessing, a whole new attack surface for a game server that runs next to its operator. The standard input, or a terminal multiplexer such as tmux for a server left running, gives the same commands with the operating system's own access control. A remote console stays possible later, behind SSH.