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): virtual LAN UDP relay for online play
Olcay Seyganfd991accb9d4
diff --git a/GeneralsMD/Code/Tools/relay/README.md b/GeneralsMD/Code/Tools/relay/README.mdnew file mode 100644index 000000000..23bc75c5f--- /dev/null+++ b/GeneralsMD/Code/Tools/relay/README.md@@ -0,0 +1,108 @@+# Virtual LAN relay++The game's LAN mode finds games by broadcast and talks to peers by address, so it stops at the+router. This relay gives every connected copy of the game a virtual address in 10.0.0.0/8 and+forwards its LAN traffic to the other copies that run the same exe and INI set. Each game thinks it+is on one LAN; the relay is the switch.++It is one Node file with no dependencies, and it keeps no state on disk.++## Running it++```+node relay.js # UDP 8094+RELAY_PORT=9000 node relay.js # another port+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.++It prints one line per join and leave, with the room and the virtual address, and once a minute a+counter line:++```+2026-11-06T08:50:00.000Z join room=1a2b3c4d:5e6f7a8b vip=10.0.0.3 name="Tank Girl"+2026-11-06T08:51:00.000Z stats sessions=4 in=5120p/880213B out=9877p/1702260B dropped=3p+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).++## Wire format++UDP, 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.++HELLO, type 1, client to relay:++| Offset | Size | Field |+|---|---|---|+| 0 | 2 | `ZR` |+| 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) |++WELCOME, type 2, relay to client, sent in answer to every HELLO:++| 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) |++DATA, type 3, client to relay:++| Offset | Size | Field |+|---|---|---|+| 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 |++DATA, type 3, relay to client:++| Offset | Size | Field |+|---|---|---|+| 0 | 2 | `ZR` |+| 2 | 1 | 3 |+| 3 | 4 | srcVip |+| 7 | 2 | srcPort |+| 9 | 2 | dstPort |+| 11 | .. | payload |++The relay never reads the payload.++## 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.++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.++## Rate limit++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+dry 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`.diff --git a/GeneralsMD/Code/Tools/relay/relay.js b/GeneralsMD/Code/Tools/relay/relay.jsnew file mode 100644index 000000000..72e38c01a--- /dev/null+++ b/GeneralsMD/Code/Tools/relay/relay.js@@ -0,0 +1,221 @@+'use strict';+// Virtual LAN relay: players behind NAT each get a virtual 10.x.y.z address and the+// relay forwards the game's LAN packets between them. Wire format in README.md.+// Run: node relay.js (UDP port from RELAY_PORT, default 8094)++const dgram = require('dgram');+const crypto = require('crypto');++const MAGIC0 = 0x5a; // 'Z'+const MAGIC1 = 0x52; // 'R'+const T_HELLO = 1;+const T_WELCOME = 2;+const T_DATA = 3;+const BROADCAST = 0xffffffff;++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 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 MAX_SESSIONS = 4096;+const RATE_BYTES_PER_SEC = 512 * 1024; // sustained, per source endpoint+const BURST_BYTES = 2 * 1024 * 1024; // a map transfer goes out in one burst+const PACKET_COST_MIN = 64; // a tiny packet still costs this much, so floods of them drain the bucket+const SWEEP_MS = 5000;+const STATS_MS = 60000;++const vipString = (v) => `${v >>> 24}.${(v >>> 16) & 255}.${(v >>> 8) & 255}.${v & 255}`;+const hex = (n) => n.toString(16).padStart(8, '0');++function createRelay(opts = {}) {+ const now = opts.now || Date.now;+ 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 sock = dgram.createSocket('udp4');+ const sessions = new Map(); // session id -> session+ const byVip = new Map(); // vip -> session+ const byEndpoint = new Map(); // "ip:port" -> session+ const buckets = new Map(); // "ip:port" -> { tokens, at }+ const stats = { pktIn: 0, bytesIn: 0, pktOut: 0, bytesOut: 0, dropped: 0 };+ let nextVip = 1;+ let timers = [];++ function allocVip() {+ for (let i = 0; i < 0xffffff; i++) {+ const n = nextVip;+ nextVip = nextVip >= 0xfffffe ? 1 : nextVip + 1;+ const low = n & 255;+ if (low === 0 || low === 255) continue;+ const vip = (0x0a000000 | n) >>> 0;+ if (!byVip.has(vip)) return vip;+ }+ return 0;+ }++ function newSessionId() {+ for (;;) {+ const id = crypto.randomBytes(4).readUInt32BE(0);+ if (id !== 0 && !sessions.has(id)) return id;+ }+ }++ function allow(key, len) {+ const t = now();+ let b = buckets.get(key);+ if (!b) buckets.set(key, (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;+ }++ function send(buf, s) {+ stats.pktOut++;+ stats.bytesOut += buf.length;+ sock.send(buf, s.port, s.address);+ }++ function remove(s, reason) {+ sessions.delete(s.id);+ byVip.delete(s.vip);+ if (byEndpoint.get(s.key) === s) byEndpoint.delete(s.key);+ 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;+ 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 hello(msg, rinfo, key) {+ const exe = msg.readUInt32BE(3);+ const ini = msg.readUInt32BE(7);+ const id = msg.readUInt32BE(11);+ const name = msg.subarray(HELLO_HEADER, HELLO_HEADER + MAX_NAME).toString('utf8');+ let s = id ? 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 };+ 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)}`);+ } else {+ bind(s, rinfo, key);+ }+ s.seen = now();+ const w = Buffer.alloc(11);+ w[0] = MAGIC0;+ w[1] = MAGIC1;+ w[2] = T_WELCOME;+ w.writeUInt32BE(s.id, 3);+ w.writeUInt32BE(s.vip, 7);+ 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);+ s.seen = now();+ const dst = msg.readUInt32BE(7);+ 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+ msg.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);+ return true;+ }++ function onMessage(msg, rinfo) {+ stats.pktIn++;+ 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 (!ok) stats.dropped++;+ }++ 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);+ }++ function report() {+ log(`stats sessions=${sessions.size} in=${stats.pktIn}p/${stats.bytesIn}B out=${stats.pktOut}p/${stats.bytesOut}B dropped=${stats.dropped}p`);+ for (const k of Object.keys(stats)) stats[k] = 0;+ }++ sock.on('message', onMessage);+ sock.on('error', (e) => log(`socket error ${e.message}`));++ return {+ sessions,+ sweep,+ report,+ start(port = DEFAULT_PORT, host) {+ return new Promise((resolve, reject) => {+ sock.once('error', reject);+ sock.bind(port, host, () => {+ sock.off('error', reject);+ timers = [setInterval(sweep, SWEEP_MS), setInterval(report, STATS_MS)];+ resolve(sock.address().port);+ });+ });+ },+ stop() {+ timers.forEach(clearInterval);+ sock.close();+ },+ };+}++module.exports = { createRelay, MAX_PACKET, IDLE_MS, DATA_IN_HEADER, DATA_OUT_HEADER, vipString };++if (require.main === module) {+ const port = Number(process.env.RELAY_PORT) || DEFAULT_PORT;+ createRelay()+ .start(port)+ .then((p) => console.log(`${new Date().toISOString()} relay listening on udp/${p}`))+ .catch((e) => {+ console.error(`relay: cannot bind udp/${port}: ${e.message}`);+ process.exit(1);+ });+}diff --git a/GeneralsMD/Code/Tools/relay/test.js b/GeneralsMD/Code/Tools/relay/test.jsnew file mode 100644index 000000000..369a8f6d4--- /dev/null+++ b/GeneralsMD/Code/Tools/relay/test.js@@ -0,0 +1,163 @@+'use strict';+// Self-check for relay.js: node test.js (exit code 0 = pass)++const assert = require('assert');+const dgram = require('dgram');+const { createRelay, IDLE_MS, MAX_PACKET } = 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;++function client() {+ const sock = dgram.createSocket('udp4');+ 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),+ // next datagram, or null after ms+ next(ms = 300) {+ if (queue.length) return Promise.resolve(queue.shift());+ return new Promise((res) => {+ const t = setTimeout(() => { waiter = null; res(null); }, ms);+ waiter = (m) => { clearTimeout(t); res(m); };+ });+ },+ })));+}++function hello(exe, ini, session, name = '') {+ const n = Buffer.from(name, 'utf8');+ const b = Buffer.alloc(15 + 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);+ return b;+}++function data(session, dstVip, dstPort, srcPort, payload) {+ const p = Buffer.from(payload);+ const b = Buffer.alloc(15 + 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);+ 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);+ 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);+ assert.strictEqual(s.vip >>> 24, 10, 'vip not in 10/8');+ return s;+}++function parseData(m) {+ assert.ok(m, 'expected DATA, got nothing');+ assert.strictEqual(m.toString('latin1', 0, 2), 'ZR');+ assert.strictEqual(m[2], 3);+ return { srcVip: m.readUInt32BE(3), srcPort: m.readUInt16BE(7), dstPort: m.readUInt16BE(9), payload: m.subarray(11).toString() };+}++async function main() {+ relayPort = await relay.start(0, HOST);+ const [a, b, c, a2, d] = await Promise.all([client(), client(), client(), client(), client()]);++ // hello / welcome: two in one room get distinct vips, a third in another room+ const A = await join(a, 0x1111, 0x2222, 0, 'Alpha');+ const B = await join(b, 0x1111, 0x2222);+ const C = await join(c, 0x1111, 0x3333, 0, '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);++ // unicast carries src vip, both ports and the payload+ a.send(data(A.session, B.vip, 8086, 8088, 'hi B'));+ assert.deepStrictEqual(parseData(await b.next()), { srcVip: A.vip, srcPort: 8088, dstPort: 8086, payload: 'hi B' });++ // broadcast reaches the room, not the sender and not another room+ a.send(data(A.session, 0xffffffff, 8086, 8086, 'lobby'));+ assert.deepStrictEqual(parseData(await b.next()), { srcVip: A.vip, srcPort: 8086, dstPort: 8086, payload: 'lobby' });+ assert.strictEqual(await c.next(150), null, 'broadcast crossed rooms');+ assert.strictEqual(await a.next(150), null, 'broadcast echoed to sender');++ // unicast into another room is dropped+ a.send(data(A.session, C.vip, 8086, 8086, 'nope'));+ 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'));+ 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)));+ 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, '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+ clock += IDLE_MS - 10000;+ await join(b, 0x1111, 0x2222, B.session);+ clock += 15000;+ relay.sweep();+ 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`);++ 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();+ console.log('relay test: all checks passed');+}++main().catch((e) => {+ console.error(e);+ process.exit(1);+});