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
feat(relay): HELLO_AUTH tickets, account rooms, leave order
Olcay Seygan99c0ef1605b4
diff --git a/GeneralsMD/Code/Tools/relay/README.md b/GeneralsMD/Code/Tools/relay/README.mdindex e142a7750..a10d5e97e 100644--- a/GeneralsMD/Code/Tools/relay/README.md+++ b/GeneralsMD/Code/Tools/relay/README.md@@ -34,7 +34,8 @@ counter line:```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+known session with different CRCs) or `replaced` (the account logged in again). `setRoom` prints a+`room vip=... from=... to=...` line. A two-player match moves about 290 KB a minute each way perplayer through it.## Wire format@@ -56,7 +57,20 @@ HELLO, type 1, client to relay:| 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 it accepts:+HELLO_AUTH, type 4, client to relay, refused unless the relay was given an `authorize` hook:++| Offset | Size | Field |+|---|---|---|+| 0 | 2 | `ZR` |+| 2 | 1 | 4 |+| 3 | 4 | exeCRC |+| 7 | 4 | iniCRC |+| 11 | 8 | session, zeros on the first hello |+| 19 | 4 | wantVip |+| 23 | 16 | ticket, from the account server |+| 39 | 0..32 | player name, as in HELLO |++WELCOME, type 2, relay to client, sent in answer to every HELLO or HELLO_AUTH it accepts:| Offset | Size | Field ||---|---|---|@@ -125,6 +139,46 @@ A session with no packet for 120 seconds is removed and its address can be handegame says HELLO every 10 seconds, but only while it pumps its network, and a map load can blockfor a while between two pumps; two minutes outlasts that.+## Accounts++A relay started with an `authorize` hook also takes HELLO_AUTH. Everything above holds for it: the+rate limit, the per-IP and room caps, the endpoint check before anything is forwarded. A HELLO_AUTH+that would open a session hands its ticket to `authorize`; a known account gets a session in the+room `acct:<id>`, where it is alone, and an unknown ticket gets nothing back. The relay asks once per+new session. A retry from the same endpoint before the WELCOME arrived, and any HELLO or HELLO_AUTH+carrying the session afterwards, is answered without asking, so the server may burn a ticket on first+use. A session-0 HELLO_AUTH from an endpoint that holds a plain session is dropped.++An account holds one session. Logging in again with a fresh ticket removes the old session (`leave+... reason=replaced`) before the new one opens. The server moves sessions between rooms with+`setRoom`, for example into `match:<id>` at game start and back to `acct:<id>` after; broadcast and+unicast never leave the room, so two players reach each other only once the server put them together.++Plain HELLO keeps working beside the hook, in its (exeCRC, iniCRC) room, so a LAN `-relay` game runs+on the same relay. Without the hook HELLO_AUTH is dropped and the relay behaves as it did before+accounts.++## Using it from a server++`require('./relay')` exports `createRelay(opts)` and the constants `MAX_PACKET`, `IDLE_MS`,+`NO_SESSION`, `HELLO_HEADER`, `HELLO_AUTH_HEADER`, `DATA_IN_HEADER`, `DATA_OUT_HEADER`, plus+`vipString(vip)`. Every option is optional:++| Option | |+|---|---|+| `authorize(ticketHex)` | returns the account id for a ticket (32 hex digits), or `null`. Synchronous. A throw counts as `null` |+| `onAuthorized(accountId, vip)` | a session opened for that account, with its virtual address |+| `onLeave(accountId, atMs)` | an authorised session was removed: idle, replaced or a HELLO with other CRCs. `atMs` is when it was last heard from. One sweep reports in that order, so the first call is the player who went silent first |+| `now()` | clock in ms, `Date.now` by default |+| `log(line)` | one line per event, console by default |+| `rateBytesPerSec`, `burstBytes`, `maxPerIp`, `maxRoom`, `maxBuckets` | the limits above |++The returned object has `start(port, host)` (resolves to the bound port), `stop()` (no `onLeave`+for what is still open), `setRoom(accountId, room)` (false when the account holds no session; the+room cap does not apply, the caller is trusted), `vipOf(accountId)` (`null` when none), and for tests+`sessions`, `buckets`, `sweep()` and `report()`. Account ids are used as map keys and in room names,+so pass strings or numbers, not objects.+## LimitsThe relay holds at most 4096 sessions, 8 opened from one IP address and 16 in one room.diff --git a/GeneralsMD/Code/Tools/relay/relay.js b/GeneralsMD/Code/Tools/relay/relay.jsindex 11afbdfef..c363fd6a4 100644--- a/GeneralsMD/Code/Tools/relay/relay.js+++ b/GeneralsMD/Code/Tools/relay/relay.js@@ -11,12 +11,14 @@ const MAGIC1 = 0x52; // 'R'const T_HELLO = 1;const T_WELCOME = 2;const T_DATA = 3;+const T_HELLO_AUTH = 4;const BROADCAST = 0xffffffff;const NO_SESSION = '0000000000000000';const DEFAULT_PORT = 8094;const MAX_PACKET = 1400; // bytes, whole datagram, either directionconst HELLO_HEADER = 23; // magic(2) type(1) exeCRC(4) iniCRC(4) session(8) wantVip(4)+const HELLO_AUTH_HEADER = 39; // HELLO's header, then ticket(16)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)@@ -44,12 +46,16 @@ function createRelay(opts = {}) {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 new+ const authorize = opts.authorize; // ticket hex -> account id, or null; without it HELLO_AUTH is refused+ const onAuthorized = opts.onAuthorized || (() => {});+ const onLeave = opts.onLeave || (() => {});const sock = dgram.createSocket('udp4');const sessions = new Map(); // session id (16 hex digits) -> sessionconst byVip = new Map(); // vip -> sessionconst byEndpoint = new Map(); // "ip:port" -> session- const rooms = new Map(); // "exe:ini" -> Set of sessions+ const rooms = new Map(); // "exe:ini", "acct:<id>" or whatever setRoom names -> Set of sessions+ const accounts = new Map(); // account id -> its one sessionconst perIp = new Map(); // ip that opened them -> session countconst buckets = new Map(); // source ip -> { tokens, at }const stats = { pktIn: 0, bytesIn: 0, pktOut: 0, bytesOut: 0, dropped: 0 };@@ -100,16 +106,24 @@ function createRelay(opts = {}) {sock.send(buf, s.port, s.address);}+ function leaveRoom(s) {+ const members = rooms.get(s.room);+ members.delete(s);+ if (!members.size) rooms.delete(s.room);+ }+function remove(s, reason) {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);+ leaveRoom(s);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}`);+ if (s.account !== null) {+ if (accounts.get(s.account) === s) accounts.delete(s.account);+ onLeave(s.account, s.seen);+ }}function place(s, rinfo, key) {@@ -120,13 +134,12 @@ function createRelay(opts = {}) {byEndpoint.set(key, s);}- function create(exe, ini, want, name, rinfo, key) {- const room = `${hex(exe)}:${hex(ini)}`;+ function create(exe, ini, want, name, rinfo, key, 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 };+ const s = { id: newSessionId(), vip, exe, ini, room, name, ip: rinfo.address, key: null, seen: 0, verified: false, account: null };sessions.set(s.id, s);byVip.set(vip, s);rooms.set(room, members.add(s));@@ -136,15 +149,37 @@ function createRelay(opts = {}) {return s;}+ // A new session for whoever the ticket belongs to, in a room of its own. An account holds one session:+ // logging in again replaces the old one. authorize is asked once per new session, never on a retry+ // or keepalive, so the server may make a ticket single-use.+ function login(exe, ini, want, name, rinfo, key, ticket) {+ let account = null;+ try {+ account = authorize(ticket) ?? null;+ } catch (e) {+ log(`authorize threw ${e.message}`);+ }+ if (account === null) return null;+ const old = accounts.get(account);+ if (old) remove(old, 'replaced');+ const s = create(exe, ini, want, name, rinfo, key, `acct:${account}`);+ if (!s) return null;+ s.account = account;+ accounts.set(account, s);+ onAuthorized(account, s.vip);+ return s;+ }+/* A session is forwarded to only once a packet carrying its id came back from its endpoint, and theid only ever goes out in a WELCOME to that endpoint. A HELLO with a forged source address thereforeopens a session nothing reaches, and the relay cannot be aimed at someone else. */- function hello(msg, rinfo, key) {+ function hello(msg, rinfo, key, auth) {const exe = msg.readUInt32BE(3);const ini = msg.readUInt32BE(7);const id = msg.toString('hex', 11, 19);const want = msg.readUInt32BE(19);- const name = msg.subarray(HELLO_HEADER, HELLO_HEADER + MAX_NAME).toString('utf8');+ const nameAt = auth ? HELLO_AUTH_HEADER : HELLO_HEADER;+ const name = msg.subarray(nameAt, nameAt + MAX_NAME).toString('utf8');let s = id !== NO_SESSION ? sessions.get(id) : undefined;if (s && (s.exe !== exe || s.ini !== ini)) {remove(s, 'version changed');@@ -164,10 +199,11 @@ function createRelay(opts = {}) {} else {// 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.+ // HELLO from someone's endpoint cannot end their session. A HELLO_AUTH gets back only a session that+ // is already authorised.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 && (s.exe !== exe || s.ini !== ini || (auth && s.account === null))) return false;+ if (!s) s = auth ? login(exe, ini, want, name, rinfo, key, msg.toString('hex', HELLO_HEADER, HELLO_AUTH_HEADER)) : create(exe, ini, want, name, rinfo, key);if (!s) return false;}s.seen = now();@@ -215,7 +251,8 @@ function createRelay(opts = {}) {const key = `${rinfo.address}:${rinfo.port}`;let ok = false;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);+ if (msg[2] === T_HELLO && msg.length >= HELLO_HEADER) ok = allow(rinfo.address, Math.max(msg.length, PACKET_COST_MIN)) && hello(msg, rinfo, key, false);+ else if (msg[2] === T_HELLO_AUTH && msg.length >= HELLO_AUTH_HEADER && authorize) ok = allow(rinfo.address, Math.max(msg.length, PACKET_COST_MIN)) && hello(msg, rinfo, key, true);else if (msg[2] === T_DATA && msg.length >= DATA_IN_HEADER) ok = data(msg, rinfo.address, key);}if (!ok) stats.dropped++;@@ -223,7 +260,9 @@ function createRelay(opts = {}) {function sweep() {const t = now();- for (const s of sessions.values()) if (t - s.seen > IDLE_MS) remove(s, 'idle');+ // oldest silence first, so onLeave reports who went quiet first+ const idle = [...sessions.values()].filter((s) => t - s.seen > IDLE_MS).sort((a, b) => a.seen - b.seen);+ for (const s of idle) remove(s, 'idle');for (const [k, b] of buckets) if (t - b.at > bucketFullMs) buckets.delete(k);}@@ -240,6 +279,18 @@ function createRelay(opts = {}) {buckets,sweep,report,+ // Moves an authorised session to another room; unicast and broadcast stay inside it. The caller is+ // trusted, so the room cap does not apply. False when the account holds no session.+ setRoom(account, room) {+ const s = accounts.get(account);+ if (!s) return false;+ log(`room vip=${vipString(s.vip)} from=${s.room} to=${room}`);+ leaveRoom(s);+ s.room = room;+ rooms.set(room, (rooms.get(room) || new Set()).add(s));+ return true;+ },+ vipOf: (account) => accounts.get(account)?.vip ?? null,start(port = DEFAULT_PORT, host) {return new Promise((resolve, reject) => {sock.once('error', reject);@@ -257,7 +308,7 @@ function createRelay(opts = {}) {};}-module.exports = { createRelay, MAX_PACKET, IDLE_MS, NO_SESSION, HELLO_HEADER, DATA_IN_HEADER, DATA_OUT_HEADER, vipString };+module.exports = { createRelay, MAX_PACKET, IDLE_MS, NO_SESSION, HELLO_HEADER, HELLO_AUTH_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 a7f3e12cf..8c605ec95 100644--- a/GeneralsMD/Code/Tools/relay/test.js+++ b/GeneralsMD/Code/Tools/relay/test.js@@ -3,7 +3,7 @@const assert = require('assert');const dgram = require('dgram');-const { createRelay, IDLE_MS, MAX_PACKET, NO_SESSION, HELLO_HEADER, DATA_IN_HEADER } = require('./relay');+const { createRelay, IDLE_MS, MAX_PACKET, NO_SESSION, HELLO_HEADER, HELLO_AUTH_HEADER, DATA_IN_HEADER } = require('./relay');let clock = 1000000;const logLines = [];@@ -58,9 +58,20 @@ function data(session, dstVip, dstPort, srcPort, payload) {return b;}+function helloAuth(exe, ini, ticket, session = NO_SESSION, name = '', want = 0) {+ const b = Buffer.concat([hello(exe, ini, session, '', want), Buffer.from(ticket, 'hex'), Buffer.from(name, 'utf8')]);+ b[2] = 4;+ assert.strictEqual(b.length, HELLO_AUTH_HEADER + Buffer.byteLength(name));+ return b;+}+// the WELCOME a HELLO gets, or null when the relay says nothingasync function join(c, exe, ini, session = NO_SESSION, name = '', want = 0) {- c.send(hello(exe, ini, session, name, want));+ return welcome(c, hello(exe, ini, session, name, want));+}++async function welcome(c, pkt) {+ c.send(pkt);const w = await c.next(200);if (!w) return null;assert.strictEqual(w.length, 15);@@ -188,6 +199,10 @@ async function main() {assert.notStrictEqual(A3.session, A2.session, 'expired session revived');assert.strictEqual(A3.vip, A.vip, 'a forgotten client lost its address');+ // without an authorize hook HELLO_AUTH gets nothing+ const h = await client(port);+ assert.strictEqual(await welcome(h, helloAuth(0x1111, 0x2222, 'aa'.repeat(16))), null, 'HELLO_AUTH answered with no hook');+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]));relay.stop();@@ -229,6 +244,110 @@ async function main() {assert.ok(got >= 25 && got <= 40, `two listeners: rate limit let ${got} of 80 through to each`);limited.stop();+ // HELLO_AUTH: tickets name accounts, each account starts alone in acct:<id>+ const T1 = 'a1'.repeat(16), T2 = 'b2'.repeat(16), T3 = 'c3'.repeat(16), BAD = 'ee'.repeat(16);+ const tickets = new Map([[T1, 'u1'], [T2, 'u2'], [T3, 'u3']]);+ const asked = [], authorized = [], leaves = [];+ const authed = createRelay({+ now: () => clock,+ log,+ authorize: (t) => { asked.push(t); return tickets.get(t) ?? null; },+ onAuthorized: (id, vip) => authorized.push([id, vip]),+ onLeave: (id, at) => leaves.push([id, at]),+ });+ const authPort = await authed.start(0, '127.0.0.1');+ const [p1, p2, p3, p1b, l1, l2, forger] =await Promise.all([...Array(7)].map((_, i) => client(authPort, `127.0.1.${i + 1}`)));+ const authMember = async (c, ticket, name) => {+ const s = await welcome(c, helloAuth(9, 9, ticket, NO_SESSION, name));+ assert.ok(s, 'good ticket refused');+ assert.deepStrictEqual(await welcome(c, helloAuth(9, 9, ticket, s.session, name)), s);+ return s;+ };++ // bad ticket: asked once, nothing back, no session+ assert.strictEqual(await welcome(forger, helloAuth(9, 9, BAD)), null, 'bad ticket answered');+ assert.deepStrictEqual(asked, [BAD]);+ assert.strictEqual(authed.sessions.size, 0);++ // good ticket: authorised once even though the confirming HELLO_AUTH carries the ticket again+ const P1 = await authMember(p1, T1, 'One');+ assert.deepStrictEqual(asked, [BAD, T1], 'keepalive asked authorize again');+ assert.deepStrictEqual(authorized, [['u1', P1.vip]]);+ assert.strictEqual(authed.vipOf('u1'), P1.vip);+ assert.strictEqual(authed.vipOf('nobody'), null);+ assert.ok(logLines.some((l) => l.startsWith('join room=acct:u1 ') && l.includes('"One"')));+ // a retry with no session from the same endpoint gets the same session without asking again+ assert.deepStrictEqual(await welcome(p1, helloAuth(9, 9, T1)), P1);+ assert.strictEqual(asked.length, 2);+ // plain HELLO with the id keeps it alive too+ assert.deepStrictEqual(await join(p1, 9, 9, P1.session), P1);+ const P2 = await authMember(p2, T2, 'Two');+ const P3 = await authMember(p3, T3, 'Three');++ // plain HELLO still works beside the hook, in its CRC room+ const L1 = await member(l1, 9, 9, 'Lan1');+ const L2 = await member(l2, 9, 9, 'Lan2');+ l1.send(data(L1.session, L2.vip, 8086, 8086, 'lan'));+ assert.strictEqual(parseData(await l2.next()).payload, 'lan');+ l1.send(data(L1.session, 0xffffffff, 8086, 8086, 'lan all'));+ assert.strictEqual(parseData(await l2.next()).payload, 'lan all');+ assert.strictEqual(await p1.next(150), null, 'LAN broadcast reached an account room');+ // a plain session's endpoint cannot be turned into an account by a session-0 HELLO_AUTH+ assert.strictEqual(await welcome(l1, helloAuth(9, 9, T3)), null, 'HELLO_AUTH took over a plain session');++ // private rooms: nothing crosses between accounts+ p1.send(data(P1.session, P2.vip, 8086, 8086, 'private'));+ p1.send(data(P1.session, 0xffffffff, 8086, 8086, 'private all'));+ assert.strictEqual(await p2.next(150), null, 'account rooms not private');++ // match room: unicast and broadcast inside it, nobody outside hears+ assert.strictEqual(authed.setRoom('u1', 'match:1'), true);+ assert.strictEqual(authed.setRoom('u2', 'match:1'), true);+ assert.strictEqual(authed.setRoom('nobody', 'match:1'), false);+ p1.send(data(P1.session, P2.vip, 8086, 8086, 'gl hf'));+ assert.strictEqual(parseData(await p2.next()).payload, 'gl hf');+ p2.send(data(P2.session, 0xffffffff, 8086, 8086, 'match all'));+ assert.deepStrictEqual(parseData(await p1.next()), { srcVip: P2.vip, srcPort: 8086, dstPort: 8086, payload: 'match all' });+ assert.strictEqual(await p3.next(150), null, 'match broadcast left the room');+ assert.strictEqual(await l1.next(150), null, 'match broadcast reached the LAN room');+ p1.send(data(P1.session, P3.vip, 8086, 8086, 'leak'));+ p1.send(data(P1.session, L1.vip, 8086, 8086, 'leak'));+ assert.strictEqual(await p3.next(150), null, 'unicast out of the match room');+ assert.strictEqual(await l1.next(150), null, 'unicast into the LAN room');+ // and back out: u2 home again, u1 alone in the match room+ authed.setRoom('u2', 'acct:u2');+ p1.send(data(P1.session, P2.vip, 8086, 8086, 'gone'));+ assert.strictEqual(await p2.next(150), null, 'setRoom back left the session in the match');++ // logging in again replaces: the old session leaves, the account moves to the new one+ clock += 1000;+ const P1b = await authMember(p1b, T1, 'One again');+ assert.notStrictEqual(P1b.session, P1.session);+ assert.strictEqual(authed.vipOf('u1'), P1b.vip);+ assert.deepStrictEqual(leaves.map((l) => l[0]), ['u1'], 'replace did not fire onLeave');+ assert.ok(logLines.some((l) => l.startsWith('leave room=match:1 ') && l.endsWith('reason=replaced')));+ assert.ok(!authed.sessions.has(P1.session), 'replaced session still held');++ // idle: onLeave in the order the sessions went silent, not the order they joined; plain ones fire nothing+ const t0 = clock;+ clock = t0 + 1000; await join(p3, 9, 9, P3.session);+ clock = t0 + 2000; await join(p1b, 9, 9, P1b.session);+ clock = t0 + 3000; await join(p2, 9, 9, P2.session);+ clock = t0 + 3000 + IDLE_MS + 1;+ authed.sweep();+ assert.strictEqual(authed.sessions.size, 0);+ assert.deepStrictEqual(leaves.slice(1), [['u3', t0 + 1000], ['u1', t0 + 2000], ['u2', t0 + 3000]]);+ assert.strictEqual(authed.vipOf('u2'), null);+ authed.stop();++ // HELLO_AUTH counts against the per-IP cap like HELLO+ const authCap = createRelay({ log, maxPerIp: 1, authorize: (t) => tickets.get(t) ?? null });+ const authCapPort = await authCap.start(0, '127.0.0.1');+ const [m1, m2] = await Promise.all([client(authCapPort), client(authCapPort)]);+ assert.ok(await welcome(m1, helloAuth(9, 9, T1)));+ assert.strictEqual(await welcome(m2, helloAuth(9, 9, T2)), null, 'per-IP cap skipped by HELLO_AUTH');+ authCap.stop();+for (const s of sockets) s.close();console.log('relay test: all checks passed');}