Skip to content

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.

feat(gameengine): -control, a WebSocket that drives a running game

Olcay Seygan51a660cde6d4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 82fb51d0f..4db365095 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -897,6 +897,7 @@ found and fixed — EA's own, not port damage.**
- No debugger here: a crash symboliser, a sampling profiler, probes in live matches.
- A graphics fix is argued with pixels: an unattended match can now be told where to point the camera and which frame to photograph, so the two builds are compared by counting the pixels between them. The river above changed 126,535 of them and the eye had been calling it "about the same".
- A unit's cost is argued with the same army twice. An unattended match can now take its army from a text file - spawn eight of that unit there on frame thirty, send them across the map on frame six hundred, stop them on frame nine hundred - and be told which faction each seat plays and to leave every seat without a computer player behind it. Before that, whatever was on the field came out of the seed: measuring what angry mobs cost meant waiting for a match that happened to build some, and two runs that drew different sides were never comparable in the first place.
+- And the other half of that: a running game will now take orders down a socket. Started with the switch for it, the game listens on this machine only and answers anything that can speak to a web page - start a match on this map with these players, put five of that unit there, send them across the map, take a picture, tell me the frame number and what everybody owns. The commands are the same lines the text file above takes. A twenty-line Python script can now set up a match, produce an army and read the result back, which is how the mob numbers in this list were produced.
- Reverted and recorded: wide FOV, the whole group movement rework, tree shadows out of a stencil
volume. That last one was a day spent proving the models cannot do it: a tree is a flat two-sided
sheet with no closed silhouette, so a palm threw its trunk and a leafy tree threw nothing. The
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/ControlServer.h b/GeneralsMD/Code/GameEngine/Include/Common/ControlServer.h
new file mode 100644
index 000000000..8bdc3182c
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Include/Common/ControlServer.h
@@ -0,0 +1,74 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: ControlServer.h /////////////////////////////////////////////////////////////////////////
+//
+// -control [port]: a WebSocket on 127.0.0.1 that drives the game from outside it.
+//
+// The scenario file answers "play this match the same way twice". This answers the other half:
+// poke the running game and ask it what happened. Start a skirmish, spawn a worker, send a
+// selection somewhere, take a picture, read the frame number and everybody's money back - from
+// Python, from a browser console, from anything that speaks WebSocket.
+//
+// It listens on the loopback address only. There is no authentication and none is wanted: the
+// socket can start a match and create units, so it has to be unreachable from anywhere but this
+// machine, and binding to 127.0.0.1 is what makes that true rather than a promise.
+//
+// Commands are one line of text per frame, and world commands are the same grammar the scenario
+// files use, minus the leading frame number:
+//
+// spawn <slot> <template> <count> <x> <y> [spacing]
+// move|attackmove <slot> <selector> <x> <y>
+// attack <slot> <selector> <targetSlot> <targetSelector>
+// stop <slot> <selector>
+//
+// plus a handful the files have no use for: ping, status, screenshot, skirmish, quit.
+//
+// Replies are one JSON object per frame. Every reply carries "ok", and a failed one carries
+// "error" saying what was wrong with the command rather than dropping it.
+//
+// World commands do not take effect where they arrive. Reading a socket happens on a render pass
+// and creating an object has to happen inside a logic frame, so a command is queued by
+// ControlServer_poll and carried out by ControlServer_runCommands on the next logic frame. That is
+// also what keeps the game deterministic while something is driving it.
+//
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#pragma once
+
+#ifndef __CONTROLSERVER_H_
+#define __CONTROLSERVER_H_
+
+#include "Lib/BaseType.h"
+
+/** Accept connections, read commands, send replies. Called once per engine pass. */
+extern void ControlServer_poll( void );
+
+/** Carry out the world commands that arrived since the last logic frame. Called from
+ GameLogic::update, which is the only place it is safe to make an object. */
+extern void ControlServer_runCommands( void );
+
+/** Close the socket. Called when the engine shuts down. */
+extern void ControlServer_shutdown( void );
+
+/** The WebSocket handshake reply for a client key: SHA-1 of the key and the protocol's own GUID,
+ base64'd. Public because it is the one piece of this file that can be tested without a socket,
+ and RFC 6455 ships a worked example to test it against. */
+extern Bool ControlServer_computeAcceptKey( const char *clientKey, char *out, Int outSize );
+
+#endif // __CONTROLSERVER_H_
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
index ee4992ef7..7551afc04 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h
@@ -400,6 +400,7 @@ public:
Int m_resDrillY; ///< the height -resdrill asks for
Bool m_resDrillKeep; ///< -resdrillkeep: answer the confirmation with Ok and stay on the new mode
Bool m_noRenderDevice; ///< -nodevice: run without a Direct3D device at all, for a machine whose session is locked
+ Int m_controlPort; ///< -control [port]: listen for WebSocket commands on 127.0.0.1 (0 = off)
AsciiString m_scenarioFile; ///< -scenario <name>: play Run/Scenarios/<name>.txt instead of leaving the match to a person or an AI (empty = off)
Bool m_autoSkirmishTakeover; ///< -takeover: give every -autoskirmish slot a driverless human seat, so nothing thinks unless a scenario says so
AsciiString m_autoSkirmishSide[ MAX_PLAYER_COUNT ]; ///< -side <slot> <faction>: name that slot's faction instead of drawing it from the seed
diff --git a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
index e304cdbf4..63a72ff9c 100644
--- a/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
+++ b/GeneralsMD/Code/GameEngine/Include/GameLogic/ScenarioDrill.h
@@ -101,6 +101,11 @@ extern const char *ScenarioDrill_parseResultName( ScenarioParseResult result );
/** Run whatever the file asks for on this logic frame. Called from GameLogic::update. */
extern void ScenarioDrill_tick( void );
+/** Carry out one action now. The scenario file is one caller; the control server is the other, so
+ that a command typed down a socket means exactly what the same line means in a file. Only safe
+ from inside a logic frame, and only while a match is running. */
+extern Bool ScenarioDrill_execute( const ScenarioAction &action );
+
/** One line for the end-of-run summary: how much of the file actually happened. */
extern const char *ScenarioDrill_report( void );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index b18ed6615..7ba230692 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -1600,6 +1600,34 @@ Int parseResDrillKeep(char *args[], int)
return 1;
}
+/* -control [port] opens a WebSocket on 127.0.0.1 and lets something outside the game drive it.
+
+ The scenario file answers "play this match the same way twice". This answers the other half:
+ poke a running game and ask it what happened. Start a match, spawn a unit, send a selection
+ somewhere, take a picture, read the frame number and everybody's money back - from Python, from
+ a browser console, from anything that speaks WebSocket.
+
+ Loopback only, and deliberately so: the socket can create units, so it has to be unreachable
+ from another machine, and binding to 127.0.0.1 is what makes that true rather than a promise.
+ There is no authentication and none would help; anything that can reach the port can already
+ run programs on this machine. */
+Int parseControlPort(char *args[], int num)
+{
+ const Int CONTROL_DEFAULT_PORT = 8787;
+ if (TheWritableGlobalData)
+ {
+ TheWritableGlobalData->m_controlPort = CONTROL_DEFAULT_PORT;
+ if (num > 1 && args[1] && args[1][0] >= '0' && args[1][0] <= '9')
+ {
+ const Int port = atoi(args[1]);
+ if (port > 0 && port < 65536)
+ TheWritableGlobalData->m_controlPort = port;
+ return 2;
+ }
+ }
+ return 1;
+}
+
/* -nodevice runs the whole game without a Direct3D device.
-headless already draws nothing, but it still takes a 100x100 windowed device, and D3D9 answers
@@ -2080,6 +2108,7 @@ static CommandLineParam params[] =
{ "-uidrill", parseUIDrill },
{ "-resdrill", parseResDrill },
{ "-resdrillkeep", parseResDrillKeep },
+ { "-control", parseControlPort },
{ "-nodevice", parseNoDevice },
{ "-scenario", parseScenario },
{ "-side", parseSide },
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
index 75ea27b4c..1031c5836 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp
@@ -85,6 +85,7 @@
#include "GameLogic/Weapon.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/Locomotor.h"
+#include "Common/ControlServer.h" // -control: the WebSocket that drives the game from outside
#include "GameLogic/RankInfo.h"
#include "GameLogic/ScenarioDrill.h" // -scenario says at the end how much of the file ran
#include "GameLogic/ScriptEngine.h"
@@ -217,6 +218,9 @@ GameEngine::~GameEngine()
extern bool DX8Wrapper_IsWindowed;
DX8Wrapper_IsWindowed = false;
+ // close the control socket before anything it can reach is torn down
+ ControlServer_shutdown();
+
delete TheMapCache;
TheMapCache = NULL;
@@ -342,7 +346,7 @@ static void startPendingSaveGame( void )
* populateRandomStartPosition). Meant for unattended runs - eight AI players fighting at whatever
* frame rate the machine gives, with the local slot watching.
*/
-static void startAutoSkirmish( void )
+static void startAutoSkirmish( Int numPlayersWanted )
{
AsciiString mapName = TheGlobalData->m_mapName;
if (mapName.isEmpty())
@@ -363,7 +367,7 @@ static void startAutoSkirmish( void )
return;
}
- Int numPlayers = TheGlobalData->m_autoSkirmishPlayers;
+ Int numPlayers = numPlayersWanted;
if (numPlayers > md->m_numPlayers)
{
DEBUG_LOG(("-autoskirmish: '%s' holds %d players, not %d\n", mapName.str(), md->m_numPlayers, numPlayers));
@@ -498,6 +502,17 @@ static void startAutoSkirmish( void )
fixedStartPositions ? ", start positions fixed to slot order" : ""));
}
+/** -----------------------------------------------------------------------------------------------
+ * The same door, for -control's "skirmish" command. The player count is a parameter rather than
+ * the global that -autoskirmish sets, because that global is also what marks a run unattended: a
+ * match somebody is driving down a socket has to stay up when it ends, not write its numbers out
+ * and quit.
+ */
+void GameEngine_startSkirmish( Int numPlayers )
+{
+ startAutoSkirmish( numPlayers );
+}
+
/** -----------------------------------------------------------------------------------------------
* -netgame <ip>[,<ip>...] -netslot <n>: play a LAN game against those addresses, with the slot
* list, the map and the seed coming from the command line instead of from the lobby. Same job as
@@ -1011,7 +1026,7 @@ void GameEngine::init( int argc, char *argv[] )
}
else if (TheGlobalData->m_autoSkirmishPlayers > 0)
{
- startAutoSkirmish();
+ startAutoSkirmish( TheGlobalData->m_autoSkirmishPlayers );
}
//
@@ -1761,6 +1776,13 @@ static void updateHeadlessRun( void )
its numbers down is not a measurement. This still cannot fire on a game a person started:
reaching here needs -headless or -autoskirmish, and neither is on a menu. */
const Bool unattended = TheGlobalData->m_headless || TheGlobalData->m_autoSkirmishPlayers > 0;
+
+ /* Except that a run with a control socket open is not unattended at all - somebody is driving
+ it from the other end, and tearing the process down the moment a match is decided takes the
+ socket with it. Whoever is driving says when it ends, by sending "quit". */
+ if (TheGlobalData->m_controlPort > 0)
+ return;
+
if (!unattended || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())
return;
@@ -2097,6 +2119,9 @@ void GameEngine::update( void )
updateUIDrill();
updateResDrill();
updateInputWatch();
+ // -control: read whatever came down the socket. What it asks for is carried out on the next
+ // logic frame, by ControlServer_runCommands, because that is where making an object is safe.
+ ControlServer_poll();
#ifdef DEBUG_LOGGING
fpsFrames++;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
index 7e05b7837..0676b313c 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp
@@ -708,6 +708,7 @@ GlobalData::GlobalData()
m_resDrillY = 0;
m_resDrillKeep = FALSE;
m_noRenderDevice = FALSE; // -headless still takes a 100x100 device unless -nodevice says not to
+ m_controlPort = 0; // nothing listens; -control opens the socket
m_scenarioFile.clear(); // nothing is scripted; -scenario is a measuring tool and, like -groupdrill, ruins the match it runs in
m_autoSkirmishTakeover = FALSE; // the AI plays the opponents unless -takeover empties their seats
for( Int slot = 0; slot < MAX_PLAYER_COUNT; slot++ )
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp
new file mode 100644
index 000000000..7b6004403
--- /dev/null
+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp
@@ -0,0 +1,787 @@
+/*
+** Command & Conquer Generals Zero Hour(tm)
+** Copyright 2025 Electronic Arts Inc.
+**
+** This program is free software: you can redistribute it and/or modify
+** it under the terms of the GNU General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** This program is distributed in the hope that it will be useful,
+** but WITHOUT ANY WARRANTY; without even the implied warranty of
+** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+** GNU General Public License for more details.
+**
+** You should have received a copy of the GNU General Public License
+** along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+// FILE: ControlServer.cpp ///////////////////////////////////////////////////////////////////////
+//
+// -control [port]: a WebSocket on 127.0.0.1 that drives the game from outside it. See
+// ControlServer.h for the command grammar and for why world commands are queued rather than run
+// where they arrive.
+//
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
+
+#include "Common/ControlServer.h"
+#include "Common/GameEngine.h"
+#include "Common/GlobalData.h"
+#include "Common/Money.h"
+#include "Common/Player.h"
+#include "Common/PlayerList.h"
+#include "GameClient/Display.h"
+#include "GameLogic/GameLogic.h"
+#include "GameLogic/Object.h"
+#include "GameLogic/ScenarioDrill.h"
+#include "GameNetwork/GameInfo.h" // MAX_SLOTS, for the skirmish command's player count
+
+#include <vector>
+
+// windows.h, which PreRTS.h already pulled in, brings Winsock 1.1 with it. That is every call
+// this file makes, so it takes the one already on the table rather than starting the winsock2
+// header fight described in the hard constraints.
+
+// ------------------------------------------------------------------------------------------------
+// sizes and constants
+// ------------------------------------------------------------------------------------------------
+
+static const Int CONTROL_LOOPBACK_ONLY = INADDR_LOOPBACK;
+static const Int CONTROL_BACKLOG = 1;
+static const Int CONTROL_READ_CHUNK = 4096;
+static const Int CONTROL_MAX_REQUEST = 16384;
+static const Int CONTROL_MAX_COMMANDS_PER_FRAME = 64;
+
+/// RFC 6455's magic string, appended to the client key before hashing
+static const char *CONTROL_WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+
+static const Int SHA1_DIGEST_BYTES = 20;
+static const Int SHA1_BLOCK_BYTES = 64;
+
+// WebSocket opcodes, from RFC 6455 section 5.2
+static const unsigned char WS_OPCODE_TEXT = 0x1;
+static const unsigned char WS_OPCODE_CLOSE = 0x8;
+static const unsigned char WS_OPCODE_PING = 0x9;
+static const unsigned char WS_OPCODE_PONG = 0xA;
+
+// ------------------------------------------------------------------------------------------------
+// SHA-1, because the handshake needs one and nothing in GameEngine has one
+// ------------------------------------------------------------------------------------------------
+
+struct Sha1State
+{
+ UnsignedInt digest[ 5 ];
+ UnsignedInt byteCount;
+ unsigned char block[ SHA1_BLOCK_BYTES ];
+ Int blockLength;
+};
+
+static UnsignedInt sha1RotateLeft( UnsignedInt value, Int bits )
+{
+ return (value << bits) | (value >> (32 - bits));
+}
+
+static void sha1Init( Sha1State *state )
+{
+ state->digest[ 0 ] = 0x67452301;
+ state->digest[ 1 ] = 0xEFCDAB89;
+ state->digest[ 2 ] = 0x98BADCFE;
+ state->digest[ 3 ] = 0x10325476;
+ state->digest[ 4 ] = 0xC3D2E1F0;
+ state->byteCount = 0;
+ state->blockLength = 0;
+}
+
+static void sha1Transform( Sha1State *state )
+{
+ UnsignedInt w[ 80 ];
+ Int i;
+
+ for( i = 0; i < 16; ++i )
+ {
+ w[ i ] = ((UnsignedInt)state->block[ i * 4 ] << 24)
+ | ((UnsignedInt)state->block[ i * 4 + 1 ] << 16)
+ | ((UnsignedInt)state->block[ i * 4 + 2 ] << 8)
+ | ((UnsignedInt)state->block[ i * 4 + 3 ]);
+ }
+ for( i = 16; i < 80; ++i )
+ w[ i ] = sha1RotateLeft( w[ i - 3 ] ^ w[ i - 8 ] ^ w[ i - 14 ] ^ w[ i - 16 ], 1 );
+
+ UnsignedInt a = state->digest[ 0 ];
+ UnsignedInt b = state->digest[ 1 ];
+ UnsignedInt c = state->digest[ 2 ];
+ UnsignedInt d = state->digest[ 3 ];
+ UnsignedInt e = state->digest[ 4 ];
+
+ for( i = 0; i < 80; ++i )
+ {
+ UnsignedInt f, k;
+ if (i < 20) { f = (b & c) | ((~b) & d); k = 0x5A827999; }
+ else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
+ else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; }
+ else { f = b ^ c ^ d; k = 0xCA62C1D6; }
+
+ const UnsignedInt temp = sha1RotateLeft( a, 5 ) + f + e + k + w[ i ];
+ e = d;
+ d = c;
+ c = sha1RotateLeft( b, 30 );
+ b = a;
+ a = temp;
+ }
+
+ state->digest[ 0 ] += a;
+ state->digest[ 1 ] += b;
+ state->digest[ 2 ] += c;
+ state->digest[ 3 ] += d;
+ state->digest[ 4 ] += e;
+}
+
+static void sha1Update( Sha1State *state, const unsigned char *data, Int length )
+{
+ for( Int i = 0; i < length; ++i )
+ {
+ state->block[ state->blockLength++ ] = data[ i ];
+ ++state->byteCount;
+ if (state->blockLength == SHA1_BLOCK_BYTES)
+ {
+ sha1Transform( state );
+ state->blockLength = 0;
+ }
+ }
+}
+
+static void sha1Finish( Sha1State *state, unsigned char *digestOut )
+{
+ const UnsignedInt bitCount = state->byteCount * 8;
+
+ const unsigned char one = 0x80;
+ sha1Update( state, &one, 1 );
+
+ const unsigned char zero = 0x00;
+ while (state->blockLength != 56)
+ sha1Update( state, &zero, 1 );
+
+ unsigned char lengthBytes[ 8 ];
+ for( Int i = 0; i < 4; ++i )
+ lengthBytes[ i ] = 0;
+ lengthBytes[ 4 ] = (unsigned char)((bitCount >> 24) & 0xFF);
+ lengthBytes[ 5 ] = (unsigned char)((bitCount >> 16) & 0xFF);
+ lengthBytes[ 6 ] = (unsigned char)((bitCount >> 8) & 0xFF);
+ lengthBytes[ 7 ] = (unsigned char)(bitCount & 0xFF);
+ sha1Update( state, lengthBytes, 8 );
+
+ for( Int i = 0; i < SHA1_DIGEST_BYTES; ++i )
+ digestOut[ i ] = (unsigned char)((state->digest[ i / 4 ] >> (24 - 8 * (i % 4))) & 0xFF);
+}
+
+// ------------------------------------------------------------------------------------------------
+// base64
+// ------------------------------------------------------------------------------------------------
+
+static const char *BASE64_ALPHABET =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static Int base64Encode( const unsigned char *data, Int length, char *out, Int outSize )
+{
+ const Int needed = ((length + 2) / 3) * 4 + 1;
+ if (outSize < needed)
+ return 0;
+
+ Int written = 0;
+ Int at = 0;
+ while (at < length)
+ {
+ const UnsignedInt byte0 = data[ at ];
+ const UnsignedInt byte1 = (at + 1 < length) ? data[ at + 1 ] : 0;
+ const UnsignedInt byte2 = (at + 2 < length) ? data[ at + 2 ] : 0;
+ const UnsignedInt triple = (byte0 << 16) | (byte1 << 8) | byte2;
+
+ out[ written++ ] = BASE64_ALPHABET[ (triple >> 18) & 0x3F ];
+ out[ written++ ] = BASE64_ALPHABET[ (triple >> 12) & 0x3F ];
+ out[ written++ ] = (at + 1 < length) ? BASE64_ALPHABET[ (triple >> 6) & 0x3F ] : '=';
+ out[ written++ ] = (at + 2 < length) ? BASE64_ALPHABET[ triple & 0x3F ] : '=';
+ at += 3;
+ }
+
+ out[ written ] = 0;
+ return written;
+}
+
+Bool ControlServer_computeAcceptKey( const char *clientKey, char *out, Int outSize )
+{
+ if (clientKey == NULL || out == NULL)
+ return FALSE;
+
+ Sha1State state;
+ sha1Init( &state );
+ sha1Update( &state, (const unsigned char *)clientKey, (Int)strlen( clientKey ) );
+ sha1Update( &state, (const unsigned char *)CONTROL_WEBSOCKET_GUID,
+ (Int)strlen( CONTROL_WEBSOCKET_GUID ) );
+
+ unsigned char digest[ SHA1_DIGEST_BYTES ];
+ sha1Finish( &state, digest );
+
+ return base64Encode( digest, SHA1_DIGEST_BYTES, out, outSize ) > 0;
+}
+
+// ------------------------------------------------------------------------------------------------
+// socket state
+// ------------------------------------------------------------------------------------------------
+
+static SOCKET theListenSocket = INVALID_SOCKET;
+static SOCKET theClientSocket = INVALID_SOCKET;
+static Bool theWinsockStarted = FALSE;
+static Bool theHandshakeDone = FALSE;
+static std::vector<char> theIncoming;
+static std::vector<AsciiString> thePendingCommands;
+static Bool theQuitRequested = FALSE;
+
+static void closeClient( void )
+{
+ if (theClientSocket != INVALID_SOCKET)
+ {
+ closesocket( theClientSocket );
+ theClientSocket = INVALID_SOCKET;
+ }
+ theHandshakeDone = FALSE;
+ theIncoming.clear();
+}
+
+static Bool setNonBlocking( SOCKET s )
+{
+ unsigned long nonBlocking = 1;
+ return ioctlsocket( s, FIONBIO, &nonBlocking ) == 0;
+}
+
+static Bool openListenSocket( Int port )
+{
+ WSADATA wsaData;
+ if (!theWinsockStarted)
+ {
+ if (WSAStartup( MAKEWORD( 1, 1 ), &wsaData ) != 0)
+ {
+ DEBUG_LOG(("CONTROL: winsock would not start\n"));
+ return FALSE;
+ }
+ theWinsockStarted = TRUE;
+ }
+
+ theListenSocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
+ if (theListenSocket == INVALID_SOCKET)
+ {
+ DEBUG_LOG(("CONTROL: no socket\n"));
+ return FALSE;
+ }
+
+ sockaddr_in address;
+ memset( &address, 0, sizeof( address ) );
+ address.sin_family = AF_INET;
+ address.sin_port = htons( (unsigned short)port );
+ address.sin_addr.s_addr = htonl( CONTROL_LOOPBACK_ONLY );
+
+ if (bind( theListenSocket, (sockaddr *)&address, sizeof( address ) ) != 0
+ || listen( theListenSocket, CONTROL_BACKLOG ) != 0
+ || !setNonBlocking( theListenSocket ))
+ {
+ DEBUG_LOG(("CONTROL: cannot listen on 127.0.0.1:%d\n", port));
+ closesocket( theListenSocket );
+ theListenSocket = INVALID_SOCKET;
+ return FALSE;
+ }
+
+ DEBUG_LOG(("CONTROL: listening on ws://127.0.0.1:%d\n", port));
+ return TRUE;
+}
+
+// ------------------------------------------------------------------------------------------------
+// websocket framing
+// ------------------------------------------------------------------------------------------------
+
+static void sendFrame( unsigned char opcode, const char *payload, Int length )
+{
+ if (theClientSocket == INVALID_SOCKET)
+ return;
+
+ std::vector<char> frame;
+ frame.push_back( (char)(0x80 | opcode) );
+
+ // a server frame is never masked, so the length is the whole second byte
+ if (length < 126)
+ {
+ frame.push_back( (char)length );
+ }
+ else if (length < 65536)
+ {
+ frame.push_back( (char)126 );
+ frame.push_back( (char)((length >> 8) & 0xFF) );
+ frame.push_back( (char)(length & 0xFF) );
+ }
+ else
+ {
+ frame.push_back( (char)127 );
+ for( Int i = 0; i < 4; ++i )
+ frame.push_back( (char)0 );
+ frame.push_back( (char)((length >> 24) & 0xFF) );
+ frame.push_back( (char)((length >> 16) & 0xFF) );
+ frame.push_back( (char)((length >> 8) & 0xFF) );
+ frame.push_back( (char)(length & 0xFF) );
+ }
+
+ for( Int i = 0; i < length; ++i )
+ frame.push_back( payload[ i ] );
+
+ send( theClientSocket, &frame[ 0 ], (Int)frame.size(), 0 );
+}
+
+static void sendText( const char *text )
+{
+ sendFrame( WS_OPCODE_TEXT, text, (Int)strlen( text ) );
+}
+
+/** Pull one complete frame off the front of theIncoming. Returns FALSE when there is not a whole
+ one there yet, which is the normal case on a non-blocking read. */
+static Bool takeFrame( unsigned char *opcodeOut, AsciiString *payloadOut )
+{
+ const Int have = (Int)theIncoming.size();
+ if (have < 2)
+ return FALSE;
+
+ const unsigned char byte0 = (unsigned char)theIncoming[ 0 ];
+ const unsigned char byte1 = (unsigned char)theIncoming[ 1 ];
+ const Bool masked = (byte1 & 0x80) != 0;
+ Int payloadLength = byte1 & 0x7F;
+ Int at = 2;
+
+ if (payloadLength == 126)
+ {
+ if (have < at + 2)
+ return FALSE;
+ payloadLength = ((unsigned char)theIncoming[ at ] << 8) | (unsigned char)theIncoming[ at + 1 ];
+ at += 2;
+ }
+ else if (payloadLength == 127)
+ {
+ // the four high bytes of a 64-bit length are refused rather than truncated: nothing this
+ // socket accepts is four gigabytes long, so a frame claiming to be is a broken client
+ if (have < at + 8)
+ return FALSE;
+ for( Int i = 0; i < 4; ++i )
+ {
+ if (theIncoming[ at + i ] != 0)
+ {
+ closeClient();
+ return FALSE;
+ }
+ }
+ payloadLength = ((unsigned char)theIncoming[ at + 4 ] << 24)
+ | ((unsigned char)theIncoming[ at + 5 ] << 16)
+ | ((unsigned char)theIncoming[ at + 6 ] << 8)
+ | ((unsigned char)theIncoming[ at + 7 ]);
+ at += 8;
+ }
+
+ unsigned char mask[ 4 ] = { 0, 0, 0, 0 };
+ if (masked)
+ {
+ if (have < at + 4)
+ return FALSE;
+ for( Int i = 0; i < 4; ++i )
+ mask[ i ] = (unsigned char)theIncoming[ at + i ];
+ at += 4;
+ }
+
+ if (payloadLength < 0 || have < at + payloadLength)
+ return FALSE;
+
+ AsciiString payload;
+ if (payloadLength > 0)
+ {
+ std::vector<char> text;
+ text.resize( payloadLength + 1 );
+ for( Int i = 0; i < payloadLength; ++i )
+ text[ i ] = (char)((unsigned char)theIncoming[ at + i ] ^ (masked ? mask[ i % 4 ] : 0));
+ text[ payloadLength ] = 0;
+ payload.set( &text[ 0 ] );
+ }
+
+ theIncoming.erase( theIncoming.begin(), theIncoming.begin() + at + payloadLength );
+
+ *opcodeOut = byte0 & 0x0F;
+ *payloadOut = payload;
+ return TRUE;
+}
+
+// ------------------------------------------------------------------------------------------------
+// the http upgrade
+// ------------------------------------------------------------------------------------------------
+
+/** Read the client key out of the request headers. Case-insensitive on the header name, because
+ RFC 7230 says header names are, and browsers and Python libraries disagree about the casing. */
+static Bool findClientKey( const char *request, char *keyOut, Int keyOutSize )
+{
+ static const char *HEADER = "sec-websocket-key:";
+ const Int headerLength = (Int)strlen( HEADER );
+
+ for( const char *at = request; *at; ++at )
+ {
+ Int i = 0;
+ while (i < headerLength && at[ i ] && tolower( (unsigned char)at[ i ] ) == HEADER[ i ])
+ ++i;
+ if (i < headerLength)
+ continue;
+
+ const char *value = at + headerLength;
+ while (*value == ' ' || *value == '\t')
+ ++value;
+
+ Int written = 0;
+ while (*value && *value != '\r' && *value != '\n' && written < keyOutSize - 1)
+ keyOut[ written++ ] = *value++;
+ keyOut[ written ] = 0;
+ return written > 0;
+ }
+
+ return FALSE;
+}
+
+static Bool tryHandshake( void )
+{
+ // the request ends at the blank line; until then there is nothing to answer
+ theIncoming.push_back( 0 );
+ const char *request = &theIncoming[ 0 ];
+ const char *end = strstr( request, "\r\n\r\n" );
+ theIncoming.pop_back();
+
+ if (end == NULL)
+ return FALSE;
+
+ char clientKey[ 256 ];
+ char acceptKey[ 64 ];
+ if (!findClientKey( request, clientKey, sizeof( clientKey ) )
+ || !ControlServer_computeAcceptKey( clientKey, acceptKey, sizeof( acceptKey ) ))
+ {
+ DEBUG_LOG(("CONTROL: not a websocket request, closing\n"));
+ closeClient();
+ return FALSE;
+ }
+
+ char reply[ 512 ];
+ sprintf( reply,
+ "HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: %s\r\n\r\n",
+ acceptKey );
+ send( theClientSocket, reply, (Int)strlen( reply ), 0 );
+
+ const Int consumed = (Int)(end - request) + 4;
+ theIncoming.erase( theIncoming.begin(), theIncoming.begin() + consumed );
+ theHandshakeDone = TRUE;
+ DEBUG_LOG(("CONTROL: client connected\n"));
+ return TRUE;
+}
+
+// ------------------------------------------------------------------------------------------------
+// commands
+// ------------------------------------------------------------------------------------------------
+
+static void replyOk( const char *extra )
+{
+ char reply[ 1024 ];
+ if (extra && *extra)
+ sprintf( reply, "{\"ok\":true,%s}", extra );
+ else
+ sprintf( reply, "{\"ok\":true}" );
+ sendText( reply );
+}
+
+static void replyError( const char *why )
+{
+ char reply[ 512 ];
+ sprintf( reply, "{\"ok\":false,\"error\":\"%s\"}", why );
+ sendText( reply );
+}
+
+/** frame number, whether a match is running, and what each player owns. */
+static void replyStatus( void )
+{
+ const Bool inGame = TheGameLogic && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame();
+
+ std::vector<char> reply;
+ char piece[ 256 ];
+
+ sprintf( piece, "{\"ok\":true,\"frame\":%d,\"inGame\":%s,\"players\":[",
+ TheGameLogic ? (Int)TheGameLogic->getFrame() : 0,
+ inGame ? "true" : "false" );
+ for( const char *at = piece; *at; ++at )
+ reply.push_back( *at );
+
+ if (inGame && ThePlayerList)
+ {
+ Bool first = TRUE;
+ for( Int i = 0; i < ThePlayerList->getPlayerCount(); ++i )
+ {
+ Player *player = ThePlayerList->getNthPlayer( i );
+ if (player == NULL)
+ continue;
+
+ Int units = 0;
+ for( Object *obj = TheGameLogic->getFirstObject(); obj; obj = obj->getNextObject() )
+ {
+ if (obj->getControllingPlayer() == player && !obj->isEffectivelyDead())
+ ++units;
+ }
+
+ sprintf( piece, "%s{\"index\":%d,\"slot\":%d,\"money\":%u,\"units\":%d}",
+ first ? "" : ",", i, ThePlayerList->getSlotIndex( i ),
+ player->getMoney()->countMoney(), units );
+ for( const char *at = piece; *at; ++at )
+ reply.push_back( *at );
+ first = FALSE;
+ }
+ }
+
+ reply.push_back( ']' );
+ reply.push_back( '}' );
+ reply.push_back( 0 );
+ sendText( &reply[ 0 ] );
+}
+
+/** Everything that changes the world is queued; see the header for why. */
+static void handleCommand( const AsciiString &command )
+{
+ if (command.isEmpty())
+ return;
+
+ if (command == "ping")
+ {
+ replyOk( "\"pong\":true" );
+ return;
+ }
+
+ if (command == "status")
+ {
+ replyStatus();
+ return;
+ }
+
+ if (command == "screenshot")
+ {
+ if (TheDisplay == NULL)
+ {
+ replyError( "no display" );
+ return;
+ }
+ TheDisplay->takeScreenShot();
+ replyOk( "\"screenshot\":\"requested\"" );
+ return;
+ }
+
+ if (command == "quit")
+ {
+ theQuitRequested = TRUE;
+ replyOk( "\"quitting\":true" );
+ return;
+ }
+
+ /* skirmish <players> <seed> <map>
+ The map is whatever is left on the line, spaces and all, because every shipped map has a
+ space in its name and quoting rules would be one more thing to get wrong at the far end. */
+ if (strncmp( command.str(), "skirmish ", 9 ) == 0)
+ {
+ if (TheGameLogic && TheGameLogic->isInGame() && !TheGameLogic->isInShellGame())
+ {
+ replyError( "a match is already running; quit it first" );
+ return;
+ }
+
+ Int players = 0;
+ Int seed = 0;
+ char mapName[ 512 ];
+ if (sscanf( command.str(), "skirmish %d %d %511[^\n]", &players, &seed, mapName ) != 3)
+ {
+ replyError( "skirmish wants <players> <seed> <map>" );
+ return;
+ }
+ if (players < 2 || players > MAX_SLOTS)
+ {
+ replyError( "a skirmish holds between two and eight players" );
+ return;
+ }
+
+ /* m_autoSkirmishPlayers is deliberately left alone: it is also what marks a run unattended,
+ and a match somebody is driving from here has to stay up when it ends rather than write
+ its numbers out and quit. */
+ TheWritableGlobalData->m_mapName.set( mapName );
+ TheWritableGlobalData->m_fixedSeed = seed;
+
+ extern void GameEngine_startSkirmish( Int numPlayers );
+ GameEngine_startSkirmish( players );
+ replyOk( "\"starting\":true" );
+ return;
+ }
+
+ /* Anything else is a world command, and world commands are the scenario grammar with the frame
+ number left off - so put one back on and hand it to the same parser the files go through. One
+ grammar, two front ends, and a line that works in a file works down the socket. */
+ AsciiString asScenarioLine;
+ asScenarioLine.set( "0 " );
+ asScenarioLine.concat( command );
+
+ ScenarioAction action;
+ const ScenarioParseResult result = ScenarioDrill_parseLine( asScenarioLine.str(), &action );
+ if (result != SCENARIO_PARSE_OK)
+ {
+ replyError( ScenarioDrill_parseResultName( result ) );
+ return;
+ }
+
+ if (!TheGameLogic || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())
+ {
+ replyError( "no match is running" );
+ return;
+ }
+
+ if ((Int)thePendingCommands.size() >= CONTROL_MAX_COMMANDS_PER_FRAME)
+ {
+ replyError( "too many commands queued for one frame" );
+ return;
+ }
+
+ thePendingCommands.push_back( command );
+ replyOk( "\"queued\":true" );
+}
+
+// ------------------------------------------------------------------------------------------------
+// the two ticks
+// ------------------------------------------------------------------------------------------------
+
+void ControlServer_poll( void )
+{
+ if (TheGlobalData == NULL || TheGlobalData->m_controlPort <= 0)
+ return;
+
+ if (theListenSocket == INVALID_SOCKET)
+ {
+ if (!openListenSocket( TheGlobalData->m_controlPort ))
+ {
+ // stop trying: a port that will not bind now will not bind on the next frame either
+ TheWritableGlobalData->m_controlPort = 0;
+ return;
+ }
+ }
+
+ if (theClientSocket == INVALID_SOCKET)
+ {
+ const SOCKET accepted = accept( theListenSocket, NULL, NULL );
+ if (accepted == INVALID_SOCKET)
+ return;
+ theClientSocket = accepted;
+ setNonBlocking( theClientSocket );
+ theHandshakeDone = FALSE;
+ theIncoming.clear();
+ }
+
+ char chunk[ CONTROL_READ_CHUNK ];
+ for( ;; )
+ {
+ const Int received = recv( theClientSocket, chunk, sizeof( chunk ), 0 );
+ if (received > 0)
+ {
+ for( Int i = 0; i < received; ++i )
+ theIncoming.push_back( chunk[ i ] );
+ if ((Int)theIncoming.size() > CONTROL_MAX_REQUEST)
+ {
+ DEBUG_LOG(("CONTROL: client sent more than %d bytes without a frame, closing\n",
+ CONTROL_MAX_REQUEST));
+ closeClient();
+ return;
+ }
+ continue;
+ }
+
+ if (received == 0)
+ {
+ DEBUG_LOG(("CONTROL: client went away\n"));
+ closeClient();
+ return;
+ }
+
+ if (WSAGetLastError() != WSAEWOULDBLOCK)
+ {
+ closeClient();
+ return;
+ }
+ break;
+ }
+
+ if (!theHandshakeDone)
+ {
+ if (theIncoming.empty() || !tryHandshake())
+ return;
+ }
+
+ unsigned char opcode = 0;
+ AsciiString payload;
+ while (theClientSocket != INVALID_SOCKET && takeFrame( &opcode, &payload ))
+ {
+ if (opcode == WS_OPCODE_CLOSE)
+ {
+ closeClient();
+ return;
+ }
+ if (opcode == WS_OPCODE_PING)
+ {
+ sendFrame( WS_OPCODE_PONG, payload.str(), (Int)strlen( payload.str() ) );
+ continue;
+ }
+ if (opcode != WS_OPCODE_TEXT)
+ continue;
+
+ handleCommand( payload );
+ }
+}
+
+void ControlServer_runCommands( void )
+{
+ if (thePendingCommands.empty())
+ return;
+
+ for( std::vector<AsciiString>::iterator it = thePendingCommands.begin();
+ it != thePendingCommands.end(); ++it )
+ {
+ AsciiString asScenarioLine;
+ asScenarioLine.set( "0 " );
+ asScenarioLine.concat( *it );
+
+ ScenarioAction action;
+ if (ScenarioDrill_parseLine( asScenarioLine.str(), &action ) != SCENARIO_PARSE_OK)
+ continue;
+
+ ScenarioDrill_execute( action );
+ }
+
+ thePendingCommands.clear();
+
+ if (theQuitRequested && TheGameEngine)
+ TheGameEngine->setQuitting( TRUE );
+}
+
+void ControlServer_shutdown( void )
+{
+ closeClient();
+
+ if (theListenSocket != INVALID_SOCKET)
+ {
+ closesocket( theListenSocket );
+ theListenSocket = INVALID_SOCKET;
+ }
+
+ if (theWinsockStarted)
+ {
+ WSACleanup();
+ theWinsockStarted = FALSE;
+ }
+}
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
index 79e031239..b4430471d 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/GameLogic.cpp
@@ -93,6 +93,7 @@
#include "GameLogic/Module/DestroyModule.h"
#include "GameLogic/Module/OpenContain.h"
#include "GameLogic/PartitionManager.h"
+#include "Common/ControlServer.h"
#include "GameLogic/PolygonTrigger.h"
#include "GameLogic/ScenarioDrill.h"
#include "GameLogic/ScriptActions.h"
@@ -4268,6 +4269,10 @@ void GameLogic::update( void )
point of measuring two builds against it. */
ScenarioDrill_tick();
+ /* And whatever arrived down the control socket since the last logic frame. Reading a socket
+ happens on a render pass and making an object has to happen in here, so the two are split. */
+ ControlServer_runCommands();
+
QueryPerformanceCounter( (LARGE_INTEGER *)&tScripts );
Bool freezeTime = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished();
diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
index 68693d50c..7bb2a28e3 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/System/ScenarioDrill.cpp
@@ -553,7 +553,7 @@ static Bool executeOrder( const ScenarioAction &action, Player *player )
return ordered;
}
-static Bool executeAction( const ScenarioAction &action )
+Bool ScenarioDrill_execute( const ScenarioAction &action )
{
Player *player = findPlayerForSlot( action.slot );
if (player == NULL)
@@ -595,7 +595,7 @@ void ScenarioDrill_tick( void )
while (theScenarioCursor < (Int)theScenarioActions.size()
&& theScenarioActions[ theScenarioCursor ].frame <= now)
{
- if (executeAction( theScenarioActions[ theScenarioCursor ] ))
+ if (ScenarioDrill_execute( theScenarioActions[ theScenarioCursor ] ))
++theScenarioActionsRun;
else
++theScenarioActionsFailed;
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index cbf432980..04f03ff0b 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -43,6 +43,7 @@
#include "Common/Energy.h"
#include "Common/RandomValue.h"
#include "GameLogic/ScenarioDrill.h"
+#include "Common/ControlServer.h"
#include "GameLogic/LogicRandomValue.h"
#include "GameClient/ClientRandomValue.h"
#include "Common/ThingTemplate.h"
@@ -10335,3 +10336,32 @@ TEST(scenario_refuses_a_line_it_cannot_read)
// and every refusal has something to say for itself in the log
CHECK_STR( ScenarioDrill_parseResultName( SCENARIO_PARSE_BAD_FRAME ), "frame is not a whole number" );
}
+
+/* -control's WebSocket handshake.
+ *
+ * The reply to a client key is SHA-1 of the key and the protocol's GUID, base64'd. Nothing in
+ * GameEngine had either of those, so both are written out in ControlServer.cpp and both are the
+ * kind of thing that is either exactly right or silently useless - a wrong byte gives a reply the
+ * client refuses, and the only symptom is a socket that never talks.
+ *
+ * RFC 6455 section 1.3 ships a worked example, which is what this checks against.
+ */
+TEST(control_server_answers_the_rfc_handshake_example)
+{
+ char accept[ 64 ];
+
+ CHECK( ControlServer_computeAcceptKey( "dGhlIHNhbXBsZSBub25jZQ==", accept, sizeof( accept ) ) );
+ CHECK_STR( accept, "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" );
+
+ // a second known pair, so that a SHA-1 that happens to be right for one input is not enough
+ CHECK( ControlServer_computeAcceptKey( "x3JJHMbDL1EzLkh9GBhXDw==", accept, sizeof( accept ) ) );
+ CHECK_STR( accept, "HSmrc0sMlYUkAGmm5OPpG2HaGWk=" );
+
+ // and an empty key still hashes rather than walking off the end of anything
+ CHECK( ControlServer_computeAcceptKey( "", accept, sizeof( accept ) ) );
+ CHECK_EQ( (Int)strlen( accept ), 28 );
+
+ // a buffer too small to hold the 28 characters and the terminator is refused, not overrun
+ char tooSmall[ 8 ];
+ CHECK( !ControlServer_computeAcceptKey( "dGhlIHNhbXBsZSBub25jZQ==", tooSmall, sizeof( tooSmall ) ) );
+}
diff --git a/GeneralsMD/Code/Tools/control_client.py b/GeneralsMD/Code/Tools/control_client.py
new file mode 100644
index 000000000..4b2d030e2
--- /dev/null
+++ b/GeneralsMD/Code/Tools/control_client.py
@@ -0,0 +1,212 @@
+"""Drive a running game over its -control WebSocket.
+
+Start the game with -control (default port 8787) and then, from here:
+
+ from control_client import Control
+ with Control() as game:
+ print(game.send("status"))
+ game.send("spawn 0 GLAInfantryAngryMobNexus 8 760 920 60")
+ game.send("attackmove 0 GLAInfantryAngryMobNexus 1400 1400")
+ game.send("screenshot")
+
+World commands are the scenario-file grammar with the leading frame number left off, so a line
+that works in Run/Scenarios/*.txt works here. The rest are ping, status, screenshot and quit.
+
+No dependencies on purpose: this speaks enough of RFC 6455 to talk to one server on loopback, and
+anybody who wants to poke the game should not first have to install anything.
+
+Run it directly for a smoke test:
+
+ python control_client.py # ping, status
+ python control_client.py 8787 "spawn 0 AmericaVehicleHumvee 4 800 900"
+"""
+
+import base64
+import hashlib
+import json
+import os
+import socket
+import struct
+import sys
+
+DEFAULT_PORT = 8787
+WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
+OPCODE_TEXT = 0x1
+OPCODE_CLOSE = 0x8
+OPCODE_PING = 0x9
+OPCODE_PONG = 0xA
+
+
+class ControlError(RuntimeError):
+ pass
+
+
+class Control(object):
+ """One connection to one running game."""
+
+ def __init__(self, port=DEFAULT_PORT, host="127.0.0.1", timeout=10.0):
+ self.socket = socket.create_connection((host, port), timeout)
+ self.socket.settimeout(timeout)
+ self._buffer = b""
+ self._handshake(host, port)
+
+ # -- lifetime ---------------------------------------------------------
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_):
+ self.close()
+
+ def close(self):
+ if self.socket is None:
+ return
+ try:
+ self._send_frame(OPCODE_CLOSE, b"")
+ except OSError:
+ pass
+ self.socket.close()
+ self.socket = None
+
+ # -- the handshake ----------------------------------------------------
+
+ def _handshake(self, host, port):
+ key = base64.b64encode(os.urandom(16)).decode("ascii")
+ request = (
+ "GET / HTTP/1.1\r\n"
+ "Host: %s:%d\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Key: %s\r\n"
+ "Sec-WebSocket-Version: 13\r\n\r\n" % (host, port, key)
+ )
+ self.socket.sendall(request.encode("ascii"))
+
+ while b"\r\n\r\n" not in self._buffer:
+ self._fill()
+
+ head, _, rest = self._buffer.partition(b"\r\n\r\n")
+ self._buffer = rest
+ head = head.decode("ascii", "replace")
+
+ if "101" not in head.split("\r\n")[0]:
+ raise ControlError("server refused the upgrade: %s" % head.split("\r\n")[0])
+
+ expected = base64.b64encode(
+ hashlib.sha1((key + WEBSOCKET_GUID).encode("ascii")).digest()
+ ).decode("ascii")
+ for line in head.split("\r\n"):
+ name, _, value = line.partition(":")
+ if name.strip().lower() == "sec-websocket-accept":
+ if value.strip() != expected:
+ raise ControlError("wrong accept key: %r" % value.strip())
+ return
+ raise ControlError("no Sec-WebSocket-Accept in the reply")
+
+ # -- framing ----------------------------------------------------------
+
+ def _fill(self):
+ chunk = self.socket.recv(4096)
+ if not chunk:
+ raise ControlError("the game closed the connection")
+ self._buffer += chunk
+
+ def _send_frame(self, opcode, payload):
+ header = bytearray([0x80 | opcode])
+ mask = os.urandom(4)
+ length = len(payload)
+ if length < 126:
+ header.append(0x80 | length)
+ elif length < 65536:
+ header.append(0x80 | 126)
+ header += struct.pack(">H", length)
+ else:
+ header.append(0x80 | 127)
+ header += struct.pack(">Q", length)
+ header += mask
+ masked = bytes(byte ^ mask[i % 4] for i, byte in enumerate(payload))
+ self.socket.sendall(bytes(header) + masked)
+
+ def _read_frame(self):
+ while True:
+ while len(self._buffer) < 2:
+ self._fill()
+
+ first, second = self._buffer[0], self._buffer[1]
+ opcode = first & 0x0F
+ length = second & 0x7F
+ at = 2
+
+ if length == 126:
+ while len(self._buffer) < at + 2:
+ self._fill()
+ length = struct.unpack(">H", self._buffer[at:at + 2])[0]
+ at += 2
+ elif length == 127:
+ while len(self._buffer) < at + 8:
+ self._fill()
+ length = struct.unpack(">Q", self._buffer[at:at + 8])[0]
+ at += 8
+
+ while len(self._buffer) < at + length:
+ self._fill()
+
+ payload = self._buffer[at:at + length]
+ self._buffer = self._buffer[at + length:]
+
+ if opcode == OPCODE_CLOSE:
+ raise ControlError("the game closed the connection")
+ if opcode == OPCODE_PING:
+ self._send_frame(OPCODE_PONG, payload)
+ continue
+ if opcode == OPCODE_PONG:
+ continue
+ return payload.decode("utf-8", "replace")
+
+ # -- commands ---------------------------------------------------------
+
+ def send(self, command):
+ """Send one command and return the reply, decoded from JSON."""
+ self._send_frame(OPCODE_TEXT, command.encode("utf-8"))
+ reply = self._read_frame()
+ try:
+ return json.loads(reply)
+ except ValueError:
+ raise ControlError("the game answered something that is not JSON: %r" % reply)
+
+ # a few names so that calling code reads like what it is doing
+
+ def status(self):
+ return self.send("status")
+
+ def spawn(self, slot, template, count, x, y, spacing=None):
+ line = "spawn %d %s %d %g %g" % (slot, template, count, x, y)
+ if spacing is not None:
+ line += " %g" % spacing
+ return self.send(line)
+
+ def move(self, slot, selector, x, y):
+ return self.send("move %d %s %g %g" % (slot, selector, x, y))
+
+ def attack_move(self, slot, selector, x, y):
+ return self.send("attackmove %d %s %g %g" % (slot, selector, x, y))
+
+ def stop(self, slot, selector):
+ return self.send("stop %d %s" % (slot, selector))
+
+ def screenshot(self):
+ return self.send("screenshot")
+
+
+def main(argv):
+ port = int(argv[1]) if len(argv) > 1 else DEFAULT_PORT
+ commands = argv[2:] or ["ping", "status"]
+
+ with Control(port) as game:
+ for command in commands:
+ print("%-60s -> %s" % (command, game.send(command)))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv))