Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
fix(relay): verified sessions, 64-bit ids, per-IP limits
Olcay Seygan64015eec7572
diff --git a/GeneralsMD/Code/Tools/relay/README.md b/GeneralsMD/Code/Tools/relay/README.mdindex 23bc75c5f..e142a7750 100644--- a/GeneralsMD/Code/Tools/relay/README.md+++ b/GeneralsMD/Code/Tools/relay/README.md@@ -16,7 +16,13 @@ node test.js # self-check, exit code 0 on pass```Tested on Node 22. The relay listens on every interface; open the UDP port in the firewall and that-is the whole deployment.+is the whole deployment. Give it a machine that is not also running the game flat out: two uncapped+copies on the same PC starved it for up to 69 seconds at normal priority, and every match through it+stalled.++The game side is `-relay host:port`. Entering the LAN screen waits up to five seconds for the+relay's WELCOME, with the screen frozen, and a relay that never answers is reported as a network+socket error; the next try waits ten more seconds.It prints one line per join and leave, with the room and the virtual address, and once a minute acounter line:@@ -27,15 +33,16 @@ counter line:2026-11-06T08:52:10.000Z leave room=1a2b3c4d:5e6f7a8b vip=10.0.0.3 reason=idle```-A leave says why: `idle` (30 seconds without a packet), `replaced` (a new session came from the-same address and port, which is a restarted game), or `version changed` (a hello for a known-session with different CRCs).+A leave says why: `idle` (120 seconds without a packet) or `version changed` (a HELLO carrying a+known session with different CRCs). A two-player match moves about 290 KB a minute each way per+player through it.## Wire formatUDP, one message per datagram. Integers are big-endian. Every packet starts with the two bytes`Z` `R` (0x5A 0x52) and a type byte. No datagram may exceed 1400 bytes; larger ones are dropped,-which leaves 1385 bytes of payload in a client's DATA.+which leaves 1381 bytes of payload in a client's DATA. A session is 8 opaque bytes the relay picks+at random; all zeros means none.HELLO, type 1, client to relay:@@ -45,17 +52,18 @@ HELLO, type 1, client to relay:| 2 | 1 | 1 || 3 | 4 | exeCRC || 7 | 4 | iniCRC |-| 11 | 4 | session, 0 on the first hello |-| 15 | 0..32 | player name, UTF-8, may be empty (longer is cut at 32 bytes) |+| 11 | 8 | session, zeros on the first hello |+| 19 | 4 | wantVip, the address asked for, 0 for any |+| 23 | 0..32 | player name, UTF-8, may be empty (longer is cut at 32 bytes) |-WELCOME, type 2, relay to client, sent in answer to every HELLO:+WELCOME, type 2, relay to client, sent in answer to every HELLO it accepts:| Offset | Size | Field ||---|---|---|| 0 | 2 | `ZR` || 2 | 1 | 2 |-| 3 | 4 | session |-| 7 | 4 | vip, the client's virtual IPv4 address (10.x.y.z) |+| 3 | 8 | session, the one to use from now on |+| 11 | 4 | vip, the client's virtual IPv4 address (10.x.y.z) |DATA, type 3, client to relay:@@ -63,11 +71,11 @@ DATA, type 3, client to relay:|---|---|---|| 0 | 2 | `ZR` || 2 | 1 | 3 |-| 3 | 4 | session |-| 7 | 4 | dstVip, 0xFFFFFFFF for broadcast |-| 11 | 2 | dstPort |-| 13 | 2 | srcPort, the sender's own logical port |-| 15 | .. | payload |+| 3 | 8 | session |+| 11 | 4 | dstVip, 0xFFFFFFFF for broadcast |+| 15 | 2 | dstPort |+| 17 | 2 | srcPort, the sender's own logical port |+| 19 | .. | payload |DATA, type 3, relay to client:@@ -80,29 +88,53 @@ DATA, type 3, relay to client:| 9 | 2 | dstPort || 11 | .. | payload |-The relay never reads the payload.+The relay never reads the payload. A WELCOME is smaller than the HELLO it answers, so a HELLO from a+forged address gets nothing bigger back.## Sessions and rooms-A HELLO with session 0, or with a session the relay does not know, opens a new session with a-fresh random session number and the next free virtual address. A HELLO carrying a live session and-the same two CRCs keeps both, so the game should send HELLO every 10 seconds or so as its-keepalive and to learn its address after a reconnect. The session number is the only credential:-any packet carrying a valid one is accepted from whatever address it arrives from, and replies go-to that address from then on. That is how a NAT that rebinds the client's port stays connected.-Keep the session number out of logs and screenshots.+A HELLO with no session from an address and port that do not hold one opens a session: a random+8-byte session number and a virtual address, wantVip when it is a 10.x.y.z address, not .0 or .255,+that no session holds, the next free one otherwise. The lobby asks for nothing at first and for the+address it has on every HELLO after, so a relay that restarted or forgot it gives the same address+back if it is still free. A `-netgame` run asks from the start, because its slot list names every+copy's address up front, so `-netgame 10.0.0.1,10.0.0.2 -netslot n -relay host:port` plays a+scripted match through the relay (`net_check.py --relay`).++A HELLO with no session, or one the relay does not know, from an address and port that already hold+a session gets that session back when the CRCs match and nothing when they do not. The game resends+HELLO every 500 ms until it hears a WELCOME, and on a slow link the second one arrives first; and a+forged HELLO from someone's address cannot end their session.++Nothing is forwarded to a session until a packet carrying its number has come back from its address.+The number only ever goes out in a WELCOME to that address, so a session opened by a HELLO with a+forged source address is never sent anything. The game answers its first WELCOME with a second HELLO+at once, and says HELLO every 10 seconds after that as its keepalive.++Only a HELLO moves a session to another address and port, which is what NAT rebinding looks like.+The session gets a new number in the WELCOME to the new address, and is forwarded to again once that+number comes back, so a session can be moved only by whoever reads the new address. A session is+never moved onto an address another session holds. DATA from any address other than the session's+own is dropped. Keep the session number out of logs and screenshots all the same.The room is the (exeCRC, iniCRC) pair, which is what the game's own LAN join already insists on.Broadcast goes to every other session in the sender's room. Unicast to an address in another room,or to one that does not exist, is dropped.-A session with no packet for 30 seconds is removed and its address can be handed out again. The-relay holds at most 4096 sessions.+A session with no packet for 120 seconds is removed and its address can be handed out again. The+game says HELLO every 10 seconds, but only while it pumps its network, and a map load can block+for a while between two pumps; two minutes outlasts that.++## Limits-## Rate limit+The relay holds at most 4096 sessions, 8 opened from one IP address and 16 in one room.-Each source address and port has a token bucket in bytes: 2 MiB of burst, refilled at 512 KiB a-second. A packet costs its length, and never less than 64 bytes, so a flood of tiny packets runs+Each source IP address has a token bucket in bytes: 2 MiB of burst, refilled at 512 KiB a second.+A HELLO costs its length, a DATA its length for every copy the relay sends, and neither less than 64+bytes a copy, so a broadcast to fifteen players costs fifteen sends and a flood of tiny packets runsdry as fast as one of big ones. The burst is sized for a map transfer, which is the only time the-game sends much; a lobby and a match sit far under the refill rate. Packets over the limit are-dropped and counted in the `dropped` figure. The numbers are constants at the top of `relay.js`.+game sends much; a lobby and a match sit far under the refill rate. Players behind one carrier NAT+share an address and so a bucket. At most 65536 buckets are kept, and a new address is dropped+while the table is full; a bucket left alone long enough to fill up again is forgotten. Packets over+any limit are dropped and counted in the `dropped` figure. The numbers are constants at the top of+`relay.js`.diff --git a/GeneralsMD/Code/Tools/relay/relay.js b/GeneralsMD/Code/Tools/relay/relay.jsindex 72e38c01a..11afbdfef 100644--- a/GeneralsMD/Code/Tools/relay/relay.js+++ b/GeneralsMD/Code/Tools/relay/relay.js@@ -12,16 +12,21 @@ const T_HELLO = 1;const T_WELCOME = 2;const T_DATA = 3;const BROADCAST = 0xffffffff;+const NO_SESSION = '0000000000000000';const DEFAULT_PORT = 8094;const MAX_PACKET = 1400; // bytes, whole datagram, either direction-const HELLO_HEADER = 15; // magic(2) type(1) exeCRC(4) iniCRC(4) session(4)-const DATA_IN_HEADER = 15; // magic(2) type(1) session(4) dstVip(4) dstPort(2) srcPort(2)+const HELLO_HEADER = 23; // magic(2) type(1) exeCRC(4) iniCRC(4) session(8) wantVip(4)+const WELCOME_SIZE = 15; // magic(2) type(1) session(8) vip(4)+const DATA_IN_HEADER = 19; // magic(2) type(1) session(8) dstVip(4) dstPort(2) srcPort(2)const DATA_OUT_HEADER = 11; // magic(2) type(1) srcVip(4) srcPort(2) dstPort(2)const MAX_NAME = 32; // bytes of UTF-8-const IDLE_MS = 30000; // a session silent this long is dropped+const IDLE_MS = 120000; // a session silent this long is dropped; outlasts one long blocking step of a map loadconst MAX_SESSIONS = 4096;-const RATE_BYTES_PER_SEC = 512 * 1024; // sustained, per source endpoint+const MAX_SESSIONS_PER_IP = 8; // one host cannot take the whole table+const MAX_ROOM = 16; // a broadcast reaches at most 15 others+const MAX_BUCKETS = 65536; // rate limit entries; new source addresses are dropped while it is full+const RATE_BYTES_PER_SEC = 512 * 1024; // sustained, per source IPconst BURST_BYTES = 2 * 1024 * 1024; // a map transfer goes out in one burstconst PACKET_COST_MIN = 64; // a tiny packet still costs this much, so floods of them drain the bucketconst SWEEP_MS = 5000;@@ -35,17 +40,28 @@ function createRelay(opts = {}) {const log = opts.log || ((line) => console.log(`${new Date().toISOString()} ${line}`));const rate = opts.rateBytesPerSec ?? RATE_BYTES_PER_SEC;const burst = opts.burstBytes ?? BURST_BYTES;+ const maxPerIp = opts.maxPerIp ?? MAX_SESSIONS_PER_IP;+ const maxRoom = opts.maxRoom ?? MAX_ROOM;+ const maxBuckets = opts.maxBuckets ?? MAX_BUCKETS;+ const bucketFullMs = (burst / rate) * 1000; // an untouched bucket is full again after this, as good as newconst sock = dgram.createSocket('udp4');- const sessions = new Map(); // session id -> session+ const sessions = new Map(); // session id (16 hex digits) -> sessionconst byVip = new Map(); // vip -> sessionconst byEndpoint = new Map(); // "ip:port" -> session- const buckets = new Map(); // "ip:port" -> { tokens, at }+ const rooms = new Map(); // "exe:ini" -> Set of sessions+ const perIp = new Map(); // ip that opened them -> session count+ const buckets = new Map(); // source ip -> { tokens, at }const stats = { pktIn: 0, bytesIn: 0, pktOut: 0, bytesOut: 0, dropped: 0 };let nextVip = 1;let timers = [];- function allocVip() {+ // A client may ask for an address (a -netgame slot list names each copy's, and a client whose+ // session was forgotten asks for the one it had); it gets it when it is a usable 10.x.y.z nobody+ // holds, the next free one otherwise.+ function allocVip(want) {+ const low = want & 255;+ if (want >>> 24 === 10 && low !== 0 && low !== 255 && !byVip.has(want)) return want;for (let i = 0; i < 0xffffff; i++) {const n = nextVip;nextVip = nextVip >= 0xfffffe ? 1 : nextVip + 1;@@ -59,18 +75,20 @@ function createRelay(opts = {}) {function newSessionId() {for (;;) {- const id = crypto.randomBytes(4).readUInt32BE(0);- if (id !== 0 && !sessions.has(id)) return id;+ const id = crypto.randomBytes(8).toString('hex');+ if (id !== NO_SESSION && !sessions.has(id)) return id;}}- function allow(key, len) {+ function allow(ip, cost) {const t = now();- let b = buckets.get(key);- if (!b) buckets.set(key, (b = { tokens: burst, at: t }));+ let b = buckets.get(ip);+ if (!b) {+ if (buckets.size >= maxBuckets) return false;+ buckets.set(ip, (b = { tokens: burst, at: t }));+ }b.tokens = Math.min(burst, b.tokens + ((t - b.at) * rate) / 1000);b.at = t;- const cost = Math.max(len, PACKET_COST_MIN);if (b.tokens < cost) return false;b.tokens -= cost;return true;@@ -86,77 +104,108 @@ function createRelay(opts = {}) {sessions.delete(s.id);byVip.delete(s.vip);if (byEndpoint.get(s.key) === s) byEndpoint.delete(s.key);+ const members = rooms.get(s.room);+ members.delete(s);+ if (!members.size) rooms.delete(s.room);+ const n = perIp.get(s.ip) - 1;+ if (n) perIp.set(s.ip, n); else perIp.delete(s.ip);log(`leave room=${s.room} vip=${vipString(s.vip)} reason=${reason}`);}- // One endpoint belongs to one session. A session moving to a new endpoint is NAT rebinding;- // a session already sitting on that endpoint is a restarted client and goes.- function bind(s, rinfo, key) {- if (s.key === key) return;+ function place(s, rinfo, key) {if (byEndpoint.get(s.key) === s) byEndpoint.delete(s.key);- const other = byEndpoint.get(key);- if (other && other !== s) remove(other, 'replaced');s.key = key;s.address = rinfo.address;s.port = rinfo.port;byEndpoint.set(key, s);}+ function create(exe, ini, want, name, rinfo, key) {+ const room = `${hex(exe)}:${hex(ini)}`;+ const members = rooms.get(room) || new Set();+ if (sessions.size >= MAX_SESSIONS || (perIp.get(rinfo.address) || 0) >= maxPerIp || members.size >= maxRoom) return null;+ const vip = allocVip(want);+ if (!vip) return null;+ const s = { id: newSessionId(), vip, exe, ini, room, name, ip: rinfo.address, key: null, seen: 0, verified: false };+ sessions.set(s.id, s);+ byVip.set(vip, s);+ rooms.set(room, members.add(s));+ perIp.set(s.ip, (perIp.get(s.ip) || 0) + 1);+ place(s, rinfo, key);+ log(`join room=${room} vip=${vipString(vip)} name=${JSON.stringify(name)}`);+ return s;+ }++ /* A session is forwarded to only once a packet carrying its id came back from its endpoint, and the+ id only ever goes out in a WELCOME to that endpoint. A HELLO with a forged source address therefore+ opens a session nothing reaches, and the relay cannot be aimed at someone else. */function hello(msg, rinfo, key) {const exe = msg.readUInt32BE(3);const ini = msg.readUInt32BE(7);- const id = msg.readUInt32BE(11);+ const id = msg.toString('hex', 11, 19);+ const want = msg.readUInt32BE(19);const name = msg.subarray(HELLO_HEADER, HELLO_HEADER + MAX_NAME).toString('utf8');- let s = id ? sessions.get(id) : undefined;+ let s = id !== NO_SESSION ? sessions.get(id) : undefined;if (s && (s.exe !== exe || s.ini !== ini)) {remove(s, 'version changed');s = undefined;}- if (!s) {- if (sessions.size >= MAX_SESSIONS) return false;- const vip = allocVip();- if (!vip) return false;- s = { id: newSessionId(), vip, exe, ini, room: `${hex(exe)}:${hex(ini)}`, name, key: null, seen: 0 };+ if (s && s.key !== key) {+ // NAT moved the client. Never onto an endpoint another session holds, and under a new id, which+ // only whoever reads the new endpoint learns.+ if (byEndpoint.has(key)) return false;+ sessions.delete(s.id);+ s.id = newSessionId();sessions.set(s.id, s);- byVip.set(vip, s);- bind(s, rinfo, key);- log(`join room=${s.room} vip=${vipString(vip)} name=${JSON.stringify(name)}`);+ s.verified = false;+ place(s, rinfo, key);+ } else if (s) {+ s.verified = true;} else {- bind(s, rinfo, key);+ // A HELLO the endpoint's session did not sign: the client retrying before our WELCOME reached+ // it, or one that lost its id. Same CRCs get that session; other CRCs are dropped, so a forged+ // HELLO from someone's endpoint cannot end their session.+ s = byEndpoint.get(key);+ if (s && (s.exe !== exe || s.ini !== ini)) return false;+ if (!s) s = create(exe, ini, want, name, rinfo, key);+ if (!s) return false;}s.seen = now();- const w = Buffer.alloc(11);+ const w = Buffer.alloc(WELCOME_SIZE);w[0] = MAGIC0;w[1] = MAGIC1;w[2] = T_WELCOME;- w.writeUInt32BE(s.id, 3);- w.writeUInt32BE(s.vip, 7);+ w.write(s.id, 3, 'hex');+ w.writeUInt32BE(s.vip, 11);send(w, s);return true;}- function data(msg, rinfo, key) {- const s = sessions.get(msg.readUInt32BE(3));- if (!s) return false;- bind(s, rinfo, key);+ function data(msg, ip, key) {+ const s = sessions.get(msg.toString('hex', 3, 11));+ if (!s || s.key !== key) return false; // only a HELLO moves a session to another endpoint+ s.verified = true;s.seen = now();- const dst = msg.readUInt32BE(7);+ const dst = msg.readUInt32BE(11);+ const targets = [];+ if (dst === BROADCAST) {+ for (const t of rooms.get(s.room)) if (t !== s && t.verified) targets.push(t);+ } else {+ const t = byVip.get(dst);+ if (!t || t === s || t.room !== s.room || !t.verified) return false;+ targets.push(t);+ }+ // the sender pays for every copy, so a broadcast is no cheaper than sending each one itself+ if (!allow(ip, Math.max(msg.length, PACKET_COST_MIN) * Math.max(targets.length, 1))) return false;const out = Buffer.allocUnsafe(msg.length - DATA_IN_HEADER + DATA_OUT_HEADER);out[0] = MAGIC0;out[1] = MAGIC1;out[2] = T_DATA;out.writeUInt32BE(s.vip, 3);- out.writeUInt16BE(msg.readUInt16BE(13), 7); // srcPort- out.writeUInt16BE(msg.readUInt16BE(11), 9); // dstPort+ out.writeUInt16BE(msg.readUInt16BE(17), 7); // srcPort+ out.writeUInt16BE(msg.readUInt16BE(15), 9); // dstPortmsg.copy(out, DATA_OUT_HEADER, DATA_IN_HEADER);- if (dst === BROADCAST) {- // ponytail: scans every session per broadcast; keep a per-room set if sessions reach thousands- for (const t of sessions.values()) if (t !== s && t.room === s.room) send(out, t);- return true;- }- const t = byVip.get(dst);- if (!t || t.room !== s.room) return false;- send(out, t);+ for (const t of targets) send(out, t);return true;}@@ -165,9 +214,9 @@ function createRelay(opts = {}) {stats.bytesIn += msg.length;const key = `${rinfo.address}:${rinfo.port}`;let ok = false;- if (msg.length >= 3 && msg.length <= MAX_PACKET && msg[0] === MAGIC0 && msg[1] === MAGIC1 && allow(key, msg.length)) {- if (msg[2] === T_HELLO && msg.length >= HELLO_HEADER) ok = hello(msg, rinfo, key);- else if (msg[2] === T_DATA && msg.length >= DATA_IN_HEADER) ok = data(msg, rinfo, key);+ if (msg.length >= 3 && msg.length <= MAX_PACKET && msg[0] === MAGIC0 && msg[1] === MAGIC1) {+ if (msg[2] === T_HELLO && msg.length >= HELLO_HEADER) ok = allow(rinfo.address, Math.max(msg.length, PACKET_COST_MIN)) && hello(msg, rinfo, key);+ else if (msg[2] === T_DATA && msg.length >= DATA_IN_HEADER) ok = data(msg, rinfo.address, key);}if (!ok) stats.dropped++;}@@ -175,7 +224,7 @@ function createRelay(opts = {}) {function sweep() {const t = now();for (const s of sessions.values()) if (t - s.seen > IDLE_MS) remove(s, 'idle');- for (const [k, b] of buckets) if (t - b.at > IDLE_MS) buckets.delete(k);+ for (const [k, b] of buckets) if (t - b.at > bucketFullMs) buckets.delete(k);}function report() {@@ -188,6 +237,7 @@ function createRelay(opts = {}) {return {sessions,+ buckets,sweep,report,start(port = DEFAULT_PORT, host) {@@ -207,7 +257,7 @@ function createRelay(opts = {}) {};}-module.exports = { createRelay, MAX_PACKET, IDLE_MS, DATA_IN_HEADER, DATA_OUT_HEADER, vipString };+module.exports = { createRelay, MAX_PACKET, IDLE_MS, NO_SESSION, HELLO_HEADER, DATA_IN_HEADER, DATA_OUT_HEADER, vipString };if (require.main === module) {const port = Number(process.env.RELAY_PORT) || DEFAULT_PORT;diff --git a/GeneralsMD/Code/Tools/relay/test.js b/GeneralsMD/Code/Tools/relay/test.jsindex 369a8f6d4..a7f3e12cf 100644--- a/GeneralsMD/Code/Tools/relay/test.js+++ b/GeneralsMD/Code/Tools/relay/test.js@@ -3,24 +3,24 @@const assert = require('assert');const dgram = require('dgram');-const { createRelay, IDLE_MS, MAX_PACKET } = require('./relay');+const { createRelay, IDLE_MS, MAX_PACKET, NO_SESSION, HELLO_HEADER, DATA_IN_HEADER } = require('./relay');-const HOST = '127.0.0.1';let clock = 1000000;const logLines = [];-const relay = createRelay({ now: () => clock, log: (l) => logLines.push(l), burstBytes: 64 * 1024 });-let relayPort;+const log = (l) => logLines.push(l);+const sockets = [];-function client() {+// a client socket on host (any 127.x address is loopback, which gives the relay distinct source IPs)+function client(relayPort, host = '127.0.0.1') {const sock = dgram.createSocket('udp4');+ sockets.push(sock);const queue = [];let waiter = null;sock.on('message', (m) => {if (waiter) { const w = waiter; waiter = null; w(m); } else queue.push(m);});- return new Promise((resolve) => sock.bind(0, HOST, () => resolve({- sock,- send: (buf) => sock.send(buf, relayPort, HOST),+ return new Promise((resolve) => sock.bind(0, host, () => resolve({+ send: (buf) => sock.send(buf, relayPort, '127.0.0.1'),// next datagram, or null after msnext(ms = 300) {if (queue.length) return Promise.resolve(queue.shift());@@ -32,44 +32,54 @@ function client() {})));}-function hello(exe, ini, session, name = '') {+function hello(exe, ini, session = NO_SESSION, name = '', want = 0) {const n = Buffer.from(name, 'utf8');- const b = Buffer.alloc(15 + n.length);+ const b = Buffer.alloc(HELLO_HEADER + n.length);b.write('ZR', 0, 'latin1');b[2] = 1;b.writeUInt32BE(exe, 3);b.writeUInt32BE(ini, 7);- b.writeUInt32BE(session, 11);- n.copy(b, 15);+ b.write(session, 11, 'hex');+ b.writeUInt32BE(want >>> 0, 19);+ n.copy(b, HELLO_HEADER);return b;}function data(session, dstVip, dstPort, srcPort, payload) {const p = Buffer.from(payload);- const b = Buffer.alloc(15 + p.length);+ const b = Buffer.alloc(DATA_IN_HEADER + p.length);b.write('ZR', 0, 'latin1');b[2] = 3;- b.writeUInt32BE(session, 3);- b.writeUInt32BE(dstVip >>> 0, 7);- b.writeUInt16BE(dstPort, 11);- b.writeUInt16BE(srcPort, 13);- p.copy(b, 15);+ b.write(session, 3, 'hex');+ b.writeUInt32BE(dstVip >>> 0, 11);+ b.writeUInt16BE(dstPort, 15);+ b.writeUInt16BE(srcPort, 17);+ p.copy(b, DATA_IN_HEADER);return b;}-async function join(c, exe, ini, session = 0, name = '') {- c.send(hello(exe, ini, session, name));- const w = await c.next();- assert.ok(w, 'no WELCOME');- assert.strictEqual(w.length, 11);+// the WELCOME a HELLO gets, or null when the relay says nothing+async function join(c, exe, ini, session = NO_SESSION, name = '', want = 0) {+ c.send(hello(exe, ini, session, name, want));+ const w = await c.next(200);+ if (!w) return null;+ assert.strictEqual(w.length, 15);assert.strictEqual(w.toString('latin1', 0, 2), 'ZR');assert.strictEqual(w[2], 2);- const s = { session: w.readUInt32BE(3), vip: w.readUInt32BE(7) };- assert.notStrictEqual(s.session, 0);+ const s = { session: w.toString('hex', 3, 11), vip: w.readUInt32BE(11) };+ assert.notStrictEqual(s.session, NO_SESSION);assert.strictEqual(s.vip >>> 24, 10, 'vip not in 10/8');return s;}+// join, then answer with the id as the game does, which is what lets the relay forward to the endpoint+async function member(c, exe, ini, name = '', want = 0) {+ const s = await join(c, exe, ini, NO_SESSION, name, want);+ assert.ok(s, 'no WELCOME');+ assert.deepStrictEqual(await join(c, exe, ini, s.session, name), s);+ return s;+}+function parseData(m) {assert.ok(m, 'expected DATA, got nothing');assert.strictEqual(m.toString('latin1', 0, 2), 'ZR');@@ -78,19 +88,24 @@ function parseData(m) {}async function main() {- relayPort = await relay.start(0, HOST);- const [a, b, c, a2, d] = await Promise.all([client(), client(), client(), client(), client()]);+ const relay = createRelay({ now: () => clock, log });+ const port = await relay.start(0, '127.0.0.1');+ const [a, b, c, a2, e, f, g] = await Promise.all([...Array(7)].map(() => client(port)));- // hello / welcome: two in one room get distinct vips, a third in another room- const A = await join(a, 0x1111, 0x2222, 0, 'Alpha');+ // hello / welcome: distinct vips, a third in another room; a retried session-0 hello gets the same session+ const A = await member(a, 0x1111, 0x2222, 'Alpha');+ assert.deepStrictEqual(await join(a, 0x1111, 0x2222, NO_SESSION, 'Alpha'), A, 'retried hello replaced the session');const B = await join(b, 0x1111, 0x2222);- const C = await join(c, 0x1111, 0x3333, 0, 'Charlie');+ const C = await member(c, 0x1111, 0x3333, 'Charlie');assert.notStrictEqual(A.vip, B.vip);assert.notStrictEqual(A.session, B.session);assert.ok(logLines.some((l) => l.startsWith('join room=00001111:00002222') && l.includes('"Alpha"')));- // keepalive hello with the session keeps session and vip- assert.deepStrictEqual(await join(a, 0x1111, 0x2222, A.session, 'Alpha'), A);+ // nothing is forwarded to an endpoint until it answers with its id: a forged hello reflects nothing+ a.send(data(A.session, 0xffffffff, 8086, 8086, 'early'));+ a.send(data(A.session, B.vip, 8086, 8086, 'early'));+ assert.strictEqual(await b.next(150), null, 'forwarded to an unverified session');+ assert.deepStrictEqual(await join(b, 0x1111, 0x2222, B.session), B);// unicast carries src vip, both ports and the payloada.send(data(A.session, B.vip, 8086, 8088, 'hi B'));@@ -107,29 +122,59 @@ async function main() {assert.strictEqual(await c.next(150), null, 'unicast crossed rooms');// unknown session, bad magic and oversize packets are dropped- b.send(data(0xdeadbeef, A.vip, 8086, 8086, 'forged'));+ b.send(data('deadbeefdeadbeef', A.vip, 8086, 8086, 'forged'));const bad = data(B.session, A.vip, 8086, 8086, 'x');bad[0] = 0x41;b.send(bad);- b.send(data(B.session, A.vip, 8086, 8086, Buffer.alloc(MAX_PACKET - 14)));+ b.send(data(B.session, A.vip, 8086, 8086, Buffer.alloc(MAX_PACKET - DATA_IN_HEADER + 1)));assert.strictEqual(await a.next(150), null, 'bad packet forwarded');// largest legal packet goes through- b.send(data(B.session, A.vip, 8086, 8086, Buffer.alloc(MAX_PACKET - 15, 0x61)));- assert.strictEqual(parseData(await a.next()).payload.length, MAX_PACKET - 15);-- // NAT rebinding: same session from a new endpoint keeps the vip and moves delivery there- assert.deepStrictEqual(await join(a2, 0x1111, 0x2222, A.session), A);+ b.send(data(B.session, A.vip, 8086, 8086, Buffer.alloc(MAX_PACKET - DATA_IN_HEADER, 0x61)));+ assert.strictEqual(parseData(await a.next()).payload.length, MAX_PACKET - DATA_IN_HEADER);++ // DATA carrying A's id from another endpoint neither moves A nor goes anywhere+ a2.send(data(A.session, B.vip, 8086, 8086, 'hijack'));+ assert.strictEqual(await b.next(150), null, 'DATA from a foreign endpoint forwarded');+ b.send(data(B.session, A.vip, 8086, 8086, 'still a'));+ assert.strictEqual(parseData(await a.next()).payload, 'still a');++ // a session-0 hello with other CRCs from A's endpoint does not end A+ a.send(hello(0x9999, 0x2222));+ assert.strictEqual(await a.next(150), null, 'answered a hello with other CRCs from a held endpoint');+ b.send(data(B.session, A.vip, 8086, 8086, 'kept'));+ assert.strictEqual(parseData(await a.next()).payload, 'kept');++ // a session cannot move onto an endpoint another session holds+ b.send(hello(0x1111, 0x2222, A.session));+ assert.strictEqual(await b.next(150), null, 'moved a session onto a held endpoint');+ b.send(data(B.session, A.vip, 8086, 8086, 'b still b'));+ assert.strictEqual(parseData(await a.next()).payload, 'b still b');++ // NAT rebinding: a hello with the id from a new endpoint moves the session there under a new id that+ // only the new endpoint has seen, and it is served once it answers with that id+ const A2 = await join(a2, 0x1111, 0x2222, A.session);+ assert.strictEqual(A2.vip, A.vip);+ assert.notStrictEqual(A2.session, A.session, 'moved session kept its id');+ b.send(data(B.session, A.vip, 8086, 8086, 'not yet'));+ assert.strictEqual(await a2.next(150), null, 'moved session served before it answered');+ assert.strictEqual(await a.next(150), null, 'old endpoint still served');+ assert.deepStrictEqual(await join(a2, 0x1111, 0x2222, A2.session), A2);b.send(data(B.session, A.vip, 8086, 8086, 'moved'));assert.strictEqual(parseData(await a2.next()).payload, 'moved');- assert.strictEqual(await a.next(150), null, 'old endpoint still served');- // DATA from yet another endpoint rebinds too- a.send(data(A.session, B.vip, 8086, 8086, 'back'));- assert.strictEqual(parseData(await b.next()).payload, 'back');- b.send(data(B.session, A.vip, 8086, 8086, 'to a'));- assert.strictEqual(parseData(await a.next()).payload, 'to a');-- // idle expiry: B keeps alive, A and C go silent+ a.send(data(A.session, B.vip, 8086, 8086, 'old id'));+ assert.strictEqual(await b.next(150), null, 'old id still accepted');++ // a requested address is granted when free, refused when held, ignored outside 10/8+ const E = await join(e, 0x1111, 0x2222, NO_SESSION, 'Echo', 0x0a630005);+ assert.strictEqual(E.vip, 0x0a630005, 'free requested vip not granted');+ const F = await join(f, 0x1111, 0x2222, NO_SESSION, '', 0x0a630005);+ assert.notStrictEqual(F.vip, E.vip, 'held vip handed out twice');+ const G = await join(g, 0x1111, 0x2222, NO_SESSION, '', 0xc0a80105);+ assert.notStrictEqual(G.vip, 0xc0a80105);++ // idle expiry: B keeps alive, the rest go silent+ assert.ok(IDLE_MS >= 120000, 'idle timeout shorter than a long map load step');clock += IDLE_MS - 10000;await join(b, 0x1111, 0x2222, B.session);clock += 15000;@@ -137,27 +182,58 @@ async function main() {assert.strictEqual(relay.sessions.size, 1);assert.ok(logLines.some((l) => l.startsWith('leave room=00001111:00003333') && l.endsWith('reason=idle')));b.send(data(B.session, A.vip, 8086, 8086, 'gone?'));- assert.strictEqual(await a.next(150), null, 'expired vip still delivered');- const A3 = await join(a, 0x1111, 0x2222, A.session);- assert.notStrictEqual(A3.session, A.session, 'expired session revived');-- // rate limit: a fresh source gets its burst (64 KiB in this test) and then nothing until the clock moves- const D = await join(d, 0x1111, 0x2222);- const big = data(D.session, B.vip, 1, 1, Buffer.alloc(1000));- for (let i = 0; i < 80; i++) d.send(big);- let got = 0;- while (await b.next(200)) got++;- assert.ok(got >= 50 && got < 80, `rate limit let ${got} of 80 through`);+ assert.strictEqual(await a2.next(150), null, 'expired vip still delivered');+ // the game's keepalive asks for the address it had, so a forgotten session comes back on it+ const A3 = await join(a2, 0x1111, 0x2222, A2.session, '', A.vip);+ assert.notStrictEqual(A3.session, A2.session, 'expired session revived');+ assert.strictEqual(A3.vip, A.vip, 'a forgotten client lost its address');relay.report();assert.ok(/^stats sessions=\d+ in=\d+p\/\d+B out=\d+p\/\d+B dropped=\d+p$/.test(logLines[logLines.length - 1]));-- for (const x of [a, b, c, a2, d]) x.sock.close();relay.stop();++ // caps: sessions per source IP and per room+ const capped = createRelay({ log, maxPerIp: 2, maxRoom: 3 });+ const capPort = await capped.start(0, '127.0.0.1');+ const [k1, k2, k3, k4, k5, k6] = await Promise.all([+ client(capPort), client(capPort), client(capPort), client(capPort, '127.0.0.2'), client(capPort, '127.0.0.3'), client(capPort, '127.0.0.3')]);+ assert.ok(await join(k1, 1, 1));+ assert.ok(await join(k2, 1, 1));+ assert.strictEqual(await join(k3, 1, 1), null, 'per-IP session cap not enforced');+ assert.ok(await join(k4, 1, 1), 'another IP refused');+ assert.strictEqual(await join(k5, 1, 1), null, 'room cap not enforced');+ assert.ok(await join(k6, 1, 2), 'another room refused');+ capped.stop();++ // the rate limit table has a size: a new source IP is dropped while it is full+ const full = createRelay({ log, maxBuckets: 1 });+ const fullPort = await full.start(0, '127.0.0.1');+ const [q1, q2] = await Promise.all([client(fullPort), client(fullPort, '127.0.0.2')]);+ assert.ok(await join(q1, 1, 1));+ assert.strictEqual(await join(q2, 1, 1), null, 'rate table grew past its cap');+ assert.strictEqual(full.buckets.size, 1);+ full.stop();++ // rate limit per source IP (64 KiB burst here, the clock stands still), and a broadcast is charged+ // once for every copy: with two listeners each gets about half of what one would+ const limited = createRelay({ now: () => clock, log, burstBytes: 64 * 1024 });+ const limitPort = await limited.start(0, '127.0.0.1');+ const [x, y, z] = await Promise.all([client(limitPort, '127.0.0.4'), client(limitPort, '127.0.0.5'), client(limitPort, '127.0.0.5')]);+ const X = await member(x, 7, 7);+ await member(y, 7, 7);+ await member(z, 7, 7);+ const big = data(X.session, 0xffffffff, 1, 1, Buffer.alloc(1000));+ for (let i = 0; i < 80; i++) x.send(big);+ let got = 0;+ while (await y.next(200)) got++;+ assert.ok(got >= 25 && got <= 40, `two listeners: rate limit let ${got} of 80 through to each`);+ limited.stop();++ for (const s of sockets) s.close();console.log('relay test: all checks passed');}-main().catch((e) => {- console.error(e);+main().catch((err) => {+ console.error(err);process.exit(1);});