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(gamenetwork): mbedTLS line-JSON client and -online switches
Olcay Seygan33b50ad2b60f
diff --git a/GeneralsMD/Code/BuildFingerprint.manifest b/GeneralsMD/Code/BuildFingerprint.manifestindex 0e3aa9bbd..af57647a7 100644--- a/GeneralsMD/Code/BuildFingerprint.manifest+++ b/GeneralsMD/Code/BuildFingerprint.manifest@@ -81,6 +81,7 @@ Data/Cinema/geproto_oasis.txtData/Cinema/gpu1m_battle.txtData/Cinema/gunfx.txtData/Cinema/headlights.txt+Data/Cinema/heathaze.txtData/Cinema/hero_loop.txtData/Cinema/hero_loop_01.txtData/Cinema/hero_loop_02.txt@@ -156,6 +157,7 @@ Data/Cinema/rf_thumb_fa.txtData/Cinema/rf_thumb_fe.txtData/Cinema/rf_town.txtData/Cinema/rf_watch.txt+Data/Cinema/rocketfx.txtData/Cinema/s240_beach.txtData/Cinema/s240_bridge.txtData/Cinema/s240_heli.txt@@ -170,6 +172,8 @@ Data/Cinema/scudlaunch_film.txtData/Cinema/shadowfar.txtData/Cinema/shadowpan.txtData/Cinema/spectre_reshoot.txt+Data/Cinema/summary_close.txt+Data/Cinema/summary_fire.txtData/Cinema/swpair_nuke.txtData/Cinema/swpair_scud.txtData/Cinema/thumb_chaos_a.txt@@ -182,6 +186,8 @@ Data/Cinema/tr_oasis.txtData/Cinema/tr_open.txtData/Cinema/tr_palms.txtData/Cinema/tr_watch.txt+Data/Cinema/tracers_desert.txt+Data/Cinema/tracers_snow.txtData/Cinema/v240_heli.txtData/Cinema/v240_hook.txtData/Cinema/v240_hook2.txt@@ -291,6 +297,7 @@ Data/Scenarios/glowmicrowave.txtData/Scenarios/gpu1m_battle.txtData/Scenarios/guardradius.txtData/Scenarios/gunfx.txt+Data/Scenarios/gunsnow.txtData/Scenarios/handicap.txtData/Scenarios/headlights.txtData/Scenarios/helislide.txt@@ -321,6 +328,7 @@ Data/Scenarios/jetrunway.txtData/Scenarios/jetsturn.txtData/Scenarios/jetturn.txtData/Scenarios/kargu.txt+Data/Scenarios/laserflow.txtData/Scenarios/laserglow.txtData/Scenarios/laserlook.txtData/Scenarios/leadinfantry.txt@@ -391,6 +399,7 @@ Data/Scenarios/rf_t2_wall.txtData/Scenarios/rf_t2_wolf.txtData/Scenarios/rf_thumb_fa.txtData/Scenarios/rf_thumb_fe.txt+Data/Scenarios/rocketfx.txtData/Scenarios/rocketglow.txtData/Scenarios/s240_beach.txtData/Scenarios/s240_bridge.txt@@ -420,6 +429,7 @@ Data/Scenarios/strikeair_nuke.txtData/Scenarios/strikeair_nukehelix.txtData/Scenarios/strikeair_particle.txtData/Scenarios/strikeair_scud.txt+Data/Scenarios/summaryclose.txtData/Scenarios/sun_cloak.txtData/Scenarios/sun_trees.txtData/Scenarios/swhole.txt@@ -1093,6 +1103,7 @@ GameEngine/Include/GameNetwork/NetPacket.hGameEngine/Include/GameNetwork/NetworkDefs.hGameEngine/Include/GameNetwork/NetworkInterface.hGameEngine/Include/GameNetwork/NetworkUtil.h+GameEngine/Include/GameNetwork/Online/OnlineConnection.hGameEngine/Include/GameNetwork/RankPointValue.hGameEngine/Include/GameNetwork/StallJudgement.hGameEngine/Include/GameNetwork/Transport.h@@ -1728,6 +1739,10 @@ GameEngine/Source/GameNetwork/NetMessageStream.cppGameEngine/Source/GameNetwork/NetPacket.cppGameEngine/Source/GameNetwork/Network.cppGameEngine/Source/GameNetwork/NetworkUtil.cpp+GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp+GameEngine/Source/GameNetwork/Online/OnlineConnection.cpp+GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp+GameEngine/Source/GameNetwork/Online/OnlineStats.cppGameEngine/Source/GameNetwork/StallJudgement.cppGameEngine/Source/GameNetwork/Transport.cppGameEngine/Source/GameNetwork/User.cpp@@ -3078,6 +3093,7 @@ Libraries/Source/gamespy-strlwr-c-only.patchLibraries/Source/glslang/.gitignoreLibraries/Source/lzhl-clear-history.patchLibraries/Source/max4sdk/.gitignore+Libraries/Source/mbedtls/.gitignoreLibraries/Source/miniaudio/.gitignoreLibraries/Source/profile/_pch.cppLibraries/Source/profile/_pch.h@@ -3226,6 +3242,7 @@ Tests/test_minimap_input.incTests/test_modern_water_config.cppTests/test_msvc_float_casts.cppTests/test_observer_camera.inc+Tests/test_online.cppTests/test_pixelcentre.cppTests/test_posix_draw_resolve.cppTests/test_posix_gpu_draw.cpp@@ -4232,6 +4249,9 @@ Tools/packaging-resolution-check.shTools/peacetime_layout.pyTools/pink_laser.pyTools/record-dx11-shaders.ps1+Tools/relay/README.md+Tools/relay/relay.js+Tools/relay/test.jsTools/replay-check.shTools/root-readonly-check.shTools/signal_marks.pydiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 626e435ed..179ed4370 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -129,7 +129,9 @@ set(VENDORED${COMP}/ZLib/deflate.c${COMP}/LZHCompress/CompLibSource/Lzhl.cpp# The GameSpy SDK is built everywhere since B6 (see "gamespy" below).- ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/GameSpy/CMakeLists.txt)+ ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/GameSpy/CMakeLists.txt+ # mbedTLS, the online service's TLS, everywhere too (see "mbedtls" below).+ ${CMAKE_CURRENT_SOURCE_DIR}/Libraries/Source/mbedtls/library/ssl_tls.c)# The DirectX 8 headers are only read by targets this file does not define on macOS, and A2 decides# what a Mac fetch pulls down. Demanding them here would stop a Mac configure over files nothing# portable includes.@@ -864,6 +866,19 @@ set(GS_BUILD_TESTS OFF CACHE BOOL "" FORCE)set(GS_INCLUDE_VOICE OFF CACHE BOOL "" FORCE)add_subdirectory(${LIBSRC}/GameSpy ${CMAKE_CURRENT_BINARY_DIR}/gamespy)+# ---- mbedtls --------------------------------------------------------------+# mbedTLS 3.6.7 (Apache-2.0), fetched by both vendor scripts: the TLS under the online service's lobby+# connection (onlineconnection below), on every platform, since WinHTTP would leave macOS and Linux out.+# Upstream's CMakeLists builds programs and tests and wants Python for files the release tarball already+# carries, so library/*.c is compiled here with the stock mbedtls_config.h. Windows' entropy source is+# BCryptGenRandom, and net_sockets.c is Winsock there.+file(GLOB MBEDTLS_SOURCES ${LIBSRC}/mbedtls/library/*.c)+add_library(mbedtls STATIC ${MBEDTLS_SOURCES})+target_include_directories(mbedtls PUBLIC ${LIBSRC}/mbedtls/include PRIVATE ${LIBSRC}/mbedtls/library)+if(ZH_PLATFORM_WINDOWS)+ target_link_libraries(mbedtls PUBLIC ws2_32 bcrypt)+endif()+# ---- SDL3 and miniaudio: the platform layer off Windows (decision 3) -------------------------------# Both are fetched by Tools/vendor.sh and neither is fetched on Windows, which keeps Win32Device and# Miles. Nothing links either yet: C2/C3 take SDL3's window and events, D4 its GPU API, C4 miniaudio.@@ -1053,6 +1068,17 @@ list(REMOVE_ITEM GAMEENGINE_SOURCES# includer - the live code went to GameNetwork/GameSpy/ instead.list(REMOVE_ITEM GAMEENGINE_SOURCES${GE}/Source/GameNetwork/GameSpyGameInfo.cpp)+# The online service's connection (TLS line, JSON reader and writer) knows nothing of the engine and is a+# library of its own, so test_online links it without the game. The adapters beside it stay in gameengine.+list(REMOVE_ITEM GAMEENGINE_SOURCES+ ${GE}/Source/GameNetwork/Online/OnlineConnection.cpp)+add_library(onlineconnection STATIC ${GE}/Source/GameNetwork/Online/OnlineConnection.cpp)+target_include_directories(onlineconnection PUBLIC ${GE}/Include)+target_link_libraries(onlineconnection PRIVATE mbedtls)+set_target_properties(onlineconnection PROPERTIES CXX_STANDARD 17)+if(ZH_PLATFORM_POSIX)+ target_link_libraries(onlineconnection PUBLIC Threads::Threads)+endif()# Platform bodies of one interface: each side's file is left out of the other's build, so Windows# gets exactly the sources it had. B5, bucket (c).# - StackDump.cpp: dbghelp symbol lookup and a structured-exception context walk, Windows only.@@ -1204,7 +1230,7 @@ if(ZH_PLATFORM_WINDOWS)endif()target_link_libraries(gameengine PUBLIC${ZH_GAMEENGINE_WW3D2} wwlib wwmath wwsaveload wwdebug wwutil compression ${ZH_GAMEENGINE_DEBUGLIB} ${ZH_GAMEENGINE_WWDOWNLOAD}- benchmark ${ZH_GAMEENGINE_EABROWSERDISPATCH} ${ZH_GAMEENGINE_PROFILE} gamespy+ benchmark ${ZH_GAMEENGINE_EABROWSERDISPATCH} ${ZH_GAMEENGINE_PROFILE} gamespy onlineconnection${ZH_GAMEENGINE_DINPUT8} ${ZH_GAMEENGINE_WIN32_SDK_LIBS})# B1's gate: the bytes a UnicodeString puts into the replay and network CRC, before and after@@ -2282,6 +2308,10 @@ endif()add_lib_test(test_compression compression)+# The online service's connection: the JSON line reader and writer, and a TLS loopback against a server+# inside the test, verified against a CA the test makes on the spot (no key or certificate is committed).+add_lib_test(test_online onlineconnection mbedtls)+# .w3d on-disk layout pins. Deliberately OUTSIDE the ZH_PLATFORM_WINDOWS guard# below: it is header-only, asserts sizeof/offsetof and links nothing but the# harness, so it builds on a platform where ww3d2 itself does not compile yet -diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 184bf5e3c..826be54f2 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -546,6 +546,18 @@ public:AsciiString m_lanPlayerName; ///< -lanname <name>: the name this copy takes in the LAN lobby (empty = the one in the preferences)AsciiString m_relayHost; ///< -relay <host:port>: the LAN lobby and its games go through this UDP relay (empty = real LAN; Transport.cpp)UnsignedShort m_relayPort; ///< the port of it, 0 when -relay named none+ AsciiString m_onlineHost; ///< -online <host:port>: the online service to log in to (empty = none; GameNetwork/Online)+ UnsignedShort m_onlinePort; ///< the port of it, 0 when -online named none+ AsciiString m_onlineCAFile; ///< -onlineca <file>: PEM CA the service's certificate is checked against (empty = the Let's Encrypt roots)+ AsciiString m_onlineUser; ///< -onlineuser <email>: log in with this account instead of the login screen's fields+ AsciiString m_onlinePass; ///< -onlinepass <password>: its password (a test switch: it shows in the process list)+ AsciiString m_onlineRegisterNick; ///< -onlineregister <nick>: create the -onlineuser account under this nick before logging in+ AsciiString m_onlineHostGame; ///< -onlinehost <name>: host a custom game of this name once in the lobby+ AsciiString m_onlineJoinGame; ///< -onlinejoin <name>: join the custom game of this name once it is listed+ AsciiString m_onlineSay; ///< -onlinesay <text>: say this in the lobby and again in the staging room+ AsciiString m_onlineMap; ///< -onlinemap <map>: the map -onlinehost sets+ Bool m_onlineStart; ///< -onlinestart: the -onlinehost host starts the game once someone has joined+ Bool m_quickMatchOnStart; ///< -quickmatch: go into the Quick Match queue once logged inBool m_lanLobbyOnStart; ///< -lanlobby: open the LAN lobby instead of stopping at the main menuBool m_skirmishLobbyOnStart; ///< -skirmishlobby: open the skirmish staging room instead of stopping at the main menuBool m_optionsMenuOnStart; ///< -optionsmenu: open the options screen over the main menu at startupdiff --git a/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineConnection.h b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineConnection.hnew file mode 100644index 000000000..bfe41cf55--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameNetwork/Online/OnlineConnection.h@@ -0,0 +1,156 @@+/*+** 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: OnlineConnection.h ///////////////////////////////////////////////////////////////////////+// Desc: The game's line to the online service: TLS over TCP, one flat JSON object per line.+///////////////////////////////////////////////////////////////////////////////////////////////////++#pragma once++#ifndef _ONLINE_CONNECTION_H_+#define _ONLINE_CONNECTION_H_++#include <string>+#include <utility>+#include <vector>++/* The lobby protocol (docs/plans/ONLINE-SERVICE.md in the owner's workspace) sends one JSON object per+ line, at most ONLINE_MAX_LINE bytes before the newline, its type in "t". A value is a scalar (string,+ number, true, false, null) or an array of scalars; nothing nests further, which is what keeps this+ reader a page long. Nothing in this file or its .cpp knows the engine: it builds as a library of its+ own, so test_online drives it without linking the game. */++enum { ONLINE_MAX_LINE = 8192 };++struct OnlineValue+{+ enum Kind { NUL, BOOLEAN, NUMBER, STRING, ARRAY };+ Kind kind;+ bool boolean;+ std::string text; ///< a STRING's UTF-8, or a NUMBER's JSON spelling (kept as text, so a 64-bit id survives)+ std::vector<OnlineValue> items; ///< an ARRAY's scalars++ OnlineValue() : kind( NUL ), boolean( false ) {}+};++class OnlineMessage+{+public:+ /* Reading. A missing key or one of another kind gives the default. */+ bool has( const char *key ) const;+ const OnlineValue *find( const char *key ) const;+ std::string getString( const char *key, const char *otherwise = "" ) const;+ long long getInt( const char *key, long long otherwise = 0 ) const;+ double getNumber( const char *key, double otherwise = 0.0 ) const;+ bool getBool( const char *key, bool otherwise = false ) const;+ std::vector<std::string> getStrings( const char *key ) const; ///< an array's strings; other items are skipped+ std::vector<long long> getInts( const char *key ) const; ///< an array's numbers as integers+ std::string type() const { return getString( "t" ); }++ /* Writing. Setting a key that is there replaces it; keys keep the order they were first set in. */+ OnlineMessage &setString( const char *key, const std::string &value );+ OnlineMessage &setInt( const char *key, long long value );+ OnlineMessage &setNumber( const char *key, double value ); ///< NaN and infinity are written as null: JSON has neither+ OnlineMessage &setBool( const char *key, bool value );+ OnlineMessage &setNull( const char *key );+ OnlineMessage &setStrings( const char *key, const std::vector<std::string> &values );+ OnlineMessage &setInts( const char *key, const std::vector<long long> &values );+ OnlineMessage &set( const char *key, const OnlineValue &value );++ void clear() { m_fields.clear(); }+ size_t size() const { return m_fields.size(); }+ const std::vector< std::pair<std::string, OnlineValue> > &fields() const { return m_fields; }++ /* The object as one line, newline included. False when a string is not valid UTF-8 or the line would+ be longer than ONLINE_MAX_LINE; out is left empty then. */+ bool toLine( std::string &out ) const;++ /* One line, without its newline (a trailing CR is allowed). False on anything but a flat object of+ scalars and arrays of scalars in valid UTF-8: a nested object or array, a duplicate key, a bad+ escape, a lone surrogate, \u0000, a raw control character, trailing text. out is cleared first. */+ static bool parse( const char *line, size_t length, OnlineMessage &out );++private:+ std::vector< std::pair<std::string, OnlineValue> > m_fields;+};++/* Cuts a byte stream into lines. A line longer than ONLINE_MAX_LINE is dropped whole, up to and+ including its newline, and reported once as OVERSIZE; blank lines are skipped. */+class OnlineLineReader+{+public:+ enum Result { NONE, LINE, OVERSIZE };++ OnlineLineReader() : m_skipping( false ) {}+ void feed( const char *bytes, size_t count );+ Result next( std::string &line ); ///< line without its newline or a trailing CR++private:+ std::string m_buffer;+ bool m_skipping; ///< inside an oversize line, throwing bytes away until its newline+};++/* True when the bytes are UTF-8 as RFC 3629 has it: no overlong forms, no surrogates, nothing past U+10FFFF. */+bool OnlineIsUtf8( const char *bytes, size_t count );++/* A TLS client to the service on a thread of its own, so a slow DNS answer, an unreachable host or a+ handshake over a bad link never holds up a game frame. The game calls receive() once a pass and+ send() whenever it likes; both only touch queues.++ OnlineConnection c;+ c.connect( "lobby.example", 7000, caPem ); // caPem empty: the Let's Encrypt roots below+ ...+ OnlineMessage m;+ while (c.receive( m )) handle( m );+ if (c.state() == OnlineConnection::CLOSED) report( c.error() );++ The certificate is checked against the CA in caPem and the host name given to connect(). TLS 1.2+ only for now; the .cpp says why. */+class OnlineConnection+{+public:+ enum State { IDLE, CONNECTING, OPEN, CLOSED };++ OnlineConnection();+ ~OnlineConnection(); ///< closes: tens of milliseconds, or what is left of a DNS lookup under way++ /* Starts the thread. False when a connection is already running (error() is then left alone), and+ false with error() set when the address is empty or the CA does not parse; nothing has touched the+ network then. */+ bool connect( const std::string &host, unsigned short port, const std::string &caPem );++ bool send( const OnlineMessage &message ); ///< queued; false when not CONNECTING or OPEN, or toLine() refuses it+ bool receive( OnlineMessage &message ); ///< the next message that arrived, if any+ void close(); ///< hangs up and joins the thread; state() is CLOSED after++ State state() const;+ std::string error() const; ///< why the connection ended or failed to start; empty while it is fine+ unsigned droppedLines() const; ///< received lines that were oversize or not a flat JSON object++ /* ISRG Root X1 and X2, the roots Let's Encrypt chains to, as PEM. */+ static const char *defaultRoots();++private:+ OnlineConnection( const OnlineConnection & );+ OnlineConnection &operator=( const OnlineConnection & );++ struct Impl;+ Impl *m_impl;+};++#endif // _ONLINE_CONNECTION_H_diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex b51b21be3..ec7642584 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -2561,25 +2561,67 @@ Int parseLanName(char *args[], int num)/* -relay <host:port> puts the LAN lobby and its games through a UDP relay instead of the local network,so two homes behind NAT can play (Transport.cpp has the envelope). The host is resolved when thelobby opens; a missing port is kept as 0, which the lobby reports as a socket error. */-Int parseRelay(char *args[], int num)+static void splitHostPort( const char *arg, AsciiString &host, UnsignedShort &port ){- if (TheWritableGlobalData && num > 1)+ host = arg;+ port = 0;+ const char *colon = strrchr( arg, ':' );+ if (colon){- AsciiString host = args[1];- const char *colon = strrchr( args[1], ':' );- UnsignedShort port = 0;- if (colon)- {- host = std::string( args[1], colon - args[1] ).c_str();- const Int number = atoi( colon + 1 );- port = (number >= 1 && number <= 65535) ? (UnsignedShort)number : 0;- }- TheWritableGlobalData->m_relayHost = host;- TheWritableGlobalData->m_relayPort = port;+ host = std::string( arg, colon - arg ).c_str();+ const Int number = atoi( colon + 1 );+ port = (number >= 1 && number <= 65535) ? (UnsignedShort)number : 0;}+}++Int parseRelay(char *args[], int num)+{+ if (TheWritableGlobalData && num > 1)+ splitHostPort( args[1], TheWritableGlobalData->m_relayHost, TheWritableGlobalData->m_relayPort );+ return 2;+}++/* -online <host:port> logs in to the online service there (GameNetwork/Online) instead of GameSpy, and the+ rest drive it from a script the way -lanlobby and -netgame drive the LAN (docs: ONLINE-SERVICE.md's Tests+ section in the owner's workspace). Each only fills a GlobalData field; the online screens read them.+ Without -online none of them does anything. */+Int parseOnline(char *args[], int num)+{+ if (TheWritableGlobalData && num > 1)+ splitHostPort( args[1], TheWritableGlobalData->m_onlineHost, TheWritableGlobalData->m_onlinePort );+ return 2;+}++static Int parseOnlineText( char *args[], int num, AsciiString GlobalData::*field )+{+ if (TheWritableGlobalData && num > 1)+ TheWritableGlobalData->*field = args[1];return 2;}+Int parseOnlineCA(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineCAFile ); }+Int parseOnlineUser(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineUser ); }+Int parseOnlinePass(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlinePass ); }+Int parseOnlineRegister(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineRegisterNick ); }+Int parseOnlineHostGame(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineHostGame ); }+Int parseOnlineJoin(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineJoinGame ); }+Int parseOnlineSay(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineSay ); }+Int parseOnlineMap(char *args[], int num) { return parseOnlineText( args, num, &GlobalData::m_onlineMap ); }++Int parseOnlineStart(char *args[], int num)+{+ if (TheWritableGlobalData)+ TheWritableGlobalData->m_onlineStart = TRUE;+ return 1;+}++Int parseQuickMatch(char *args[], int num)+{+ if (TheWritableGlobalData)+ TheWritableGlobalData->m_quickMatchOnStart = TRUE;+ return 1;+}+/* -lanlobby starts on the LAN screen rather than the main menu. Two copies on one machine arestarted by a script and the first thing both of them do is the same four clicks; this is thoseclicks. It turns the shell map off with it: Shell::showShell only puts the main menu on the@@ -3102,6 +3144,17 @@ static CommandLineParam params[] ={ "-lanip", parseLanIP },{ "-lanname", parseLanName },{ "-relay", parseRelay },+ { "-online", parseOnline },+ { "-onlineca", parseOnlineCA },+ { "-onlineuser", parseOnlineUser },+ { "-onlinepass", parseOnlinePass },+ { "-onlineregister", parseOnlineRegister },+ { "-onlinehost", parseOnlineHostGame },+ { "-onlinejoin", parseOnlineJoin },+ { "-onlinesay", parseOnlineSay },+ { "-onlinemap", parseOnlineMap },+ { "-onlinestart", parseOnlineStart },+ { "-quickmatch", parseQuickMatch },{ "-lanlobby", parseLanLobby },{ "-skirmishlobby", parseSkirmishLobby },{ "-factionpicker", parseFactionPicker },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 3ec674a7e..26b3e50d2 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -794,6 +794,18 @@ GlobalData::GlobalData()m_lanPlayerName.clear(); // the lobby name comes out of the preferences unless -lanname says otherwisem_relayHost.clear(); // a real LAN unless -relay names a relaym_relayPort = 0;+ m_onlineHost.clear(); // no online service unless -online names one, and none of the -online* scripting+ m_onlinePort = 0;+ m_onlineCAFile.clear();+ m_onlineUser.clear();+ m_onlinePass.clear();+ m_onlineRegisterNick.clear();+ m_onlineHostGame.clear();+ m_onlineJoinGame.clear();+ m_onlineSay.clear();+ m_onlineMap.clear();+ m_onlineStart = FALSE;+ m_quickMatchOnStart = FALSE;m_lanLobbyOnStart = FALSE;m_skirmishLobbyOnStart = FALSE;m_optionsMenuOnStart = FALSE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cppnew file mode 100644index 000000000..b83506d83--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineBuddy.cpp@@ -0,0 +1,22 @@+/*+** 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: OnlineBuddy.cpp //////////////////////////////////////////////////////////////////////////+// Desc: The buddy queue answered from the online service instead of GameSpy. Empty until that+// phase lands.+///////////////////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineConnection.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineConnection.cppnew file mode 100644index 000000000..41a76f988--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineConnection.cpp@@ -0,0 +1,1130 @@+/*+** 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: OnlineConnection.cpp /////////////////////////////////////////////////////////////////////+// Desc: The game's line to the online service: TLS over TCP, one flat JSON object per line.+///////////////////////////////////////////////////////////////////////////////////////////////////++/* Built as a library of its own (CMake target onlineconnection), not with the engine's precompiled+ header: it knows nothing of the engine, and test_online links it alone. */++#include "GameNetwork/Online/OnlineConnection.h"++#include <atomic>+#include <chrono>+#include <cmath>+#include <deque>+#include <mutex>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <thread>++#ifdef _WIN32+ #ifndef WIN32_LEAN_AND_MEAN+ #define WIN32_LEAN_AND_MEAN+ #endif+ #ifndef NOMINMAX+ #define NOMINMAX+ #endif+ #include <winsock2.h>+ #include <ws2tcpip.h>+ typedef SOCKET OnlineSocket;+ #define ONLINE_BAD_SOCKET INVALID_SOCKET+ static void closeSocket( OnlineSocket s ) { closesocket( s ); }+ static bool connectPending() { return WSAGetLastError() == WSAEWOULDBLOCK; }+ static void setBlocking( OnlineSocket s, bool block ) { u_long on = block ? 0 : 1; ioctlsocket( s, FIONBIO, &on ); }+ typedef int OnlineSockLen;+#else+ #include <errno.h>+ #include <fcntl.h>+ #include <netdb.h>+ #include <netinet/in.h>+ #include <sys/select.h>+ #include <sys/socket.h>+ #include <unistd.h>+ typedef int OnlineSocket;+ #define ONLINE_BAD_SOCKET (-1)+ static void closeSocket( OnlineSocket s ) { ::close( s ); }+ static bool connectPending() { return errno == EINPROGRESS || errno == EINTR; }+ static void setBlocking( OnlineSocket s, bool block )+ {+ const int flags = fcntl( s, F_GETFL, 0 );+ fcntl( s, F_SETFL, block ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK) );+ }+ typedef socklen_t OnlineSockLen;+#endif++#include "mbedtls/ctr_drbg.h"+#include "mbedtls/entropy.h"+#include "mbedtls/error.h"+#include "mbedtls/net_sockets.h"+#include "mbedtls/ssl.h"+#include "mbedtls/x509_crt.h"++//-------------------------------------------------------------------------------------------------+// UTF-8 and the JSON line+//-------------------------------------------------------------------------------------------------++bool OnlineIsUtf8( const char *bytes, size_t count )+{+ const unsigned char *s = (const unsigned char *)bytes;+ size_t i = 0;+ while (i < count)+ {+ const unsigned c = s[ i ];+ if (c < 0x80)+ {+ ++i;+ continue;+ }+ size_t more;+ unsigned code, least;+ if ((c & 0xE0) == 0xC0) { more = 1; code = c & 0x1F; least = 0x80; }+ else if ((c & 0xF0) == 0xE0) { more = 2; code = c & 0x0F; least = 0x800; }+ else if ((c & 0xF8) == 0xF0) { more = 3; code = c & 0x07; least = 0x10000; }+ else return false;+ if (more >= count - i)+ return false;+ for (size_t k = 1; k <= more; ++k)+ {+ const unsigned b = s[ i + k ];+ if ((b & 0xC0) != 0x80)+ return false;+ code = (code << 6) | (b & 0x3F);+ }+ if (code < least || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF))+ return false;+ i += more + 1;+ }+ return true;+}++// what may go on the wire as a string: UTF-8 with no NUL, which the reader refuses as \u0000+static bool isCleanText( const std::string &s )+{+ return memchr( s.data(), 0, s.size() ) == NULL && OnlineIsUtf8( s.data(), s.size() );+}++namespace+{+ struct Cursor+ {+ const char *p;+ const char *end;+ bool atEnd() const { return p >= end; }+ };+}++// one line, so a newline is never whitespace here+static void skipSpace( Cursor &c )+{+ while (!c.atEnd() && (*c.p == ' ' || *c.p == '\t' || *c.p == '\r'))+ ++c.p;+}++static bool isDigit( char ch ) { return ch >= '0' && ch <= '9'; }++static bool parseNumber( Cursor &c, std::string &out )+{+ const char *start = c.p;+ if (!c.atEnd() && *c.p == '-')+ ++c.p;+ if (c.atEnd())+ return false;+ if (*c.p == '0')+ ++c.p;+ else if (isDigit( *c.p ))+ while (!c.atEnd() && isDigit( *c.p )) ++c.p;+ else+ return false;+ if (!c.atEnd() && *c.p == '.')+ {+ ++c.p;+ if (c.atEnd() || !isDigit( *c.p ))+ return false;+ while (!c.atEnd() && isDigit( *c.p )) ++c.p;+ }+ if (!c.atEnd() && (*c.p == 'e' || *c.p == 'E'))+ {+ ++c.p;+ if (!c.atEnd() && (*c.p == '+' || *c.p == '-'))+ ++c.p;+ if (c.atEnd() || !isDigit( *c.p ))+ return false;+ while (!c.atEnd() && isDigit( *c.p )) ++c.p;+ }+ out.assign( start, c.p );+ return true;+}++static bool isJsonNumber( const std::string &text )+{+ Cursor c = { text.data(), text.data() + text.size() };+ std::string ignored;+ return parseNumber( c, ignored ) && c.atEnd();+}++static bool parseHex4( Cursor &c, unsigned &out )+{+ if (c.end - c.p < 4)+ return false;+ out = 0;+ for (int i = 0; i < 4; ++i)+ {+ const char ch = *c.p++;+ out <<= 4;+ if (ch >= '0' && ch <= '9') out |= ch - '0';+ else if (ch >= 'a' && ch <= 'f') out |= ch - 'a' + 10;+ else if (ch >= 'A' && ch <= 'F') out |= ch - 'A' + 10;+ else return false;+ }+ return true;+}++static void appendUtf8( std::string &out, unsigned code )+{+ if (code < 0x80)+ out += (char)code;+ else if (code < 0x800)+ {+ out += (char)(0xC0 | (code >> 6));+ out += (char)(0x80 | (code & 0x3F));+ }+ else if (code < 0x10000)+ {+ out += (char)(0xE0 | (code >> 12));+ out += (char)(0x80 | ((code >> 6) & 0x3F));+ out += (char)(0x80 | (code & 0x3F));+ }+ else+ {+ out += (char)(0xF0 | (code >> 18));+ out += (char)(0x80 | ((code >> 12) & 0x3F));+ out += (char)(0x80 | ((code >> 6) & 0x3F));+ out += (char)(0x80 | (code & 0x3F));+ }+}++// raw bytes were checked as UTF-8 for the whole line before this runs, and an escape makes UTF-8 itself+static bool parseString( Cursor &c, std::string &out )+{+ if (c.atEnd() || *c.p != '"')+ return false;+ ++c.p;+ while (!c.atEnd())+ {+ const unsigned char ch = (unsigned char)*c.p++;+ if (ch == '"')+ return true;+ if (ch < 0x20)+ return false;+ if (ch != '\\')+ {+ out += (char)ch;+ continue;+ }+ if (c.atEnd())+ return false;+ switch (*c.p++)+ {+ case '"': out += '"'; break;+ case '\\': out += '\\'; break;+ case '/': out += '/'; break;+ case 'b': out += '\b'; break;+ case 'f': out += '\f'; break;+ case 'n': out += '\n'; break;+ case 'r': out += '\r'; break;+ case 't': out += '\t'; break;+ case 'u':+ {+ unsigned code;+ if (!parseHex4( c, code ))+ return false;+ if (code >= 0xD800 && code <= 0xDBFF)+ {+ unsigned low;+ if (c.end - c.p < 2 || c.p[ 0 ] != '\\' || c.p[ 1 ] != 'u')+ return false;+ c.p += 2;+ if (!parseHex4( c, low ) || low < 0xDC00 || low > 0xDFFF)+ return false;+ code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00);+ }+ else if (code >= 0xDC00 && code <= 0xDFFF)+ return false;+ if (code == 0)+ return false; // a NUL would cut every C string the game keeps it in+ appendUtf8( out, code );+ break;+ }+ default:+ return false;+ }+ }+ return false;+}++static bool parseLiteral( Cursor &c, const char *word )+{+ const size_t n = strlen( word );+ if ((size_t)(c.end - c.p) < n || memcmp( c.p, word, n ) != 0)+ return false;+ c.p += n;+ return true;+}++static bool parseScalar( Cursor &c, OnlineValue &out )+{+ if (c.atEnd())+ return false;+ switch (*c.p)+ {+ case '"':+ out.kind = OnlineValue::STRING;+ return parseString( c, out.text );+ case 't':+ out.kind = OnlineValue::BOOLEAN;+ out.boolean = true;+ return parseLiteral( c, "true" );+ case 'f':+ out.kind = OnlineValue::BOOLEAN;+ out.boolean = false;+ return parseLiteral( c, "false" );+ case 'n':+ out.kind = OnlineValue::NUL;+ return parseLiteral( c, "null" );+ default:+ out.kind = OnlineValue::NUMBER;+ return parseNumber( c, out.text );+ }+}++static bool parseValue( Cursor &c, OnlineValue &out )+{+ if (c.atEnd() || *c.p != '[')+ return parseScalar( c, out );+ out.kind = OnlineValue::ARRAY;+ ++c.p;+ skipSpace( c );+ if (!c.atEnd() && *c.p == ']')+ {+ ++c.p;+ return true;+ }+ for (;;)+ {+ OnlineValue item;+ if (!parseScalar( c, item ))+ return false;+ out.items.push_back( item );+ skipSpace( c );+ if (c.atEnd())+ return false;+ const char ch = *c.p++;+ if (ch == ']')+ return true;+ if (ch != ',')+ return false;+ skipSpace( c );+ }+}++bool OnlineMessage::parse( const char *line, size_t length, OnlineMessage &out )+{+ out.clear();+ if (length > ONLINE_MAX_LINE || !OnlineIsUtf8( line, length ))+ return false;+ Cursor c = { line, line + length };+ skipSpace( c );+ if (c.atEnd() || *c.p++ != '{')+ return false;+ skipSpace( c );+ bool ok = false;+ if (!c.atEnd() && *c.p == '}')+ {+ ++c.p;+ ok = true;+ }+ else+ {+ for (;;)+ {+ std::string key;+ OnlineValue value;+ if (!parseString( c, key ) || out.has( key.c_str() ))+ break;+ skipSpace( c );+ if (c.atEnd() || *c.p++ != ':')+ break;+ skipSpace( c );+ if (!parseValue( c, value ))+ break;+ out.m_fields.push_back( std::make_pair( key, value ) );+ skipSpace( c );+ if (c.atEnd())+ break;+ const char ch = *c.p++;+ if (ch == '}')+ {+ ok = true;+ break;+ }+ if (ch != ',')+ break;+ skipSpace( c );+ }+ }+ skipSpace( c );+ if (!ok || !c.atEnd())+ {+ out.clear();+ return false;+ }+ return true;+}++static void appendQuoted( std::string &out, const std::string &s )+{+ out += '"';+ for (size_t i = 0; i < s.size(); ++i)+ {+ const unsigned char ch = (unsigned char)s[ i ];+ switch (ch)+ {+ case '"': out += "\\\""; break;+ case '\\': out += "\\\\"; break;+ case '\n': out += "\\n"; break;+ case '\r': out += "\\r"; break;+ case '\t': out += "\\t"; break;+ case '\b': out += "\\b"; break;+ case '\f': out += "\\f"; break;+ default:+ if (ch < 0x20)+ {+ char escape[ 8 ];+ snprintf( escape, sizeof( escape ), "\\u%04x", ch );+ out += escape;+ }+ else+ out += (char)ch;+ }+ }+ out += '"';+}++static bool appendScalar( std::string &out, const OnlineValue &v )+{+ switch (v.kind)+ {+ case OnlineValue::NUL: out += "null"; return true;+ case OnlineValue::BOOLEAN: out += v.boolean ? "true" : "false"; return true;+ case OnlineValue::NUMBER:+ if (!isJsonNumber( v.text ))+ return false;+ out += v.text;+ return true;+ case OnlineValue::STRING:+ if (!isCleanText( v.text ))+ return false;+ appendQuoted( out, v.text );+ return true;+ default:+ return false;+ }+}++bool OnlineMessage::toLine( std::string &out ) const+{+ out = "{";+ bool ok = true;+ for (size_t i = 0; i < m_fields.size() && ok; ++i)+ {+ const OnlineValue &v = m_fields[ i ].second;+ ok = isCleanText( m_fields[ i ].first );+ if (!ok)+ break;+ if (i > 0)+ out += ',';+ appendQuoted( out, m_fields[ i ].first );+ out += ':';+ if (v.kind == OnlineValue::ARRAY)+ {+ out += '[';+ for (size_t k = 0; k < v.items.size() && ok; ++k)+ {+ if (k > 0)+ out += ',';+ ok = appendScalar( out, v.items[ k ] );+ }+ out += ']';+ }+ else+ ok = appendScalar( out, v );+ }+ out += '}';+ if (!ok || out.size() > ONLINE_MAX_LINE)+ {+ out.clear();+ return false;+ }+ out += '\n';+ return true;+}++//-------------------------------------------------------------------------------------------------+// OnlineMessage's accessors+//-------------------------------------------------------------------------------------------------++const OnlineValue *OnlineMessage::find( const char *key ) const+{+ for (size_t i = 0; i < m_fields.size(); ++i)+ if (m_fields[ i ].first == key)+ return &m_fields[ i ].second;+ return NULL;+}++bool OnlineMessage::has( const char *key ) const+{+ return find( key ) != NULL;+}++std::string OnlineMessage::getString( const char *key, const char *otherwise ) const+{+ const OnlineValue *v = find( key );+ return (v && v->kind == OnlineValue::STRING) ? v->text : std::string( otherwise );+}++// an integer spelling exactly through strtoll, so ids past 2^53 survive; anything with a fraction or an+// exponent through strtod. Both read the C locale's '.', which is the only one the game runs in.+static long long numberAsInt( const std::string &text )+{+ if (text.find_first_of( ".eE" ) == std::string::npos)+ return strtoll( text.c_str(), NULL, 10 );+ return (long long)strtod( text.c_str(), NULL );+}++long long OnlineMessage::getInt( const char *key, long long otherwise ) const+{+ const OnlineValue *v = find( key );+ return (v && v->kind == OnlineValue::NUMBER) ? numberAsInt( v->text ) : otherwise;+}++double OnlineMessage::getNumber( const char *key, double otherwise ) const+{+ const OnlineValue *v = find( key );+ return (v && v->kind == OnlineValue::NUMBER) ? strtod( v->text.c_str(), NULL ) : otherwise;+}++bool OnlineMessage::getBool( const char *key, bool otherwise ) const+{+ const OnlineValue *v = find( key );+ return (v && v->kind == OnlineValue::BOOLEAN) ? v->boolean : otherwise;+}++std::vector<std::string> OnlineMessage::getStrings( const char *key ) const+{+ std::vector<std::string> result;+ const OnlineValue *v = find( key );+ if (v && v->kind == OnlineValue::ARRAY)+ for (size_t i = 0; i < v->items.size(); ++i)+ if (v->items[ i ].kind == OnlineValue::STRING)+ result.push_back( v->items[ i ].text );+ return result;+}++std::vector<long long> OnlineMessage::getInts( const char *key ) const+{+ std::vector<long long> result;+ const OnlineValue *v = find( key );+ if (v && v->kind == OnlineValue::ARRAY)+ for (size_t i = 0; i < v->items.size(); ++i)+ if (v->items[ i ].kind == OnlineValue::NUMBER)+ result.push_back( numberAsInt( v->items[ i ].text ) );+ return result;+}++OnlineMessage &OnlineMessage::set( const char *key, const OnlineValue &value )+{+ for (size_t i = 0; i < m_fields.size(); ++i)+ if (m_fields[ i ].first == key)+ {+ m_fields[ i ].second = value;+ return *this;+ }+ m_fields.push_back( std::make_pair( std::string( key ), value ) );+ return *this;+}++OnlineMessage &OnlineMessage::setString( const char *key, const std::string &value )+{+ OnlineValue v;+ v.kind = OnlineValue::STRING;+ v.text = value;+ return set( key, v );+}++static OnlineValue intValue( long long value )+{+ OnlineValue v;+ v.kind = OnlineValue::NUMBER;+ char text[ 32 ];+ snprintf( text, sizeof( text ), "%lld", value );+ v.text = text;+ return v;+}++OnlineMessage &OnlineMessage::setInt( const char *key, long long value )+{+ return set( key, intValue( value ) );+}++OnlineMessage &OnlineMessage::setNumber( const char *key, double value )+{+ if (!std::isfinite( value ))+ return setNull( key );+ OnlineValue v;+ v.kind = OnlineValue::NUMBER;+ char text[ 40 ];+ snprintf( text, sizeof( text ), "%.17g", value );+ v.text = text;+ return set( key, v );+}++OnlineMessage &OnlineMessage::setBool( const char *key, bool value )+{+ OnlineValue v;+ v.kind = OnlineValue::BOOLEAN;+ v.boolean = value;+ return set( key, v );+}++OnlineMessage &OnlineMessage::setNull( const char *key )+{+ return set( key, OnlineValue() );+}++OnlineMessage &OnlineMessage::setStrings( const char *key, const std::vector<std::string> &values )+{+ OnlineValue v;+ v.kind = OnlineValue::ARRAY;+ for (size_t i = 0; i < values.size(); ++i)+ {+ OnlineValue item;+ item.kind = OnlineValue::STRING;+ item.text = values[ i ];+ v.items.push_back( item );+ }+ return set( key, v );+}++OnlineMessage &OnlineMessage::setInts( const char *key, const std::vector<long long> &values )+{+ OnlineValue v;+ v.kind = OnlineValue::ARRAY;+ for (size_t i = 0; i < values.size(); ++i)+ v.items.push_back( intValue( values[ i ] ) );+ return set( key, v );+}++//-------------------------------------------------------------------------------------------------+// OnlineLineReader+//-------------------------------------------------------------------------------------------------++void OnlineLineReader::feed( const char *bytes, size_t count )+{+ m_buffer.append( bytes, count );+}++OnlineLineReader::Result OnlineLineReader::next( std::string &line )+{+ for (;;)+ {+ const size_t newline = m_buffer.find( '\n' );+ if (m_skipping)+ {+ if (newline == std::string::npos)+ {+ m_buffer.clear();+ return NONE;+ }+ m_buffer.erase( 0, newline + 1 );+ m_skipping = false;+ continue;+ }+ if (newline == std::string::npos)+ {+ // one byte over the limit is still a line if it is the CR of a CRLF, so wait for one more+ if (m_buffer.size() > (size_t)ONLINE_MAX_LINE + 1)+ {+ m_buffer.clear();+ m_skipping = true;+ return OVERSIZE;+ }+ return NONE;+ }+ size_t length = newline;+ if (length > 0 && m_buffer[ length - 1 ] == '\r')+ --length;+ if (length > ONLINE_MAX_LINE)+ {+ m_buffer.erase( 0, newline + 1 );+ return OVERSIZE;+ }+ if (length == 0)+ {+ m_buffer.erase( 0, newline + 1 );+ continue;+ }+ line.assign( m_buffer, 0, length );+ m_buffer.erase( 0, newline + 1 );+ return LINE;+ }+}++//-------------------------------------------------------------------------------------------------+// OnlineConnection+//-------------------------------------------------------------------------------------------------++/* ponytail: TLS 1.2 only. The stock mbedtls_config.h has no MBEDTLS_THREADING_C, and mbedTLS 3.6 runs+ TLS 1.3 on PSA's global key store, which is only safe from one thread at a time; test_online's server+ and this client each run on their own. TLS 1.2 keeps every piece of state in the connection's own+ contexts. Lift it with MBEDTLS_THREADING_C (an ALT mutex on Windows, which has no pthread). */+static const int READ_SLICE_MS = 20; // how long a read waits before the queue to send is looked at again+static const int CONNECT_TIMEOUT_MS = 10000;+static const int HANDSHAKE_TIMEOUT_MS = 10000;++struct OnlineConnection::Impl+{+ mutable std::mutex lock;+ std::thread thread;+ std::atomic<bool> stop;+ State state;+ std::string error;+ std::deque<std::string> outgoing;+ std::deque<OnlineMessage> incoming;+ unsigned dropped;+ std::string host;+ unsigned short port;+ mbedtls_x509_crt ca;++ Impl() : stop( false ), state( IDLE ), dropped( 0 ), port( 0 ) { mbedtls_x509_crt_init( &ca ); }+ ~Impl() { mbedtls_x509_crt_free( &ca ); }++ void finish( const std::string &why )+ {+ std::lock_guard<std::mutex> guard( lock );+ state = CLOSED;+ if (!stop)+ error = why;+ outgoing.clear();+ }+ void run();+};++static std::string describe( int code )+{+ char text[ 160 ];+ mbedtls_strerror( code, text, sizeof( text ) );+ return text;+}++static long long nowMS()+{+ return std::chrono::duration_cast<std::chrono::milliseconds>(+ std::chrono::steady_clock::now().time_since_epoch() ).count();+}++/* mbedtls_net_connect would do, but it blocks until the operating system gives up on an address, 21 s+ on Windows, and a game being closed would wait that out. This one tries each address in turn on a+ non-blocking socket and looks at the stop flag every 50 ms. */+static std::string openSocket( const std::string &host, unsigned short port, const std::atomic<bool> &stop, int &fd )+{+ char service[ 8 ];+ snprintf( service, sizeof( service ), "%u", port );+ addrinfo hints;+ memset( &hints, 0, sizeof( hints ) );+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ hints.ai_protocol = IPPROTO_TCP;+ addrinfo *list = NULL;+ if (getaddrinfo( host.c_str(), service, &hints, &list ) != 0 || list == NULL)+ return "could not resolve " + host;++ const long long deadline = nowMS() + CONNECT_TIMEOUT_MS;+ std::string why = "could not reach " + host + ":" + service;+ for (addrinfo *a = list; a != NULL && !stop && nowMS() < deadline; a = a->ai_next)+ {+ OnlineSocket s = socket( a->ai_family, a->ai_socktype, a->ai_protocol );+ if (s == ONLINE_BAD_SOCKET)+ continue;+#ifdef SO_NOSIGPIPE+ const int one = 1;+ setsockopt( s, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof( one ) );+#endif+ setBlocking( s, false );+ bool connected = ::connect( s, a->ai_addr, (OnlineSockLen)a->ai_addrlen ) == 0;+ bool waiting = !connected && connectPending();+ while (waiting && !stop && nowMS() < deadline)+ {+ fd_set writable, failed;+ FD_ZERO( &writable );+ FD_ZERO( &failed );+ FD_SET( s, &writable );+ FD_SET( s, &failed );+ timeval slice = { 0, 50000 };+ const int ready = select( (int)s + 1, NULL, &writable, &failed, &slice );+ if (ready < 0)+ break;+ if (ready == 0)+ continue;+ int problem = 0;+ OnlineSockLen size = sizeof( problem );+ getsockopt( s, SOL_SOCKET, SO_ERROR, (char *)&problem, &size );+ connected = problem == 0 && FD_ISSET( s, &writable );+ waiting = false;+ }+ if (connected)+ {+ setBlocking( s, true );+ fd = (int)s; // mbedtls_net_context keeps a socket as int, Windows' SOCKET included+ freeaddrinfo( list );+ return std::string();+ }+ closeSocket( s );+ }+ freeaddrinfo( list );+ return why;+}++// mbedtls_net_send writes with write(), and a peer gone away then raises SIGPIPE, which kills a process+// on Linux. MSG_NOSIGNAL is Linux's way out, SO_NOSIGPIPE above macOS's; Windows has no signal.+static int sendBio( void *context, const unsigned char *bytes, size_t count )+{+#ifdef MSG_NOSIGNAL+ const int fd = ((mbedtls_net_context *)context)->fd;+ const ssize_t sent = ::send( fd, bytes, count, MSG_NOSIGNAL );+ if (sent >= 0)+ return (int)sent;+ if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)+ return MBEDTLS_ERR_SSL_WANT_WRITE;+ if (errno == EPIPE || errno == ECONNRESET)+ return MBEDTLS_ERR_NET_CONN_RESET;+ return MBEDTLS_ERR_NET_SEND_FAILED;+#else+ return mbedtls_net_send( context, bytes, count );+#endif+}++static bool isRetry( int code )+{+ return code == MBEDTLS_ERR_SSL_WANT_READ || code == MBEDTLS_ERR_SSL_WANT_WRITE+ || code == MBEDTLS_ERR_SSL_TIMEOUT || code == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET;+}++void OnlineConnection::Impl::run()+{+#ifdef _WIN32+ WSADATA wsa;+ WSAStartup( MAKEWORD( 2, 2 ), &wsa );+#endif+ mbedtls_net_context net;+ mbedtls_ssl_context ssl;+ mbedtls_ssl_config conf;+ mbedtls_entropy_context entropy;+ mbedtls_ctr_drbg_context random;+ mbedtls_net_init( &net );+ mbedtls_ssl_init( &ssl );+ mbedtls_ssl_config_init( &conf );+ mbedtls_entropy_init( &entropy );+ mbedtls_ctr_drbg_init( &random );++ std::string why;+ int code = 0;+ do+ {+ static const char personal[] = "zhr online";+ if ((code = mbedtls_ctr_drbg_seed( &random, mbedtls_entropy_func, &entropy,+ (const unsigned char *)personal, sizeof( personal ) - 1 )) != 0)+ {+ why = "no random source: " + describe( code );+ break;+ }+ why = openSocket( host, port, stop, net.fd );+ if (!why.empty())+ break;++ if ((code = mbedtls_ssl_config_defaults( &conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,+ MBEDTLS_SSL_PRESET_DEFAULT )) != 0)+ {+ why = describe( code );+ break;+ }+ mbedtls_ssl_conf_authmode( &conf, MBEDTLS_SSL_VERIFY_REQUIRED );+ mbedtls_ssl_conf_ca_chain( &conf, &ca, NULL );+ mbedtls_ssl_conf_rng( &conf, mbedtls_ctr_drbg_random, &random );+ mbedtls_ssl_conf_max_tls_version( &conf, MBEDTLS_SSL_VERSION_TLS1_2 );+ mbedtls_ssl_conf_read_timeout( &conf, READ_SLICE_MS );+ if ((code = mbedtls_ssl_setup( &ssl, &conf )) != 0+ || (code = mbedtls_ssl_set_hostname( &ssl, host.c_str() )) != 0)+ {+ why = describe( code );+ break;+ }+ mbedtls_ssl_set_bio( &ssl, &net, sendBio, NULL, mbedtls_net_recv_timeout );++ const long long deadline = nowMS() + HANDSHAKE_TIMEOUT_MS;+ while ((code = mbedtls_ssl_handshake( &ssl )) != 0 && isRetry( code ) && !stop && nowMS() < deadline)+ ;+ if (code != 0)+ {+ if (code == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED)+ {+ char text[ 512 ];+ mbedtls_x509_crt_verify_info( text, sizeof( text ), "", mbedtls_ssl_get_verify_result( &ssl ) );+ why = "the server's certificate was refused: " + std::string( text );+ while (!why.empty() && (why[ why.size() - 1 ] == '\n'))+ why.erase( why.size() - 1 );+ }+ else if (isRetry( code ))+ why = "the TLS handshake timed out";+ else+ why = "the TLS handshake failed: " + describe( code );+ break;+ }+ {+ std::lock_guard<std::mutex> guard( lock );+ state = OPEN;+ }++ OnlineLineReader reader;+ std::deque<std::string> sending;+ while (!stop && why.empty())+ {+ {+ std::lock_guard<std::mutex> guard( lock );+ sending.swap( outgoing );+ }+ for (; !sending.empty() && why.empty(); sending.pop_front())+ {+ const std::string &line = sending.front();+ size_t done = 0;+ while (done < line.size() && !stop)+ {+ code = mbedtls_ssl_write( &ssl, (const unsigned char *)line.data() + done, line.size() - done );+ if (code > 0)+ done += code;+ else if (!isRetry( code ))+ {+ why = "the connection broke while sending: " + describe( code );+ break;+ }+ }+ }+ if (!why.empty())+ break;++ unsigned char bytes[ 4096 ];+ code = mbedtls_ssl_read( &ssl, bytes, sizeof( bytes ) );+ if (code > 0)+ {+ reader.feed( (const char *)bytes, code );+ std::string line;+ OnlineLineReader::Result result;+ while ((result = reader.next( line )) != OnlineLineReader::NONE)+ {+ OnlineMessage message;+ const bool ok = result == OnlineLineReader::LINE && OnlineMessage::parse( line.data(), line.size(), message );+ std::lock_guard<std::mutex> guard( lock );+ if (ok)+ incoming.push_back( message );+ else+ ++dropped;+ }+ }+ else if (code == 0 || code == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY)+ why = "the server closed the connection";+ else if (!isRetry( code ))+ why = "the connection broke: " + describe( code );+ }+ if (stop)+ mbedtls_ssl_close_notify( &ssl );+ } while (false);++ mbedtls_net_free( &net );+ mbedtls_ssl_free( &ssl );+ mbedtls_ssl_config_free( &conf );+ mbedtls_ctr_drbg_free( &random );+ mbedtls_entropy_free( &entropy );+#ifdef _WIN32+ WSACleanup();+#endif+ finish( why );+}++OnlineConnection::OnlineConnection() : m_impl( new Impl )+{+}++OnlineConnection::~OnlineConnection()+{+ close();+ delete m_impl;+}++bool OnlineConnection::connect( const std::string &host, unsigned short port, const std::string &caPem )+{+ if (m_impl->thread.joinable())+ {+ if (state() != CLOSED)+ return false; // error() stays the running connection's+ m_impl->thread.join();+ }++ std::lock_guard<std::mutex> guard( m_impl->lock );+ m_impl->state = CLOSED;+ m_impl->error.clear();+ m_impl->outgoing.clear();+ m_impl->incoming.clear();+ m_impl->dropped = 0;+ m_impl->stop = false;+ if (host.empty() || port == 0)+ {+ m_impl->error = "no server address";+ return false;+ }++ // mbedtls_x509_crt_parse wants a PEM's terminating NUL counted in the length+ const std::string pem = caPem.empty() ? std::string( defaultRoots() ) : caPem;+ mbedtls_x509_crt_free( &m_impl->ca );+ mbedtls_x509_crt_init( &m_impl->ca );+ const int code = mbedtls_x509_crt_parse( &m_impl->ca, (const unsigned char *)pem.c_str(), pem.size() + 1 );+ if (code < 0 || m_impl->ca.raw.len == 0)+ {+ m_impl->error = "the CA certificate does not parse: " + describe( code < 0 ? code : MBEDTLS_ERR_X509_INVALID_FORMAT );+ return false;+ }++ m_impl->host = host;+ m_impl->port = port;+ m_impl->state = CONNECTING;+ m_impl->thread = std::thread( &Impl::run, m_impl );+ return true;+}++bool OnlineConnection::send( const OnlineMessage &message )+{+ std::string line;+ if (!message.toLine( line ))+ return false;+ std::lock_guard<std::mutex> guard( m_impl->lock );+ if (m_impl->state != CONNECTING && m_impl->state != OPEN)+ return false;+ m_impl->outgoing.push_back( line );+ return true;+}++bool OnlineConnection::receive( OnlineMessage &message )+{+ std::lock_guard<std::mutex> guard( m_impl->lock );+ if (m_impl->incoming.empty())+ return false;+ message = m_impl->incoming.front();+ m_impl->incoming.pop_front();+ return true;+}++void OnlineConnection::close()+{+ m_impl->stop = true;+ if (m_impl->thread.joinable())+ m_impl->thread.join();+ std::lock_guard<std::mutex> guard( m_impl->lock );+ if (m_impl->state != IDLE)+ m_impl->state = CLOSED;+}++OnlineConnection::State OnlineConnection::state() const+{+ std::lock_guard<std::mutex> guard( m_impl->lock );+ return m_impl->state;+}++std::string OnlineConnection::error() const+{+ std::lock_guard<std::mutex> guard( m_impl->lock );+ return m_impl->error;+}++unsigned OnlineConnection::droppedLines() const+{+ std::lock_guard<std::mutex> guard( m_impl->lock );+ return m_impl->dropped;+}++// https://letsencrypt.org/certs/isrgrootx1.pem (SHA-256 96:BC:EC:06:...:DF:08:C6, until 2035-06-04) and+// https://letsencrypt.org/certs/isrg-root-x2.pem (SHA-256 69:72:9B:8E:...:CB:14:70, until 2040-09-17).+const char *OnlineConnection::defaultRoots()+{+ return+ "-----BEGIN CERTIFICATE-----\n"+ "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"+ "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"+ "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"+ "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"+ "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"+ "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"+ "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"+ "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"+ "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"+ "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"+ "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"+ "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"+ "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"+ "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"+ "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"+ "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"+ "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"+ "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"+ "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"+ "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"+ "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"+ "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"+ "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"+ "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"+ "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"+ "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"+ "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"+ "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"+ "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"+ "-----END CERTIFICATE-----\n"+ "-----BEGIN CERTIFICATE-----\n"+ "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n"+ "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n"+ "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n"+ "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n"+ "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n"+ "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n"+ "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n"+ "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n"+ "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n"+ "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n"+ "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n"+ "/q4AaOeMSQ+2b1tbFfLn\n"+ "-----END CERTIFICATE-----\n";+}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cppnew file mode 100644index 000000000..bac2d85af--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlinePeer.cpp@@ -0,0 +1,22 @@+/*+** 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: OnlinePeer.cpp ///////////////////////////////////////////////////////////////////////////+// Desc: The peer queue (login, chat rooms, game list, staging room, Quick Match) answered from the+// online service instead of GameSpy. Empty until that phase lands.+///////////////////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cppnew file mode 100644index 000000000..dfb443b7b--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Online/OnlineStats.cpp@@ -0,0 +1,22 @@+/*+** 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: OnlineStats.cpp //////////////////////////////////////////////////////////////////////////+// Desc: The persistent-storage queue (player stats, match results) answered from the online+// service instead of GameSpy. Empty until that phase lands.+///////////////////////////////////////////////////////////////////////////////////////////////////diff --git a/GeneralsMD/Code/Libraries/Source/mbedtls/.gitignore b/GeneralsMD/Code/Libraries/Source/mbedtls/.gitignorenew file mode 100644index 000000000..5e7d2734c--- /dev/null+++ b/GeneralsMD/Code/Libraries/Source/mbedtls/.gitignore@@ -0,0 +1,4 @@+# Ignore everything in this directory+*+# Except this file+!.gitignorediff --git a/GeneralsMD/Code/Tests/test_online.cpp b/GeneralsMD/Code/Tests/test_online.cppnew file mode 100644index 000000000..b72f3a55b--- /dev/null+++ b/GeneralsMD/Code/Tests/test_online.cpp@@ -0,0 +1,617 @@+/*+ * test_online: the online service's connection (GameNetwork/Online/OnlineConnection).+ *+ * The JSON line reader and writer through round trips and every way a line can be wrong, the line cutter+ * fed a byte at a time and past its limit, then a real TLS connection over loopback to a server running+ * in this process. The server's certificate is signed by a CA the test makes on the spot, so nothing+ * secret is committed and nothing expires: the client has to accept it against that CA and refuse it+ * against another.+ */++#include "test_harness.h"++#include "GameNetwork/Online/OnlineConnection.h"++#include <chrono>+#include <string>+#include <thread>+#include <vector>++#ifdef _WIN32+ #ifndef WIN32_LEAN_AND_MEAN+ #define WIN32_LEAN_AND_MEAN+ #endif+ #include <winsock2.h>+ typedef int TestSockLen;+#else+ #include <arpa/inet.h>+ #include <netinet/in.h>+ #include <sys/socket.h>+ typedef socklen_t TestSockLen;+#endif++#include "mbedtls/ctr_drbg.h"+#include "mbedtls/entropy.h"+#include "mbedtls/net_sockets.h"+#include "mbedtls/pk.h"+#include "mbedtls/ssl.h"+#include "mbedtls/x509_crt.h"++//-------------------------------------------------------------------------------------------------+// the JSON line+//-------------------------------------------------------------------------------------------------++static bool parseText( const std::string &line, OnlineMessage &out )+{+ return OnlineMessage::parse( line.data(), line.size(), out );+}++TEST(online_json_round_trip)+{+ const std::string awkward = std::string( "quote \" backslash \\ slash / newline \n tab \t bell \x01 del \x7f" " end" );+ const std::string turkish = "\xC3\x87" "a\xC4\x9F" "r\xC4\xB1 \xE2\x9C\x93 \xF0\x9F\x98\x80"; // a Turkish name, a check mark and an emoji+ std::vector<std::string> maps;+ maps.push_back( "Tournament Desert" );+ maps.push_back( turkish );+ maps.push_back( "" );+ std::vector<long long> ids;+ ids.push_back( -1 );+ ids.push_back( 0 );+ ids.push_back( 9007199254740993LL ); // 2^53 + 1: lost if numbers went through a double++ OnlineMessage m;+ m.setString( "t", "qm.join" ).setString( "text", awkward ).setString( "nick", turkish )+ .setInt( "exe", 0x89ABCDEFLL ).setInt( "big", 9007199254740993LL ).setInt( "neg", -42 )+ .setNumber( "half", 0.5 ).setNumber( "nan", NAN ).setBool( "yes", true ).setBool( "no", false )+ .setNull( "nothing" ).setStrings( "maps", maps ).setInts( "ids", ids ).setStrings( "none", std::vector<std::string>() );+ m.setInt( "neg", -43 ); // replaces in place++ std::string line;+ CHECK( m.toLine( line ) );+ CHECK( !line.empty() && line[ line.size() - 1 ] == '\n' );+ CHECK_EQ( line.find( '\n' ), line.size() - 1 ); // one line: the newline in the text went out escaped+ CHECK_EQ( line.find( "\"t\":\"qm.join\"" ), (size_t)1 ); // keys keep their first order++ OnlineMessage back;+ CHECK( OnlineMessage::parse( line.data(), line.size() - 1, back ) );+ CHECK_EQ( back.size(), m.size() );+ CHECK( back.type() == "qm.join" );+ CHECK( back.getString( "text" ) == awkward );+ CHECK( back.getString( "nick" ) == turkish );+ CHECK_EQ( back.getInt( "exe" ), 0x89ABCDEFLL );+ CHECK_EQ( back.getInt( "big" ), 9007199254740993LL );+ CHECK_EQ( back.getInt( "neg" ), -43 );+ CHECK_EQ( back.getNumber( "half" ), 0.5 );+ CHECK( back.has( "nan" ) && back.find( "nan" )->kind == OnlineValue::NUL );+ CHECK( back.getBool( "yes" ) );+ CHECK( !back.getBool( "no", true ) );+ CHECK( back.find( "nothing" )->kind == OnlineValue::NUL );+ CHECK( back.getStrings( "maps" ) == maps );+ CHECK( back.getInts( "ids" ) == ids );+ CHECK( back.find( "none" )->kind == OnlineValue::ARRAY && back.find( "none" )->items.empty() );++ // missing keys and wrong kinds give the default+ CHECK( back.getString( "missing", "x" ) == "x" );+ CHECK_EQ( back.getInt( "nick", 7 ), 7 );+ CHECK( back.getString( "exe" ).empty() );++ OnlineMessage empty;+ CHECK( empty.toLine( line ) );+ CHECK( line == "{}\n" );+}++TEST(online_json_reads_escapes_and_spacing)+{+ OnlineMessage m;+ CHECK( parseText( " { \"t\" : \"say\" ,\t\"text\":\"a\\\"b\\\\c\\/d\\b\\f\\n\\r\\t\\u00e7\\u00C7\\u2713\\ud83d\\ude00\" , \"n\" : -1.5e+2 , \"z\":0 , \"e\":1E3 , \"a\" : [ 1 , \"x\" , true , null ] }\r", m ) );+ CHECK( m.getString( "text" ) == "a\"b\\c/d\b\f\n\r\t\xC3\xA7\xC3\x87\xE2\x9C\x93\xF0\x9F\x98\x80" );+ CHECK_EQ( m.getNumber( "n" ), -150.0 );+ CHECK_EQ( m.getInt( "n" ), -150 );+ CHECK_EQ( m.getInt( "z" ), 0 );+ CHECK_EQ( m.getInt( "e" ), 1000 );+ const OnlineValue *a = m.find( "a" );+ CHECK( a && a->kind == OnlineValue::ARRAY && a->items.size() == 4 );+ CHECK( parseText( "{}", m ) && m.size() == 0 );+ CHECK( parseText( "{\"a\":[]}", m ) && m.find( "a" )->items.empty() );+ CHECK( parseText( "{\"\":\"empty key\"}", m ) && m.getString( "" ) == "empty key" );+ // raw UTF-8 passes through untouched+ CHECK( parseText( "{\"t\":\"\xC3\x87\xF0\x9F\x98\x80\"}", m ) && m.type() == "\xC3\x87\xF0\x9F\x98\x80" );+}++TEST(online_json_refuses_what_is_not_a_flat_object)+{+ const char *bad[] = {+ "",+ " ",+ "[]",+ "\"t\"",+ "{",+ "{\"t\"}",+ "{\"t\":}",+ "{\"t\":\"x\",}",+ "{\"t\":\"x\"} trailing",+ "{\"t\":\"x\"}{}",+ "{\"t\":{\"nested\":1}}",+ "{\"t\":[1,[2]]}",+ "{\"t\":[1,{}]}",+ "{\"t\":[1,]}",+ "{\"t\":[1 2]}",+ "{\"t\":\"a\",\"t\":\"b\"}", // duplicate key+ "{\"t\":\"unterminated}",+ "{\"t\":\"\\x\"}", // unknown escape+ "{\"t\":\"\\u12\"}", // short \u+ "{\"t\":\"\\u12g4\"}",+ "{\"t\":\"\\ud83d\"}", // high surrogate alone+ "{\"t\":\"\\ud83d\\u0041\"}", // high surrogate, then not a low one+ "{\"t\":\"\\ude00\"}", // low surrogate alone+ "{\"t\":\"\\u0000\"}", // NUL+ "{\"t\":\"a\tb\"}", // raw control character+ "{\"t\":01}",+ "{\"t\":1.}",+ "{\"t\":.5}",+ "{\"t\":-}",+ "{\"t\":1e}",+ "{\"t\":+1}",+ "{\"t\":tru}",+ "{\"t\":True}",+ "{\"t\":NaN}",+ "{t:1}",+ "{'t':1}",+ "{\"t\":\"\xC0\x80\"}", // overlong NUL+ "{\"t\":\"\xE0\x80\xAF\"}", // overlong '/'+ "{\"t\":\"\xED\xA0\x80\"}", // a surrogate written as UTF-8+ "{\"t\":\"\xF4\x90\x80\x80\"}", // past U+10FFFF+ "{\"t\":\"\xC3\"}", // cut short+ "{\"t\":\"\xFF\"}",+ };+ for (size_t i = 0; i < sizeof( bad ) / sizeof( bad[ 0 ] ); ++i)+ {+ OnlineMessage m;+ m.setString( "stale", "x" );+ const bool parsed = parseText( bad[ i ], m );+ if (parsed)+ printf( " accepted: %s\n", bad[ i ] );+ CHECK( !parsed );+ CHECK_EQ( m.size(), (size_t)0 ); // cleared, never half filled+ }+ // a NUL byte in the middle of the line+ const std::string withNul( "{\"t\":\"a\0b\"}", 11 );+ OnlineMessage m;+ CHECK( !parseText( withNul, m ) );+}++TEST(online_json_line_limit)+{+ // {"t":"..."} is 8 bytes around the text+ OnlineMessage m;+ m.setString( "t", std::string( ONLINE_MAX_LINE - 8, 'x' ) );+ std::string line;+ CHECK( m.toLine( line ) );+ CHECK_EQ( line.size(), (size_t)ONLINE_MAX_LINE + 1 );+ OnlineMessage back;+ CHECK( OnlineMessage::parse( line.data(), line.size() - 1, back ) );++ m.setString( "t", std::string( ONLINE_MAX_LINE - 7, 'x' ) );+ CHECK( !m.toLine( line ) );+ CHECK( line.empty() );+ const std::string over = "{\"t\":\"" + std::string( ONLINE_MAX_LINE - 7, 'x' ) + "\"}";+ CHECK( !parseText( over, back ) );++ // escapes count at their written length+ m.setString( "t", std::string( ONLINE_MAX_LINE / 2, '"' ) );+ CHECK( !m.toLine( line ) );+}++TEST(online_json_writer_refuses_bad_text)+{+ OnlineMessage m;+ std::string line;+ CHECK( !m.setString( "t", "\xC3" ).toLine( line ) );+ CHECK( !m.setString( "t", "\xED\xA0\x80" ).toLine( line ) );+ CHECK( !m.setString( "t", std::string( "a\0b", 3 ) ).toLine( line ) );+ m.clear();+ CHECK( !m.setString( "\xFF", "x" ).toLine( line ) );+ m.clear();+ std::vector<std::string> list;+ list.push_back( "ok" );+ list.push_back( "\xC0\x80" );+ CHECK( !m.setStrings( "t", list ).toLine( line ) );+ m.clear();+ OnlineValue nested;+ nested.kind = OnlineValue::ARRAY;+ nested.items.push_back( OnlineValue() );+ nested.items[ 0 ].kind = OnlineValue::ARRAY;+ CHECK( !m.set( "t", nested ).toLine( line ) );+ m.clear();+ OnlineValue number;+ number.kind = OnlineValue::NUMBER;+ number.text = "1e";+ CHECK( !m.set( "t", number ).toLine( line ) );+}++TEST(online_utf8_validator)+{+ CHECK( OnlineIsUtf8( "", 0 ) );+ CHECK( OnlineIsUtf8( "plain", 5 ) );+ CHECK( OnlineIsUtf8( "\xC2\x80", 2 ) ); // U+0080, the first two-byte one+ CHECK( OnlineIsUtf8( "\xEF\xBF\xBF", 3 ) ); // U+FFFF+ CHECK( OnlineIsUtf8( "\xF4\x8F\xBF\xBF", 4 ) ); // U+10FFFF+ CHECK( !OnlineIsUtf8( "\xC1\xBF", 2 ) );+ CHECK( !OnlineIsUtf8( "\xF0\x8F\xBF\xBF", 4 ) ); // overlong+ CHECK( !OnlineIsUtf8( "\x80", 1 ) );+ CHECK( !OnlineIsUtf8( "\xE2\x9C", 2 ) );+ CHECK( !OnlineIsUtf8( "\xE2\x28\x93", 3 ) );+ CHECK( !OnlineIsUtf8( "\xF8\x88\x80\x80\x80", 5 ) );+}++//-------------------------------------------------------------------------------------------------+// the line cutter+//-------------------------------------------------------------------------------------------------++TEST(online_lines_arrive_in_pieces)+{+ const std::string stream = "{\"t\":\"a\"}\r\n\n\r\n{\"t\":\"b\",\"text\":\"\xC3\x87\"}\n{\"t\":\"c\"}";+ OnlineLineReader reader;+ std::vector<std::string> lines;+ std::string line;+ for (size_t i = 0; i < stream.size(); ++i)+ {+ reader.feed( &stream[ i ], 1 );+ OnlineLineReader::Result r;+ while ((r = reader.next( line )) != OnlineLineReader::NONE)+ {+ CHECK_EQ( r, OnlineLineReader::LINE );+ lines.push_back( line );+ }+ }+ CHECK_EQ( lines.size(), (size_t)2 ); // the third has no newline yet+ CHECK( lines.size() == 2 && lines[ 0 ] == "{\"t\":\"a\"}" && lines[ 1 ] == "{\"t\":\"b\",\"text\":\"\xC3\x87\"}" );+ reader.feed( "\n", 1 );+ CHECK_EQ( reader.next( line ), OnlineLineReader::LINE );+ CHECK( line == "{\"t\":\"c\"}" );+ CHECK_EQ( reader.next( line ), OnlineLineReader::NONE );+}++TEST(online_lines_over_the_limit_are_dropped_once)+{+ OnlineLineReader reader;+ std::string line;++ // exactly the limit, with a CRLF, is a line+ std::string full( ONLINE_MAX_LINE, 'a' );+ full += "\r\n";+ reader.feed( full.data(), full.size() );+ CHECK_EQ( reader.next( line ), OnlineLineReader::LINE );+ CHECK_EQ( line.size(), (size_t)ONLINE_MAX_LINE );++ // one over, complete in one feed, followed by a good line+ std::string over( ONLINE_MAX_LINE + 1, 'b' );+ over += "\n{\"t\":\"ok\"}\n";+ reader.feed( over.data(), over.size() );+ CHECK_EQ( reader.next( line ), OnlineLineReader::OVERSIZE );+ CHECK_EQ( reader.next( line ), OnlineLineReader::LINE );+ CHECK( line == "{\"t\":\"ok\"}" );+ CHECK_EQ( reader.next( line ), OnlineLineReader::NONE );++ // a long one arriving in chunks is reported once and thrown away up to its newline, even when the+ // newline and the next line come together+ const std::string chunk( 1000, 'c' );+ int oversize = 0, lines = 0;+ for (int i = 0; i < 30; ++i)+ {+ reader.feed( chunk.data(), chunk.size() );+ OnlineLineReader::Result r;+ while ((r = reader.next( line )) != OnlineLineReader::NONE)+ (r == OnlineLineReader::OVERSIZE ? oversize : lines)++;+ }+ reader.feed( "ccc\n{\"t\":\"after\"}\n", 18 );+ OnlineLineReader::Result r;+ while ((r = reader.next( line )) != OnlineLineReader::NONE)+ (r == OnlineLineReader::OVERSIZE ? oversize : lines)++;+ CHECK_EQ( oversize, 1 );+ CHECK_EQ( lines, 1 );+ CHECK( line == "{\"t\":\"after\"}" );+}++//-------------------------------------------------------------------------------------------------+// TLS over loopback+//-------------------------------------------------------------------------------------------------++static const char *TEST_CA_NAME = "CN=Zero Hour Reforged test CA (test only),O=test_online";++struct TestPki+{+ bool ok;+ mbedtls_entropy_context entropy;+ mbedtls_ctr_drbg_context random;+ mbedtls_pk_context caKey, otherCaKey, serverKey;+ std::string caPem, otherCaPem, serverPem;+};++static bool makeKey( mbedtls_pk_context &key, mbedtls_ctr_drbg_context &random )+{+ return mbedtls_pk_setup( &key, mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY ) ) == 0+ && mbedtls_ecp_gen_key( MBEDTLS_ECP_DP_SECP256R1, mbedtls_pk_ec( key ), mbedtls_ctr_drbg_random, &random ) == 0;+}++static std::string makeCertificate( mbedtls_pk_context &subjectKey, const char *subject, mbedtls_pk_context &issuerKey,+ const char *issuer, unsigned char serial, bool authority, mbedtls_ctr_drbg_context &random )+{+ mbedtls_x509write_cert crt;+ mbedtls_x509write_crt_init( &crt );+ unsigned char pem[ 4096 ];+ mbedtls_x509write_crt_set_version( &crt, MBEDTLS_X509_CRT_VERSION_3 );+ mbedtls_x509write_crt_set_md_alg( &crt, MBEDTLS_MD_SHA256 );+ mbedtls_x509write_crt_set_subject_key( &crt, &subjectKey );+ mbedtls_x509write_crt_set_issuer_key( &crt, &issuerKey );+ const bool ok = mbedtls_x509write_crt_set_serial_raw( &crt, &serial, 1 ) == 0+ && mbedtls_x509write_crt_set_validity( &crt, "20250101000000", "20991231235959" ) == 0+ && mbedtls_x509write_crt_set_subject_name( &crt, subject ) == 0+ && mbedtls_x509write_crt_set_issuer_name( &crt, issuer ) == 0+ && mbedtls_x509write_crt_set_basic_constraints( &crt, authority ? 1 : 0, -1 ) == 0+ && mbedtls_x509write_crt_set_key_usage( &crt, authority+ ? (MBEDTLS_X509_KU_KEY_CERT_SIGN | MBEDTLS_X509_KU_CRL_SIGN) : MBEDTLS_X509_KU_DIGITAL_SIGNATURE ) == 0+ && mbedtls_x509write_crt_pem( &crt, pem, sizeof( pem ), mbedtls_ctr_drbg_random, &random ) == 0;+ mbedtls_x509write_crt_free( &crt );+ return ok ? std::string( (const char *)pem ) : std::string();+}++// made once and kept for the run; nothing of it is written anywhere+static TestPki &pki()+{+ static TestPki p;+ static bool made = false;+ if (made)+ return p;+ made = true;+ mbedtls_entropy_init( &p.entropy );+ mbedtls_ctr_drbg_init( &p.random );+ mbedtls_pk_init( &p.caKey );+ mbedtls_pk_init( &p.otherCaKey );+ mbedtls_pk_init( &p.serverKey );+ p.ok = mbedtls_ctr_drbg_seed( &p.random, mbedtls_entropy_func, &p.entropy, NULL, 0 ) == 0+ && makeKey( p.caKey, p.random ) && makeKey( p.otherCaKey, p.random ) && makeKey( p.serverKey, p.random );+ if (p.ok)+ {+ // the other CA has the same name and only another key: refused on the signature alone+ p.caPem = makeCertificate( p.caKey, TEST_CA_NAME, p.caKey, TEST_CA_NAME, 1, true, p.random );+ p.otherCaPem = makeCertificate( p.otherCaKey, TEST_CA_NAME, p.otherCaKey, TEST_CA_NAME, 1, true, p.random );+ p.serverPem = makeCertificate( p.serverKey, "CN=127.0.0.1", p.caKey, TEST_CA_NAME, 2, false, p.random );+ p.ok = !p.caPem.empty() && !p.otherCaPem.empty() && !p.serverPem.empty();+ }+ return p;+}++/* One connection: accept, handshake, read the client's first line, answer with a scripted stream (two+ lines in one write, a long line in two writes with a pause, a nested line and an oversize one the+ client must drop, then "bye"), and wait for the client to hang up. */+struct TestServer+{+ mbedtls_net_context listener;+ mbedtls_x509_crt chain;+ unsigned short port;+ int handshake;+ std::string received;+ std::thread thread;++ TestServer() : port( 0 ), handshake( 1 ) { mbedtls_net_init( &listener ); mbedtls_x509_crt_init( &chain ); }+ ~TestServer()+ {+ if (thread.joinable())+ thread.join();+ mbedtls_net_free( &listener );+ mbedtls_x509_crt_free( &chain );+ }++ bool start()+ {+ const std::string &pem = pki().serverPem;+ if (mbedtls_x509_crt_parse( &chain, (const unsigned char *)pem.c_str(), pem.size() + 1 ) != 0+ || mbedtls_net_bind( &listener, "127.0.0.1", "0", MBEDTLS_NET_PROTO_TCP ) != 0)+ return false;+ sockaddr_in address;+ TestSockLen size = sizeof( address );+ if (getsockname( listener.fd, (sockaddr *)&address, &size ) != 0)+ return false;+ port = ntohs( address.sin_port );+ thread = std::thread( &TestServer::serve, this );+ return true;+ }++ static bool writeAll( mbedtls_ssl_context &ssl, const std::string &bytes )+ {+ size_t done = 0;+ while (done < bytes.size())+ {+ const int n = mbedtls_ssl_write( &ssl, (const unsigned char *)bytes.data() + done, bytes.size() - done );+ if (n > 0)+ done += n;+ else if (n != MBEDTLS_ERR_SSL_WANT_WRITE && n != MBEDTLS_ERR_SSL_WANT_READ)+ return false;+ }+ return true;+ }++ void serve()+ {+ mbedtls_net_context client;+ mbedtls_ssl_context ssl;+ mbedtls_ssl_config conf;+ mbedtls_entropy_context entropy;+ mbedtls_ctr_drbg_context random;+ mbedtls_net_init( &client );+ mbedtls_ssl_init( &ssl );+ mbedtls_ssl_config_init( &conf );+ mbedtls_entropy_init( &entropy );+ mbedtls_ctr_drbg_init( &random );+ if (mbedtls_ctr_drbg_seed( &random, mbedtls_entropy_func, &entropy, NULL, 0 ) == 0+ && mbedtls_net_accept( &listener, &client, NULL, 0, NULL ) == 0+ && mbedtls_ssl_config_defaults( &conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT ) == 0)+ {+ mbedtls_ssl_conf_rng( &conf, mbedtls_ctr_drbg_random, &random );+ mbedtls_ssl_conf_max_tls_version( &conf, MBEDTLS_SSL_VERSION_TLS1_2 ); // as the client; OnlineConnection.cpp says why+ mbedtls_ssl_conf_read_timeout( &conf, 5000 );+ if (mbedtls_ssl_conf_own_cert( &conf, &chain, &pki().serverKey ) == 0 && mbedtls_ssl_setup( &ssl, &conf ) == 0)+ {+ mbedtls_ssl_set_bio( &ssl, &client, mbedtls_net_send, NULL, mbedtls_net_recv_timeout );+ while ((handshake = mbedtls_ssl_handshake( &ssl )) == MBEDTLS_ERR_SSL_WANT_READ || handshake == MBEDTLS_ERR_SSL_WANT_WRITE)+ ;+ }+ }+ if (handshake == 0)+ {+ unsigned char bytes[ 1024 ];+ while (received.find( '\n' ) == std::string::npos)+ {+ const int n = mbedtls_ssl_read( &ssl, bytes, sizeof( bytes ) );+ if (n <= 0)+ break;+ received.append( (const char *)bytes, n );+ }+ const std::string big = "{\"t\":\"said\",\"text\":\"" + std::string( 8000, 'x' ) + "\"}\n";+ writeAll( ssl, "{\"t\":\"welcome\",\"motd\":\"h\\u00e9llo\",\"relayPort\":7001}\n"+ "{\"t\":\"auth.ok\",\"id\":9007199254740993,\"nick\":\"\xC3\x87" "a\xC4\x9F" "r\xC4\xB1\"}\n" );+ writeAll( ssl, big.substr( 0, 3000 ) );+ std::this_thread::sleep_for( std::chrono::milliseconds( 60 ) );+ writeAll( ssl, big.substr( 3000 ) );+ writeAll( ssl, "{\"t\":[1,[2]]}\n" + std::string( 9000, 'y' ) + "\n{\"t\":\"bye\"}\n" );+ while (mbedtls_ssl_read( &ssl, bytes, sizeof( bytes ) ) > 0)+ ; // until the client's close_notify, or five quiet seconds+ }+ mbedtls_ssl_close_notify( &ssl );+ mbedtls_net_free( &client );+ mbedtls_ssl_free( &ssl );+ mbedtls_ssl_config_free( &conf );+ mbedtls_ctr_drbg_free( &random );+ mbedtls_entropy_free( &entropy );+ }+};++// the messages that arrive until "bye" or the connection ends, ten seconds at most+static std::vector<OnlineMessage> collect( OnlineConnection &c )+{+ std::vector<OnlineMessage> got;+ const auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds( 10 );+ while (std::chrono::steady_clock::now() < give_up)+ {+ OnlineMessage m;+ while (c.receive( m ))+ got.push_back( m );+ if ((!got.empty() && got.back().type() == "bye") || c.state() == OnlineConnection::CLOSED)+ break;+ std::this_thread::sleep_for( std::chrono::milliseconds( 5 ) );+ }+ return got;+}++TEST(online_tls_loopback_against_the_test_ca)+{+ CHECK( pki().ok );+ TestServer server;+ CHECK( server.start() );+ if (!pki().ok || server.port == 0)+ return;++ OnlineConnection c;+ CHECK_EQ( c.state(), OnlineConnection::IDLE );+ CHECK( c.connect( "127.0.0.1", server.port, pki().caPem ) );+ CHECK( !c.connect( "127.0.0.1", server.port, pki().caPem ) ); // one at a time+ OnlineMessage hello;+ hello.setString( "t", "hello" ).setInt( "exe", 0x12345678 ).setInt( "ini", 0x9ABCDEF0LL ).setString( "ver", "test" );+ CHECK( c.send( hello ) ); // queued before the handshake is through, sent once it is++ const std::vector<OnlineMessage> got = collect( c );+ CHECK_EQ( got.size(), (size_t)4 );+ if (got.size() == 4)+ {+ CHECK( got[ 0 ].type() == "welcome" );+ CHECK( got[ 0 ].getString( "motd" ) == "h\xC3\xA9llo" );+ CHECK_EQ( got[ 0 ].getInt( "relayPort" ), 7001 );+ CHECK( got[ 1 ].type() == "auth.ok" );+ CHECK_EQ( got[ 1 ].getInt( "id" ), 9007199254740993LL );+ CHECK( got[ 1 ].getString( "nick" ) == "\xC3\x87" "a\xC4\x9F" "r\xC4\xB1" );+ CHECK( got[ 2 ].type() == "said" );+ CHECK_EQ( got[ 2 ].getString( "text" ).size(), (size_t)8000 );+ CHECK( got[ 3 ].type() == "bye" );+ }+ CHECK_EQ( c.droppedLines(), 2u ); // the nested one and the oversize one+ CHECK_EQ( c.state(), OnlineConnection::OPEN );+ if (!c.error().empty())+ printf( " error: %s\n", c.error().c_str() );+ CHECK( c.error().empty() );++ c.close();+ CHECK_EQ( c.state(), OnlineConnection::CLOSED );+ CHECK( c.error().empty() ); // a hang-up asked for is not an error+ CHECK( !c.send( hello ) );+ if (server.thread.joinable())+ server.thread.join();+ CHECK_EQ( server.handshake, 0 );+ OnlineMessage first;+ CHECK( !server.received.empty() && parseText( server.received.substr( 0, server.received.size() - 1 ), first ) );+ CHECK( first.type() == "hello" );+ CHECK_EQ( first.getInt( "ini" ), 0x9ABCDEF0LL );+}++TEST(online_tls_refuses_a_server_the_ca_did_not_sign)+{+ CHECK( pki().ok );+ TestServer server;+ CHECK( server.start() );+ if (!pki().ok || server.port == 0)+ return;++ OnlineConnection c;+ CHECK( c.connect( "127.0.0.1", server.port, pki().otherCaPem ) );+ OnlineMessage hello;+ hello.setString( "t", "hello" );+ c.send( hello );+ const std::vector<OnlineMessage> got = collect( c );+ CHECK( got.empty() );+ CHECK_EQ( c.state(), OnlineConnection::CLOSED );+ printf( " refused with: %s\n", c.error().c_str() );+ CHECK( c.error().find( "certificate" ) != std::string::npos );+ if (server.thread.joinable())+ server.thread.join();+ CHECK( server.handshake != 0 );+ CHECK( server.received.empty() ); // the hello never left the client+}++TEST(online_tls_refuses_a_name_the_certificate_does_not_carry)+{+ CHECK( pki().ok );+ TestServer server;+ CHECK( server.start() );+ if (!pki().ok || server.port == 0)+ return;++ OnlineConnection c;+ CHECK( c.connect( "localhost", server.port, pki().caPem ) ); // signed for 127.0.0.1, not this name+ collect( c );+ CHECK_EQ( c.state(), OnlineConnection::CLOSED );+ CHECK( c.error().find( "certificate" ) != std::string::npos );+ if (server.thread.joinable())+ server.thread.join();+}++TEST(online_connect_refuses_bad_arguments)+{+ OnlineConnection c;+ CHECK( !c.connect( "", 7000, "" ) );+ CHECK( !c.error().empty() );+ CHECK( !c.connect( "127.0.0.1", 0, "" ) );+ CHECK( !c.connect( "127.0.0.1", 7000, "-----BEGIN CERTIFICATE-----\nnot base64\n-----END CERTIFICATE-----\n" ) );+ CHECK( c.error().find( "CA" ) != std::string::npos );+ CHECK( c.state() != OnlineConnection::CONNECTING && c.state() != OnlineConnection::OPEN );++ // the built-in Let's Encrypt roots parse+ mbedtls_x509_crt roots;+ mbedtls_x509_crt_init( &roots );+ const std::string pem = OnlineConnection::defaultRoots();+ CHECK_EQ( mbedtls_x509_crt_parse( &roots, (const unsigned char *)pem.c_str(), pem.size() + 1 ), 0 );+ int count = 0;+ for (const mbedtls_x509_crt *crt = &roots; crt != NULL && crt->raw.len > 0; crt = crt->next)+ ++count;+ CHECK_EQ( count, 2 );+ mbedtls_x509_crt_free( &roots );+}diff --git a/GeneralsMD/Code/Tools/vendor.ps1 b/GeneralsMD/Code/Tools/vendor.ps1index 4e055d622..5b8c42ee9 100644--- a/GeneralsMD/Code/Tools/vendor.ps1+++ b/GeneralsMD/Code/Tools/vendor.ps1@@ -37,7 +37,7 @@ function Expand-Source($archive, $name) {if (Test-Path $target) { Remove-Item -Recurse -Force $target }New-Item -ItemType Directory -Force -Path $target | Out-NullStep "unpacking $name"- if ($archive.EndsWith('.tar.gz')) {+ if ($archive -match '\.tar\.(gz|bz2)$') {tar -xf $archive -C $target} else {Expand-Archive -Path $archive -DestinationPath $target -Force@@ -152,6 +152,33 @@ function Install-Miniaudio {Step "miniaudio 0.11.25 -> Libraries\Source\miniaudio"}+# --- mbedTLS 3.6.7 (Apache-2.0), the long-term-support line: the TLS under the online service's lobby+# connection (GameNetwork\Online), the same pin as vendor.sh. The tarball is checked against the sha256+# the release publishes beside it. Only include\, library\ and the licence are copied; CMakeLists.txt+# compiles library\*.c itself, so upstream's build, programs and tests stay out.+function Install-Mbedtls {+ $destination = Join-Path $libraries 'Source\mbedtls'+ $versionHeader = Join-Path $destination 'include\mbedtls\build_info.h'+ if ((Test-Path $versionHeader) -and -not $Force -and+ (Select-String -LiteralPath $versionHeader -Pattern 'MBEDTLS_VERSION_STRING "3.6.7"' -SimpleMatch -Quiet)) { return }+ $sha = 'A7E8BCBEC0E6F761B4AF24F25677626B35F762F68EEF79C08677A363212D11F6'+ $archive = Get-File 'https://github.com/Mbed-TLS/mbedtls/releases/download/mbedtls-3.6.7/mbedtls-3.6.7.tar.bz2' (Join-Path $work 'mbedtls-3.6.7.tar.bz2')+ $hash = (Get-FileHash $archive -Algorithm SHA256).Hash+ if ($hash -ne $sha) {+ Remove-Item $archive -ErrorAction SilentlyContinue+ throw "mbedtls-3.6.7.tar.bz2 downloaded with hash $hash, and the release was published as $sha"+ }+ $source = Expand-Source $archive 'mbedtls'+ # folder by folder, so the committed .gitignore stays+ foreach ($name in @('include', 'library')) {+ $target = Join-Path $destination $name+ if (Test-Path $target) { Remove-Item -Recurse -Force $target }+ Copy-Item (Join-Path $source $name) $target -Recurse -Force+ }+ Copy-Item (Join-Path $source 'LICENSE') (Join-Path $destination 'LICENSE') -Force+ Step "mbedTLS 3.6.7 -> Libraries\Source\mbedtls"+}+# --- The fork's own upscaled art: every 3D texture at twice its size, and the ground. Not in git -# ReforgedTextures.big alone is a gigabyte, ten times# what GitHub takes in a file, and LFS in a fork is billed to the parent repository.@@ -259,6 +286,7 @@ Install-LzhlPatchInstall-DirectXInstall-GameSpyInstall-Miniaudio+Install-Mbedtls# SDL3 is the platform layer for everything that is not Windows (decision 3 in PORTING.md). Windows# keeps Win32Device, so it is not fetched here; vendor.sh fetches it, and says it skips DirectX the# same way. The same holds for SDL3's Metal patch, Libraries\Source\sdl3-metal-windowless.patch:diff --git a/GeneralsMD/Code/Tools/vendor.sh b/GeneralsMD/Code/Tools/vendor.shindex 4eeb1513a..0d32c6cdd 100755--- a/GeneralsMD/Code/Tools/vendor.sh+++ b/GeneralsMD/Code/Tools/vendor.sh@@ -89,7 +89,7 @@ expand_source() { # archive name -> prints the unpacked rootmkdir -p "$target"step "unpacking $name"case "$archive" in- *.tar.gz) tar -xf "$archive" -C "$target" || { echo "[vendor] ERROR: could not unpack $archive" >&2; return 1; } ;;+ *.tar.gz|*.tar.bz2) tar -xf "$archive" -C "$target" || { echo "[vendor] ERROR: could not unpack $archive" >&2; return 1; } ;;*) unzip -qo "$archive" -d "$target" || { echo "[vendor] ERROR: could not unpack $archive" >&2; return 1; } ;;esaclocal entry count=0 only=@@ -615,6 +615,28 @@ install_ffmpeg() {step "FFmpeg 8.1.2 (source tarball) -> Libraries/Source/FFmpeg"}+# --- mbedTLS 3.6.7 (Apache-2.0), the long-term-support line: the TLS under the online service's lobby+# connection (GameNetwork/Online), the same pin as vendor.ps1, on every platform. The tarball is checked+# against the sha256 the release publishes beside it. Only include/, library/ and the licence are copied;+# CMakeLists.txt compiles library/*.c itself, so upstream's build, programs and tests stay out.+install_mbedtls() {+ local destination="$libraries/Source/mbedtls"+ if [ -e "$destination/include/mbedtls/build_info.h" ] && [ -z "$force" ] \+ && grep -q 'MBEDTLS_VERSION_STRING "3.6.7"' "$destination/include/mbedtls/build_info.h"; then return 0; fi+ local sha='a7e8bcbec0e6f761b4af24f25677626b35f762f68eef79c08677a363212d11f6'+ local archive source hash+ archive=$(get_file 'https://github.com/Mbed-TLS/mbedtls/releases/download/mbedtls-3.6.7/mbedtls-3.6.7.tar.bz2' "$work/mbedtls-3.6.7.tar.bz2")+ hash=$(sha256_of "$archive")+ if [ "$hash" != "$sha" ]; then+ rm -f "$archive"+ echo "[vendor] ERROR: mbedtls-3.6.7.tar.bz2 has hash $hash, and the release was published as $sha" >&2+ exit 1+ fi+ source=$(expand_source "$archive" 'mbedtls')+ copy_entries "$source" "$destination" include library LICENSE+ step "mbedTLS 3.6.7 -> Libraries/Source/mbedtls"+}+get_channel_url() {if [ -n "${ZHR_CHANNEL_URL:-}" ]; then printf '%s/\n' "${ZHR_CHANNEL_URL%/}"; return 0; filocal launcher@@ -728,5 +750,6 @@ install_spirv_crossinstall_shadercrossinstall_freetypeinstall_ffmpeg+install_mbedtlsinstall_artstep 'everything the build needs is in place'